ESPHome  2024.11.0
xiaomi_ble.cpp
Go to the documentation of this file.
1 #include "xiaomi_ble.h"
2 #include "esphome/core/helpers.h"
3 #include "esphome/core/log.h"
4 
5 #ifdef USE_ESP32
6 
7 #include <vector>
8 #include "mbedtls/ccm.h"
9 
10 namespace esphome {
11 namespace xiaomi_ble {
12 
13 static const char *const TAG = "xiaomi_ble";
14 
15 bool parse_xiaomi_value(uint16_t value_type, const uint8_t *data, uint8_t value_length, XiaomiParseResult &result) {
16  // button pressed, 3 bytes, only byte 3 is used for supported devices so far
17  if ((value_type == 0x1001) && (value_length == 3)) {
18  result.button_press = data[2] == 0;
19  return true;
20  }
21  // motion detection, 1 byte, 8-bit unsigned integer
22  else if ((value_type == 0x0003) && (value_length == 1)) {
23  result.has_motion = data[0];
24  }
25  // temperature, 2 bytes, 16-bit signed integer (LE), 0.1 °C
26  else if ((value_type == 0x1004) && (value_length == 2)) {
27  const int16_t temperature = encode_uint16(data[1], data[0]);
28  result.temperature = temperature / 10.0f;
29  }
30  // humidity, 2 bytes, 16-bit signed integer (LE), 0.1 %
31  else if ((value_type == 0x1006) && (value_length == 2)) {
32  const int16_t humidity = encode_uint16(data[1], data[0]);
33  result.humidity = humidity / 10.0f;
34  }
35  // illuminance (+ motion), 3 bytes, 24-bit unsigned integer (LE), 1 lx
36  else if (((value_type == 0x1007) || (value_type == 0x000F)) && (value_length == 3)) {
37  const uint32_t illuminance = encode_uint24(data[2], data[1], data[0]);
38  result.illuminance = illuminance;
39  result.is_light = illuminance >= 100;
40  if (value_type == 0x0F)
41  result.has_motion = true;
42  }
43  // soil moisture, 1 byte, 8-bit unsigned integer, 1 %
44  else if ((value_type == 0x1008) && (value_length == 1)) {
45  result.moisture = data[0];
46  }
47  // conductivity, 2 bytes, 16-bit unsigned integer (LE), 1 µS/cm
48  else if ((value_type == 0x1009) && (value_length == 2)) {
49  const uint16_t conductivity = encode_uint16(data[1], data[0]);
50  result.conductivity = conductivity;
51  }
52  // battery / MiaoMiaoce battery, 1 byte, 8-bit unsigned integer, 1 %
53  else if ((value_type == 0x100A || value_type == 0x4803) && (value_length == 1)) {
54  result.battery_level = data[0];
55  }
56  // temperature + humidity, 4 bytes, 16-bit signed integer (LE) each, 0.1 °C, 0.1 %
57  else if ((value_type == 0x100D) && (value_length == 4)) {
58  const int16_t temperature = encode_uint16(data[1], data[0]);
59  const int16_t humidity = encode_uint16(data[3], data[2]);
60  result.temperature = temperature / 10.0f;
61  result.humidity = humidity / 10.0f;
62  }
63  // formaldehyde, 2 bytes, 16-bit unsigned integer (LE), 0.01 mg / m3
64  else if ((value_type == 0x1010) && (value_length == 2)) {
65  const uint16_t formaldehyde = encode_uint16(data[1], data[0]);
66  result.formaldehyde = formaldehyde / 100.0f;
67  }
68  // on/off state, 1 byte, 8-bit unsigned integer
69  else if ((value_type == 0x1012) && (value_length == 1)) {
70  result.is_active = data[0];
71  }
72  // mosquito tablet, 1 byte, 8-bit unsigned integer, 1 %
73  else if ((value_type == 0x1013) && (value_length == 1)) {
74  result.tablet = data[0];
75  }
76  // idle time since last motion, 4 byte, 32-bit unsigned integer, 1 min
77  else if ((value_type == 0x1017) && (value_length == 4)) {
78  const uint32_t idle_time = encode_uint32(data[3], data[2], data[1], data[0]);
79  result.idle_time = idle_time / 60.0f;
80  result.has_motion = !idle_time;
81  } else if ((value_type == 0x1018) && (value_length == 1)) {
82  result.is_light = data[0];
83  }
84  // MiaoMiaoce temperature, 4 bytes, float, 0.1 °C
85  else if ((value_type == 0x4C01) && (value_length == 4)) {
86  const uint32_t int_number = encode_uint32(data[3], data[2], data[1], data[0]);
87  float temperature;
88  std::memcpy(&temperature, &int_number, sizeof(temperature));
89  result.temperature = temperature;
90  }
91  // MiaoMiaoce humidity, 1 byte, 8-bit unsigned integer, 1 %
92  else if ((value_type == 0x4C02) && (value_length == 1)) {
93  result.humidity = data[0];
94  } else {
95  return false;
96  }
97 
98  return true;
99 }
100 
101 bool parse_xiaomi_message(const std::vector<uint8_t> &message, XiaomiParseResult &result) {
102  result.has_encryption = message[0] & 0x08; // update encryption status
103  if (result.has_encryption) {
104  ESP_LOGVV(TAG, "parse_xiaomi_message(): payload is encrypted, stop reading message.");
105  return false;
106  }
107 
108  // Data point specs
109  // Byte 0: type
110  // Byte 1: fixed 0x10
111  // Byte 2: length
112  // Byte 3..3+len-1: data point value
113 
114  const uint8_t *payload = message.data() + result.raw_offset;
115  uint8_t payload_length = message.size() - result.raw_offset;
116  uint8_t payload_offset = 0;
117  bool success = false;
118 
119  if (payload_length < 4) {
120  ESP_LOGVV(TAG, "parse_xiaomi_message(): payload has wrong size (%d)!", payload_length);
121  return false;
122  }
123 
124  while (payload_length > 3) {
125  if (payload[payload_offset + 1] != 0x10 && payload[payload_offset + 1] != 0x00 &&
126  payload[payload_offset + 1] != 0x4C && payload[payload_offset + 1] != 0x48) {
127  ESP_LOGVV(TAG, "parse_xiaomi_message(): fixed byte not found, stop parsing residual data.");
128  break;
129  }
130 
131  const uint8_t value_length = payload[payload_offset + 2];
132  if ((value_length < 1) || (value_length > 4) || (payload_length < (3 + value_length))) {
133  ESP_LOGVV(TAG, "parse_xiaomi_message(): value has wrong size (%d)!", value_length);
134  break;
135  }
136 
137  const uint16_t value_type = encode_uint16(payload[payload_offset + 1], payload[payload_offset + 0]);
138  const uint8_t *data = &payload[payload_offset + 3];
139 
140  if (parse_xiaomi_value(value_type, data, value_length, result))
141  success = true;
142 
143  payload_length -= 3 + value_length;
144  payload_offset += 3 + value_length;
145  }
146 
147  return success;
148 }
149 
151  XiaomiParseResult result;
152  if (!service_data.uuid.contains(0x95, 0xFE)) {
153  ESP_LOGVV(TAG, "parse_xiaomi_header(): no service data UUID magic bytes.");
154  return {};
155  }
156 
157  auto raw = service_data.data;
158  result.has_data = raw[0] & 0x40;
159  result.has_capability = raw[0] & 0x20;
160  result.has_encryption = raw[0] & 0x08;
161 
162  if (!result.has_data) {
163  ESP_LOGVV(TAG, "parse_xiaomi_header(): service data has no DATA flag.");
164  return {};
165  }
166 
167  static uint8_t last_frame_count = 0;
168  if (last_frame_count == raw[4]) {
169  ESP_LOGVV(TAG, "parse_xiaomi_header(): duplicate data packet received (%d).", static_cast<int>(last_frame_count));
170  result.is_duplicate = true;
171  return {};
172  }
173  last_frame_count = raw[4];
174  result.is_duplicate = false;
175  result.raw_offset = result.has_capability ? 12 : 11;
176 
177  const uint16_t device_uuid = encode_uint16(raw[3], raw[2]);
178 
179  if (device_uuid == 0x0098) { // MiFlora
181  result.name = "HHCCJCY01";
182  } else if (device_uuid == 0x01aa) { // round body, segment LCD
184  result.name = "LYWSDCGQ";
185  } else if (device_uuid == 0x015d) { // FlowerPot, RoPot
187  result.name = "HHCCPOT002";
188  } else if (device_uuid == 0x02df) { // Xiaomi (Honeywell) formaldehyde sensor, OLED display
190  result.name = "JQJCY01YM";
191  } else if (device_uuid == 0x03dd) { // Philips/Xiaomi BLE nightlight
193  result.name = "MUE4094RT";
194  result.raw_offset -= 6;
195  } else if (device_uuid == 0x0347 || // ClearGrass-branded, round body, e-ink display
196  device_uuid == 0x0B48) { // Qingping-branded, round body, e-ink display — with bindkeys
198  result.name = "CGG1";
199  } else if (device_uuid == 0x03bc) { // VegTrug Grow Care Garden
201  result.name = "GCLS002";
202  } else if (device_uuid == 0x045b) { // rectangular body, e-ink display
204  result.name = "LYWSD02";
205  } else if (device_uuid == 0x2542) { // rectangular body, e-ink display — with bindkeys
207  result.name = "LYWSD02MMC";
208  if (raw.size() == 19)
209  result.raw_offset -= 6;
210  } else if (device_uuid == 0x040a) { // Mosquito Repellent Smart Version
212  result.name = "WX08ZM";
213  } else if (device_uuid == 0x0576) { // Cleargrass (Qingping) alarm clock, segment LCD
215  result.name = "CGD1";
216  } else if (device_uuid == 0x066F) { // Cleargrass (Qingping) Temp & RH Lite
218  result.name = "CGDK2";
219  } else if (device_uuid == 0x055b) { // small square body, segment LCD, encrypted
221  result.name = "LYWSD03MMC";
222  } else if (device_uuid == 0x07f6) { // Xiaomi-Yeelight BLE nightlight
224  result.name = "MJYD02YLA";
225  if (raw.size() == 19)
226  result.raw_offset -= 6;
227  } else if (device_uuid == 0x06d3) { // rectangular body, e-ink display with alarm
229  result.name = "MHOC303";
230  } else if (device_uuid == 0x0387) { // square body, e-ink display
232  result.name = "MHOC401";
233  } else if (device_uuid == 0x0A83) { // Qingping-branded, motion & ambient light sensor
235  result.name = "CGPR1";
236  if (raw.size() == 19)
237  result.raw_offset -= 6;
238  } else if (device_uuid == 0x0A8D) { // Xiaomi Mi Motion Sensor 2
240  result.name = "RTCGQ02LM";
241  if (raw.size() == 19)
242  result.raw_offset -= 6;
243  } else {
244  ESP_LOGVV(TAG, "parse_xiaomi_header(): unknown device, no magic bytes.");
245  return {};
246  }
247 
248  return result;
249 }
250 
251 bool decrypt_xiaomi_payload(std::vector<uint8_t> &raw, const uint8_t *bindkey, const uint64_t &address) {
252  if (!((raw.size() == 19) || ((raw.size() >= 22) && (raw.size() <= 24)))) {
253  ESP_LOGVV(TAG, "decrypt_xiaomi_payload(): data packet has wrong size (%d)!", raw.size());
254  ESP_LOGVV(TAG, " Packet : %s", format_hex_pretty(raw.data(), raw.size()).c_str());
255  return false;
256  }
257 
258  uint8_t mac_reverse[6] = {0};
259  mac_reverse[5] = (uint8_t) (address >> 40);
260  mac_reverse[4] = (uint8_t) (address >> 32);
261  mac_reverse[3] = (uint8_t) (address >> 24);
262  mac_reverse[2] = (uint8_t) (address >> 16);
263  mac_reverse[1] = (uint8_t) (address >> 8);
264  mac_reverse[0] = (uint8_t) (address >> 0);
265 
266  XiaomiAESVector vector{.key = {0},
267  .plaintext = {0},
268  .ciphertext = {0},
269  .authdata = {0x11},
270  .iv = {0},
271  .tag = {0},
272  .keysize = 16,
273  .authsize = 1,
274  .datasize = 0,
275  .tagsize = 4,
276  .ivsize = 12};
277 
278  vector.datasize = (raw.size() == 19) ? raw.size() - 12 : raw.size() - 18;
279  int cipher_pos = (raw.size() == 19) ? 5 : 11;
280 
281  const uint8_t *v = raw.data();
282 
283  memcpy(vector.key, bindkey, vector.keysize);
284  memcpy(vector.ciphertext, v + cipher_pos, vector.datasize);
285  memcpy(vector.tag, v + raw.size() - vector.tagsize, vector.tagsize);
286  memcpy(vector.iv, mac_reverse, 6); // MAC address reverse
287  memcpy(vector.iv + 6, v + 2, 3); // sensor type (2) + packet id (1)
288  memcpy(vector.iv + 9, v + raw.size() - 7, 3); // payload counter
289 
290  mbedtls_ccm_context ctx;
291  mbedtls_ccm_init(&ctx);
292 
293  int ret = mbedtls_ccm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, vector.key, vector.keysize * 8);
294  if (ret) {
295  ESP_LOGVV(TAG, "decrypt_xiaomi_payload(): mbedtls_ccm_setkey() failed.");
296  mbedtls_ccm_free(&ctx);
297  return false;
298  }
299 
300  ret = mbedtls_ccm_auth_decrypt(&ctx, vector.datasize, vector.iv, vector.ivsize, vector.authdata, vector.authsize,
301  vector.ciphertext, vector.plaintext, vector.tag, vector.tagsize);
302  if (ret) {
303  uint8_t mac_address[6] = {0};
304  memcpy(mac_address, mac_reverse + 5, 1);
305  memcpy(mac_address + 1, mac_reverse + 4, 1);
306  memcpy(mac_address + 2, mac_reverse + 3, 1);
307  memcpy(mac_address + 3, mac_reverse + 2, 1);
308  memcpy(mac_address + 4, mac_reverse + 1, 1);
309  memcpy(mac_address + 5, mac_reverse, 1);
310  ESP_LOGVV(TAG, "decrypt_xiaomi_payload(): authenticated decryption failed.");
311  ESP_LOGVV(TAG, " MAC address : %s", format_hex_pretty(mac_address, 6).c_str());
312  ESP_LOGVV(TAG, " Packet : %s", format_hex_pretty(raw.data(), raw.size()).c_str());
313  ESP_LOGVV(TAG, " Key : %s", format_hex_pretty(vector.key, vector.keysize).c_str());
314  ESP_LOGVV(TAG, " Iv : %s", format_hex_pretty(vector.iv, vector.ivsize).c_str());
315  ESP_LOGVV(TAG, " Cipher : %s", format_hex_pretty(vector.ciphertext, vector.datasize).c_str());
316  ESP_LOGVV(TAG, " Tag : %s", format_hex_pretty(vector.tag, vector.tagsize).c_str());
317  mbedtls_ccm_free(&ctx);
318  return false;
319  }
320 
321  // replace encrypted payload with plaintext
322  uint8_t *p = vector.plaintext;
323  for (std::vector<uint8_t>::iterator it = raw.begin() + cipher_pos; it != raw.begin() + cipher_pos + vector.datasize;
324  ++it) {
325  *it = *(p++);
326  }
327 
328  // clear encrypted flag
329  raw[0] &= ~0x08;
330 
331  ESP_LOGVV(TAG, "decrypt_xiaomi_payload(): authenticated decryption passed.");
332  ESP_LOGVV(TAG, " Plaintext : %s, Packet : %d", format_hex_pretty(raw.data() + cipher_pos, vector.datasize).c_str(),
333  static_cast<int>(raw[4]));
334 
335  mbedtls_ccm_free(&ctx);
336  return true;
337 }
338 
339 bool report_xiaomi_results(const optional<XiaomiParseResult> &result, const std::string &address) {
340  if (!result.has_value()) {
341  ESP_LOGVV(TAG, "report_xiaomi_results(): no results available.");
342  return false;
343  }
344 
345  ESP_LOGD(TAG, "Got Xiaomi %s (%s):", result->name.c_str(), address.c_str());
346 
347  if (result->temperature.has_value()) {
348  ESP_LOGD(TAG, " Temperature: %.1f°C", *result->temperature);
349  }
350  if (result->humidity.has_value()) {
351  ESP_LOGD(TAG, " Humidity: %.1f%%", *result->humidity);
352  }
353  if (result->battery_level.has_value()) {
354  ESP_LOGD(TAG, " Battery Level: %.0f%%", *result->battery_level);
355  }
356  if (result->conductivity.has_value()) {
357  ESP_LOGD(TAG, " Conductivity: %.0fµS/cm", *result->conductivity);
358  }
359  if (result->illuminance.has_value()) {
360  ESP_LOGD(TAG, " Illuminance: %.0flx", *result->illuminance);
361  }
362  if (result->moisture.has_value()) {
363  ESP_LOGD(TAG, " Moisture: %.0f%%", *result->moisture);
364  }
365  if (result->tablet.has_value()) {
366  ESP_LOGD(TAG, " Mosquito tablet: %.0f%%", *result->tablet);
367  }
368  if (result->is_active.has_value()) {
369  ESP_LOGD(TAG, " Repellent: %s", (*result->is_active) ? "on" : "off");
370  }
371  if (result->has_motion.has_value()) {
372  ESP_LOGD(TAG, " Motion: %s", (*result->has_motion) ? "yes" : "no");
373  }
374  if (result->is_light.has_value()) {
375  ESP_LOGD(TAG, " Light: %s", (*result->is_light) ? "on" : "off");
376  }
377  if (result->button_press.has_value()) {
378  ESP_LOGD(TAG, " Button: %s", (*result->button_press) ? "pressed" : "");
379  }
380 
381  return true;
382 }
383 
385  // Previously the message was parsed twice per packet, once by XiaomiListener::parse_device()
386  // and then again by the respective device class's parse_device() function. Parsing the header
387  // here and then for each device seems to be unnecessary and complicates the duplicate packet filtering.
388  // Hence I disabled the call to parse_xiaomi_header() here and the message parsing is done entirely
389  // in the respective device instance. The XiaomiListener class is defined in __init__.py and I was not
390  // able to remove it entirely.
391 
392  return false; // with true it's not showing device scans
393 }
394 
395 } // namespace xiaomi_ble
396 } // namespace esphome
397 
398 #endif
uint8_t raw[35]
Definition: bl0939.h:19
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:364
bool parse_xiaomi_value(uint16_t value_type, const uint8_t *data, uint8_t value_length, XiaomiParseResult &result)
Definition: xiaomi_ble.cpp:15
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition: helpers.h:187
bool has_value() const
Definition: optional.h:87
bool decrypt_xiaomi_payload(std::vector< uint8_t > &raw, const uint8_t *bindkey, const uint64_t &address)
Definition: xiaomi_ble.cpp:251
constexpr uint32_t encode_uint24(uint8_t byte1, uint8_t byte2, uint8_t byte3)
Encode a 24-bit value given three bytes in most to least significant byte order.
Definition: helpers.h:192
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
Definition: xiaomi_ble.cpp:384
uint16_t temperature
Definition: sun_gtil2.cpp:26
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition: helpers.h:183
bool parse_xiaomi_message(const std::vector< uint8_t > &message, XiaomiParseResult &result)
Definition: xiaomi_ble.cpp:101
optional< XiaomiParseResult > parse_xiaomi_header(const esp32_ble_tracker::ServiceData &service_data)
Definition: xiaomi_ble.cpp:150
bool report_xiaomi_results(const optional< XiaomiParseResult > &result, const std::string &address)
Definition: xiaomi_ble.cpp:339
bool contains(uint8_t data1, uint8_t data2) const
Definition: ble_uuid.cpp:126
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
uint8_t address
Definition: bl0906.h:211
enum esphome::xiaomi_ble::XiaomiParseResult::@142 type