13#include <esp_idf_version.h>
14#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
15#include <psa/crypto.h>
16#define XIAOMI_CRYPTO_PSA
19#ifndef XIAOMI_CRYPTO_PSA
28static constexpr size_t XIAOMI_MAX_LOG_BYTES = 32;
32 if ((value_type == 0x1001) && (value_length == 3)) {
37 else if ((value_type == 0x0003) && (value_length == 1)) {
41 else if ((value_type == 0x1004) && (value_length == 2)) {
46 else if ((value_type == 0x1006) && (value_length == 2)) {
51 else if (((value_type == 0x1007) || (value_type == 0x000F)) && (value_length == 3)) {
54 result.
is_light = illuminance >= 100;
55 if (value_type == 0x0F)
59 else if ((value_type == 0x1008) && (value_length == 1)) {
63 else if ((value_type == 0x1009) && (value_length == 2)) {
64 const uint16_t conductivity =
encode_uint16(data[1], data[0]);
68 else if ((value_type == 0x100A || value_type == 0x4803) && (value_length == 1)) {
72 else if ((value_type == 0x100D) && (value_length == 4)) {
79 else if ((value_type == 0x1010) && (value_length == 2)) {
80 const uint16_t formaldehyde =
encode_uint16(data[1], data[0]);
84 else if ((value_type == 0x1012) && (value_length == 1)) {
88 else if ((value_type == 0x1013) && (value_length == 1)) {
92 else if ((value_type == 0x1017) && (value_length == 4)) {
96 }
else if ((value_type == 0x1018) && (value_length == 1)) {
100 else if ((value_type == 0x4C01) && (value_length == 4)) {
107 else if ((value_type == 0x4C02) && (value_length == 1)) {
111 else if ((value_type == 0x4C08) && (value_length == 4)) {
114 std::memcpy(&humidity, &int_number,
sizeof(humidity));
126 ESP_LOGVV(TAG,
"parse_xiaomi_message(): payload is encrypted, stop reading message.");
137 ESP_LOGVV(TAG,
"parse_xiaomi_message(): raw_offset (%d) exceeds message size (%u)!", result.
raw_offset,
138 static_cast<unsigned>(
size));
143 uint8_t payload_offset = 0;
144 bool success =
false;
146 if (payload_length < 4) {
147 ESP_LOGVV(TAG,
"parse_xiaomi_message(): payload has wrong size (%d)!", payload_length);
151 while (payload_length > 3) {
152 if (payload[payload_offset + 1] != 0x10 && payload[payload_offset + 1] != 0x00 &&
153 payload[payload_offset + 1] != 0x4C && payload[payload_offset + 1] != 0x48) {
154 ESP_LOGVV(TAG,
"parse_xiaomi_message(): fixed byte not found, stop parsing residual data.");
158 const uint8_t value_length = payload[payload_offset + 2];
159 if ((value_length < 1) || (value_length > 4) || (payload_length < (3 + value_length))) {
160 ESP_LOGVV(TAG,
"parse_xiaomi_message(): value has wrong size (%d)!", value_length);
164 const uint16_t value_type =
encode_uint16(payload[payload_offset + 1], payload[payload_offset + 0]);
165 const uint8_t *data = &payload[payload_offset + 3];
170 payload_length -= 3 + value_length;
171 payload_offset += 3 + value_length;
180 ESP_LOGVV(TAG,
"parse_xiaomi_header(): service data too short (%u).",
static_cast<unsigned>(
size));
185 if (!(
raw[0] & 0x40)) {
186 ESP_LOGVV(TAG,
"parse_xiaomi_header(): service data has no DATA flag.");
194 if (device_uuid == 0x0098) {
196 result.
name =
"HHCCJCY01";
197 }
else if (device_uuid == 0x01aa) {
199 result.
name =
"LYWSDCGQ";
200 }
else if (device_uuid == 0x015d) {
202 result.
name =
"HHCCPOT002";
203 }
else if (device_uuid == 0x02df) {
205 result.
name =
"JQJCY01YM";
206 }
else if (device_uuid == 0x03dd) {
208 result.
name =
"MUE4094RT";
210 }
else if (device_uuid == 0x0347 ||
211 device_uuid == 0x0B48) {
213 result.
name =
"CGG1";
214 }
else if (device_uuid == 0x03bc) {
216 result.
name =
"GCLS002";
217 }
else if (device_uuid == 0x045b) {
219 result.
name =
"LYWSD02";
220 }
else if (device_uuid == 0x2542 ||
221 device_uuid == 0x16e4) {
223 result.
name =
"LYWSD02MMC";
226 }
else if (device_uuid == 0x040a) {
228 result.
name =
"WX08ZM";
229 }
else if (device_uuid == 0x0576) {
231 result.
name =
"CGD1";
232 }
else if (device_uuid == 0x066F) {
234 result.
name =
"CGDK2";
235 }
else if (device_uuid == 0x055b) {
237 result.
name =
"LYWSD03MMC";
238 }
else if (device_uuid == 0x1203) {
240 result.
name =
"XMWSDJ04MMC";
243 }
else if (device_uuid == 0x07f6) {
245 result.
name =
"MJYD02YLA";
248 }
else if (device_uuid == 0x06d3) {
250 result.
name =
"MHOC303";
251 }
else if (device_uuid == 0x0387) {
253 result.
name =
"MHOC401";
254 }
else if (device_uuid == 0x0A83) {
256 result.
name =
"CGPR1";
259 }
else if (device_uuid == 0x0A8D) {
261 result.
name =
"RTCGQ02LM";
265 ESP_LOGVV(TAG,
"parse_xiaomi_header(): unknown device, no magic bytes.");
273 if ((
size != 19) && ((
size < 22) || (
size > XIAOMI_MAX_ENCRYPTED_FRAME_SIZE))) {
274 ESP_LOGVV(TAG,
"decrypt_xiaomi_payload(): data packet has wrong size (%u)!",
static_cast<unsigned>(
size));
275 ESP_LOGVV_HEX(TAG,
raw,
size, XIAOMI_MAX_LOG_BYTES,
" Packet : %s");
279 uint8_t mac_reverse[MAC_ADDRESS_SIZE] = {0};
280 mac_reverse[5] = (uint8_t) (
address >> 40);
281 mac_reverse[4] = (uint8_t) (
address >> 32);
282 mac_reverse[3] = (uint8_t) (
address >> 24);
283 mac_reverse[2] = (uint8_t) (
address >> 16);
284 mac_reverse[1] = (uint8_t) (
address >> 8);
285 mac_reverse[0] = (uint8_t) (
address >> 0);
300 const size_t cipher_pos = (
size == 19) ? 5 : 11;
302 const uint8_t *v =
raw;
305 memcpy(
vector.ciphertext, v + cipher_pos,
vector.datasize);
307 memcpy(
vector.iv, mac_reverse, 6);
308 memcpy(
vector.iv + 6, v + 2, 3);
311#ifdef XIAOMI_CRYPTO_PSA
313 uint8_t ct_with_tag[
sizeof(
vector.ciphertext) +
sizeof(
vector.tag)];
314 memcpy(ct_with_tag,
vector.ciphertext,
vector.datasize);
316 size_t ct_with_tag_size =
vector.datasize +
vector.tagsize;
318 psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
319 psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
320 psa_set_key_bits(&attributes,
vector.keysize * 8);
321 psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
322 psa_set_key_algorithm(&attributes, PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM,
vector.tagsize));
324 mbedtls_svc_key_id_t key_id;
325 if (psa_import_key(&attributes,
vector.key,
vector.keysize, &key_id) != PSA_SUCCESS) {
326 ESP_LOGVV(TAG,
"decrypt_xiaomi_payload(): psa_import_key() failed.");
330 size_t plaintext_length;
331 psa_status_t
status = psa_aead_decrypt(key_id, PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_CCM,
vector.tagsize),
333 ct_with_tag_size,
vector.plaintext,
vector.datasize, &plaintext_length);
334 psa_destroy_key(key_id);
335 bool decrypt_ok = (
status == PSA_SUCCESS && plaintext_length ==
vector.datasize);
344 uint8_t mac_address[MAC_ADDRESS_SIZE] = {0};
345 memcpy(mac_address, mac_reverse + 5, 1);
346 memcpy(mac_address + 1, mac_reverse + 4, 1);
347 memcpy(mac_address + 2, mac_reverse + 3, 1);
348 memcpy(mac_address + 3, mac_reverse + 2, 1);
349 memcpy(mac_address + 4, mac_reverse + 1, 1);
350 memcpy(mac_address + 5, mac_reverse, 1);
351 ESP_LOGVV(TAG,
"decrypt_xiaomi_payload(): authenticated decryption failed.");
352#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
353 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
357 ESP_LOGVV(TAG,
" MAC address : %s", mac_buf);
369 ESP_LOGVV(TAG,
"decrypt_xiaomi_payload(): authenticated decryption passed.");
370#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
374 static_cast<int>(
raw[4]));
379#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
380static void report_xiaomi_results(
const XiaomiParseResult &result,
const char *
address) {
381 ESP_LOGD(TAG,
"Got Xiaomi %s (%s):", result.name,
address);
383 if (result.temperature.has_value()) {
384 ESP_LOGD(TAG,
" Temperature: %.1f°C", *result.temperature);
386 if (result.humidity.has_value()) {
387 ESP_LOGD(TAG,
" Humidity: %.1f%%", *result.humidity);
389 if (result.battery_level.has_value()) {
390 ESP_LOGD(TAG,
" Battery Level: %.0f%%", *result.battery_level);
392 if (result.conductivity.has_value()) {
393 ESP_LOGD(TAG,
" Conductivity: %.0fµS/cm", *result.conductivity);
395 if (result.illuminance.has_value()) {
396 ESP_LOGD(TAG,
" Illuminance: %.0flx", *result.illuminance);
398 if (result.moisture.has_value()) {
399 ESP_LOGD(TAG,
" Moisture: %.0f%%", *result.moisture);
401 if (result.tablet.has_value()) {
402 ESP_LOGD(TAG,
" Mosquito tablet: %.0f%%", *result.tablet);
404 if (result.is_active.has_value()) {
405 ESP_LOGD(TAG,
" Repellent: %s", *result.is_active ? LOG_STR_LITERAL(
"on") : LOG_STR_LITERAL(
"off"));
407 if (result.has_motion.has_value()) {
408 ESP_LOGD(TAG,
" Motion: %s", *result.has_motion ? LOG_STR_LITERAL(
"yes") : LOG_STR_LITERAL(
"no"));
410 if (result.is_light.has_value()) {
411 ESP_LOGD(TAG,
" Light: %s", *result.is_light ? LOG_STR_LITERAL(
"on") : LOG_STR_LITERAL(
"off"));
413 if (result.button_press.has_value()) {
414 ESP_LOGD(TAG,
" Button: %s", *result.button_press ? LOG_STR_LITERAL(
"pressed") : LOG_STR_LITERAL(
""));
423 bool success =
false;
425 if (!service_data.uuid.contains(0x95, 0xFE))
427 const uint8_t *
raw = service_data.data.data();
428 const size_t size = service_data.data.size();
431 ESP_LOGVV(TAG,
"Duplicate frame %u.",
raw[4]);
435 if (!res.has_value())
438 uint8_t plaintext[XIAOMI_MAX_ENCRYPTED_FRAME_SIZE];
439 if (res->has_encryption) {
440 if (bindkey ==
nullptr) {
441 ESP_LOGVV(TAG,
"Encrypted frame but no bindkey.");
444 if (
size >
sizeof(plaintext))
455#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
456 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
471 memcpy(this->
bindkey_, bindkey.begin(), std::min(bindkey.size(),
sizeof(this->bindkey_)));
ESPDEPRECATED("Use address_str_to() instead. Removed in 2027.2.0.", "2026.8.0") std const char * address_str_to(char *buf) const
Return MAC as "XX:XX:XX:XX:XX:XX" string.
uint64_t address_uint64() const
Return MAC as packed uint64 (byte 0 in LSB — matches esp32's address_uint64).
const std::vector< ServiceData > & get_service_datas() const
optional< uint8_t > last_frame_count_
bool parse_xiaomi_device_(const ble_device_base::ESPBTDevice &device, const uint8_t *bindkey)
Encrypted frames are dropped when bindkey is null.
virtual void publish_result(const XiaomiParseResult &result)=0
void set_bindkey(std::initializer_list< uint8_t > bindkey)
void dump_bindkey_(const char *tag) const
bool parse_device(const ble_device_base::ESPBTDevice &device) override
const LogString * message
bool aes_ccm_auth_decrypt(const uint8_t key[16], const uint8_t *nonce, size_t nonce_len, const uint8_t *aad, size_t aad_len, const uint8_t *ciphertext, size_t ct_len, uint8_t *plaintext, const uint8_t *tag, size_t tag_len)
bool parse_xiaomi_message(const uint8_t *message, size_t size, XiaomiParseResult &result)
bool decrypt_xiaomi_payload(uint8_t *raw, size_t size, const uint8_t *bindkey, uint64_t address)
Decrypts the payload of raw in place and clears its encryption flag.
bool parse_xiaomi_value(uint16_t value_type, const uint8_t *data, uint8_t value_length, XiaomiParseResult &result)
optional< XiaomiParseResult > parse_xiaomi_header(const uint8_t *raw, size_t size)
Parses the frame control and product id; the caller checks the 0xFE95 UUID and filters duplicates.
ESPHOME_LOG_TAG(TAG, "xiaomi_ble")
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.
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
constexpr T encode_value_le(const uint8_t *bytes)
Encode a value from its constituent bytes (from least to most significant) in an array with length si...
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
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.
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
optional< float > humidity
optional< float > formaldehyde
optional< float > conductivity
optional< float > battery_level
enum esphome::xiaomi_ble::XiaomiParseResult::@206 type
optional< float > idle_time
optional< bool > is_light
optional< bool > has_motion
optional< float > illuminance
optional< bool > button_press
optional< float > temperature
optional< bool > is_active
optional< float > moisture