From https://www.debashishsahu.com/posts/esp32-communicating-with-xiaomi-flora-plant-sensor-using-ble/
Using ESP32 to communicate with Xiaomi flora (miflora) plant sensor using BLE and posting the values on MQTT server. I also demonstrate the use of Home Assistant miflora sensor component.
Change ESP32 Partition: https://desire.giesecke.tk/index.php/2018/04/20/change-partition-size-arduino-ide/ Home Assistant miflora sensor: https://www.home-assistant.io/components/sensor.miflora/
GitHub: sidddy/flora
Archived code from https://github.com/sidddy/flora below
config.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// array of different xiaomi flora MAC addresses char* FLORA_DEVICES[] = { "C4:7C:8D:67:11:11", "C4:7C:8D:67:22:22", "C4:7C:8D:67:33:33" }; // sleep between to runs in seconds #define SLEEP_DURATION 30 * 60 // emergency hibernate countdown in seconds #define EMERGENCY_HIBERNATE 3 * 60 // how often should the battery be read - in run count #define BATTERY_INTERVAL 6 // how often should a device be retried in a run when something fails #define RETRY 3 const char* WIFI_SSID = "ssid"; const char* WIFI_PASSWORD = "password"; // MQTT topic gets defined by "<MQTT_BASE_TOPIC>/<MAC_ADDRESS>/<property>" // where MAC_ADDRESS is one of the values from FLORA_DEVICES array // property is either temperature, moisture, conductivity, light or battery const char* MQTT_HOST = "10.10.10.1"; //set to your actual server address const int MQTT_PORT = 1883; const char* MQTT_CLIENTID = "miflora-client"; const char* MQTT_USERNAME = "username"; const char* MQTT_PASSWORD = "password"; const String MQTT_BASE_TOPIC = "flora"; const int MQTT_RETRY_WAIT = 5000; |
flora.ino
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
/** A BLE client for the Xiaomi Mi Plant Sensor, pushing measurements to an MQTT server. See https://github.com/nkolban/esp32-snippets/blob/master/Documentation/BLE%20C%2B%2B%20Guide.pdf on how bluetooth low energy and the library used are working. See https://github.com/ChrisScheffler/miflora/wiki/The-Basics for details on how the protocol is working. MIT License Copyright (c) 2017 Sven Henkel Multiple units reading by Grega Lebar 2018 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "BLEDevice.h" #include <WiFi.h> #include <PubSubClient.h> #include "config.h" // boot count used to check if battery status should be read RTC_DATA_ATTR int bootCount = 0; // device count static int deviceCount = sizeof FLORA_DEVICES / sizeof FLORA_DEVICES[0]; // the remote service we wish to connect to static BLEUUID serviceUUID("00001204-0000-1000-8000-00805f9b34fb"); // the characteristic of the remote service we are interested in static BLEUUID uuid_version_battery("00001a02-0000-1000-8000-00805f9b34fb"); static BLEUUID uuid_sensor_data("00001a01-0000-1000-8000-00805f9b34fb"); static BLEUUID uuid_write_mode("00001a00-0000-1000-8000-00805f9b34fb"); TaskHandle_t hibernateTaskHandle = NULL; WiFiClient espClient; PubSubClient client(espClient); void connectWifi() { Serial.println("Connecting to WiFi..."); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println(""); } void disconnectWifi() { WiFi.disconnect(true); Serial.println("WiFi disonnected"); } void connectMqtt() { Serial.println("Connecting to MQTT..."); client.setServer(MQTT_HOST, MQTT_PORT); while (!client.connected()) { if (!client.connect(MQTT_CLIENTID, MQTT_USERNAME, MQTT_PASSWORD)) { Serial.print("MQTT connection failed:"); Serial.print(client.state()); Serial.println("Retrying..."); delay(MQTT_RETRY_WAIT); } } Serial.println("MQTT connected"); Serial.println(""); } void disconnectMqtt() { client.disconnect(); Serial.println("MQTT disconnected"); } BLEClient* getFloraClient(BLEAddress floraAddress) { BLEClient* floraClient = BLEDevice::createClient(); if (!floraClient->connect(floraAddress)) { Serial.println("- Connection failed, skipping"); return nullptr; } Serial.println("- Connection successful"); return floraClient; } BLERemoteService* getFloraService(BLEClient* floraClient) { BLERemoteService* floraService = nullptr; try { floraService = floraClient->getService(serviceUUID); } catch (...) { // something went wrong } if (floraService == nullptr) { Serial.println("- Failed to find data service"); } else { Serial.println("- Found data service"); } return floraService; } bool forceFloraServiceDataMode(BLERemoteService* floraService) { BLERemoteCharacteristic* floraCharacteristic; // get device mode characteristic, needs to be changed to read data Serial.println("- Force device in data mode"); floraCharacteristic = nullptr; try { floraCharacteristic = floraService->getCharacteristic(uuid_write_mode); } catch (...) { // something went wrong } if (floraCharacteristic == nullptr) { Serial.println("-- Failed, skipping device"); return false; } // write the magic data uint8_t buf[2] = {0xA0, 0x1F}; floraCharacteristic->writeValue(buf, 2, true); delay(500); return true; } bool readFloraDataCharacteristic(BLERemoteService* floraService, String baseTopic) { BLERemoteCharacteristic* floraCharacteristic = nullptr; // get the main device data characteristic Serial.println("- Access characteristic from device"); try { floraCharacteristic = floraService->getCharacteristic(uuid_sensor_data); } catch (...) { // something went wrong } if (floraCharacteristic == nullptr) { Serial.println("-- Failed, skipping device"); return false; } // read characteristic value Serial.println("- Read value from characteristic"); std::string value; try{ value = floraCharacteristic->readValue(); } catch (...) { // something went wrong Serial.println("-- Failed, skipping device"); return false; } const char *val = value.c_str(); Serial.print("Hex: "); for (int i = 0; i < 16; i++) { Serial.print((int)val[i], HEX); Serial.print(" "); } Serial.println(" "); int16_t* temp_raw = (int16_t*)val; float temperature = (*temp_raw) / ((float)10.0); Serial.print("-- Temperature: "); Serial.println(temperature); int moisture = val[7]; Serial.print("-- Moisture: "); Serial.println(moisture); int light = val[3] + val[4] * 256; Serial.print("-- Light: "); Serial.println(light); int conductivity = val[8] + val[9] * 256; Serial.print("-- Conductivity: "); Serial.println(conductivity); if (temperature > 200) { Serial.println("-- Unreasonable values received, skip publish"); return false; } char buffer[64]; snprintf(buffer, 64, "%f", temperature); client.publish((baseTopic + "temperature").c_str(), buffer); snprintf(buffer, 64, "%d", moisture); client.publish((baseTopic + "moisture").c_str(), buffer); snprintf(buffer, 64, "%d", light); client.publish((baseTopic + "light").c_str(), buffer); snprintf(buffer, 64, "%d", conductivity); client.publish((baseTopic + "conductivity").c_str(), buffer); return true; } bool readFloraBatteryCharacteristic(BLERemoteService* floraService, String baseTopic) { BLERemoteCharacteristic* floraCharacteristic = nullptr; // get the device battery characteristic Serial.println("- Access battery characteristic from device"); try { floraCharacteristic = floraService->getCharacteristic(uuid_version_battery); } catch (...) { // something went wrong } if (floraCharacteristic == nullptr) { Serial.println("-- Failed, skipping battery level"); return false; } // read characteristic value Serial.println("- Read value from characteristic"); std::string value; try{ value = floraCharacteristic->readValue(); } catch (...) { // something went wrong Serial.println("-- Failed, skipping battery level"); return false; } const char *val2 = value.c_str(); int battery = val2[0]; char buffer[64]; Serial.print("-- Battery: "); Serial.println(battery); snprintf(buffer, 64, "%d", battery); client.publish((baseTopic + "battery").c_str(), buffer); return true; } bool processFloraService(BLERemoteService* floraService, char* deviceMacAddress, bool readBattery) { // set device in data mode if (!forceFloraServiceDataMode(floraService)) { return false; } String baseTopic = MQTT_BASE_TOPIC + "/" + deviceMacAddress + "/"; bool dataSuccess = readFloraDataCharacteristic(floraService, baseTopic); bool batterySuccess = true; if (readBattery) { batterySuccess = readFloraBatteryCharacteristic(floraService, baseTopic); } return dataSuccess && batterySuccess; } bool processFloraDevice(BLEAddress floraAddress, char* deviceMacAddress, bool getBattery, int tryCount) { Serial.print("Processing Flora device at "); Serial.print(floraAddress.toString().c_str()); Serial.print(" (try "); Serial.print(tryCount); Serial.println(")"); // connect to flora ble server BLEClient* floraClient = getFloraClient(floraAddress); if (floraClient == nullptr) { return false; } // connect data service BLERemoteService* floraService = getFloraService(floraClient); if (floraService == nullptr) { floraClient->disconnect(); return false; } // process devices data bool success = processFloraService(floraService, deviceMacAddress, getBattery); // disconnect from device floraClient->disconnect(); return success; } void hibernate() { esp_sleep_enable_timer_wakeup(SLEEP_DURATION * 1000000ll); Serial.println("Going to sleep now."); delay(100); esp_deep_sleep_start(); } void delayedHibernate(void *parameter) { delay(EMERGENCY_HIBERNATE*1000); // delay for five minutes Serial.println("Something got stuck, entering emergency hibernate..."); hibernate(); } void setup() { // all action is done when device is woken up Serial.begin(115200); delay(1000); // increase boot count bootCount++; // create a hibernate task in case something gets stuck xTaskCreate(delayedHibernate, "hibernate", 4096, NULL, 1, &hibernateTaskHandle); Serial.println("Initialize BLE client..."); BLEDevice::init(""); BLEDevice::setPower(ESP_PWR_LVL_P7); // connecting wifi and mqtt server connectWifi(); connectMqtt(); // check if battery status should be read - based on boot count bool readBattery = ((bootCount % BATTERY_INTERVAL) == 0); // process devices for (int i=0; i<deviceCount; i++) { int tryCount = 0; char* deviceMacAddress = FLORA_DEVICES[i]; BLEAddress floraAddress(deviceMacAddress); while (tryCount < RETRY) { tryCount++; if (processFloraDevice(floraAddress, deviceMacAddress, readBattery, tryCount)) { break; } delay(1000); } delay(1500); } // disconnect wifi and mqtt disconnectWifi(); disconnectMqtt(); // delete emergency hibernate task vTaskDelete(hibernateTaskHandle); // go to sleep now hibernate(); } void loop() { /// we're not doing anything in the loop, only on device wakeup delay(10000); } raspberry pi ESP32 MQTT Home Assistant |