ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
xiaomi_mccgq02hl.cpp
Go to the documentation of this file.
1#include "xiaomi_mccgq02hl.h"
4#include "esphome/core/log.h"
5
6#include <cstring>
7
9
10ESPHOME_LOG_TAG(TAG, "xiaomi_mccgq02hl");
11
12static constexpr uint16_t PRODUCT_ID = 0x098b;
13
14// MiBeacon frame control, low byte (raw[0])
15static constexpr uint8_t FC_ENCRYPTED = 0x08;
16static constexpr uint8_t FC_MAC_INCLUDED = 0x10;
17static constexpr uint8_t FC_CAPABILITY = 0x20;
18static constexpr uint8_t FC_OBJECT = 0x40;
19
20// Encrypted frames end in a 3-byte extended counter and a 4-byte MIC.
21static constexpr size_t MIC_SIZE = 4;
22static constexpr size_t ENCRYPTED_TRAILER = 3 + MIC_SIZE;
23// Largest encrypted payload accepted; MCCGQ02HL objects are 4 bytes.
24static constexpr size_t MAX_PAYLOAD_SIZE = 16;
25
26// Object ids. The door and light objects come in both the 0x00xx and the
27// 0x10xx flavour depending on firmware; the semantics are identical.
28static constexpr uint16_t OBJ_LIGHT = 0x0018;
29static constexpr uint16_t OBJ_LIGHT_ALT = 0x1018;
30static constexpr uint16_t OBJ_DOOR = 0x0019;
31static constexpr uint16_t OBJ_DOOR_ALT = 0x1019;
32static constexpr uint16_t OBJ_BATTERY = 0x100A;
33static constexpr uint16_t OBJ_BATTERY_ALT = 0x4803;
34
35void XiaomiMCCGQ02HL::dump_config() {
36 uint8_t mac[MAC_ADDRESS_SIZE];
38 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
39 ESP_LOGCONFIG(TAG,
40 "Xiaomi MCCGQ02HL\n"
41 " MAC Address: %s",
42 format_mac_addr_upper(mac, mac_buf));
43 LOG_BINARY_SENSOR(" ", "Opening", this);
44 LOG_BINARY_SENSOR(" ", "Light", this->light_binary_sensor_);
45 LOG_SENSOR(" ", "Battery Level", this->battery_level_sensor_);
46}
47
48void XiaomiMCCGQ02HL::set_bindkey(const char *bindkey) { parse_hex(bindkey, this->bindkey_, sizeof(this->bindkey_)); }
49
50bool XiaomiMCCGQ02HL::parse_device(const ble_device_base::ESPBTDevice &device) {
51 if (device.address_uint64() != this->address_)
52 return false;
53
54 bool success = false;
55 for (auto &service_data : device.get_service_datas()) {
56 if (!service_data.uuid.contains(0x95, 0xFE))
57 continue;
58
59 Reading reading;
60 if (!this->parse_service_data_(service_data.data, reading))
61 continue;
62
63 ESP_LOGD(TAG, "%s: open=%s light=%s battery=%s", LOG_STR_ARG(this->get_log_name()),
64 reading.open.has_value() ? (*reading.open ? LOG_STR_LITERAL("yes") : LOG_STR_LITERAL("no"))
65 : LOG_STR_LITERAL("-"),
66 reading.light.has_value() ? (*reading.light ? LOG_STR_LITERAL("yes") : LOG_STR_LITERAL("no"))
67 : LOG_STR_LITERAL("-"),
68 reading.battery_level.has_value() ? LOG_STR_LITERAL("updated") : LOG_STR_LITERAL("-"));
69
70 if (reading.open.has_value())
71 this->publish_state(*reading.open);
72 publish_optional(this->light_binary_sensor_, reading.light);
73 publish_optional(this->battery_level_sensor_, reading.battery_level);
74 success = true;
75 }
76 return success;
77}
78
79bool XiaomiMCCGQ02HL::decrypt_(const uint8_t *frame, size_t size, size_t offset, uint8_t *plaintext) const {
80 uint8_t nonce[MAC_ADDRESS_SIZE + 6];
81 for (size_t i = 0; i < MAC_ADDRESS_SIZE; i++)
82 nonce[i] = static_cast<uint8_t>(this->address_ >> (i * 8)); // MAC, reversed
83 memcpy(nonce + MAC_ADDRESS_SIZE, frame + 2, 3); // product id + frame count
84 memcpy(nonce + MAC_ADDRESS_SIZE + 3, frame + size - ENCRYPTED_TRAILER, 3); // extended counter
85 static constexpr uint8_t AUTH_DATA[1] = {0x11};
86 return ble_device_base::aes_ccm_auth_decrypt(this->bindkey_, nonce, sizeof(nonce), AUTH_DATA, sizeof(AUTH_DATA),
87 frame + offset, size - offset - ENCRYPTED_TRAILER, plaintext,
88 frame + size - MIC_SIZE, MIC_SIZE);
89}
90
91bool XiaomiMCCGQ02HL::parse_service_data_(const std::vector<uint8_t> &data, Reading &reading) {
92 const size_t size = data.size();
93 if (size < 5)
94 return false;
95 const uint8_t *raw = data.data();
96
97 const uint8_t fc = raw[0];
98 if (!(fc & FC_OBJECT))
99 return false;
100 if (encode_uint16(raw[3], raw[2]) != PRODUCT_ID) {
101 ESP_LOGVV(TAG, "Not an MCCGQ02HL frame (product id %02X%02X).", raw[3], raw[2]);
102 return false;
103 }
104
105 const uint8_t frame_count = raw[4];
106 if (this->last_frame_count_.has_value() && *this->last_frame_count_ == frame_count) {
107 ESP_LOGVV(TAG, "Duplicate frame %u.", frame_count);
108 return false;
109 }
110
111 // The bindkey is required, so plaintext frames are never trusted
112 if (!(fc & FC_ENCRYPTED)) {
113 ESP_LOGVV(TAG, "Ignoring unencrypted frame %u.", frame_count);
114 return false;
115 }
116
117 const size_t offset = 5 + ((fc & FC_MAC_INCLUDED) ? 6 : 0) + ((fc & FC_CAPABILITY) ? 1 : 0);
119 ESP_LOGW(TAG, "Unsupported encrypted frame layout (fc=0x%02X, %u bytes).", fc, (unsigned) size);
120 return false;
121 }
122 uint8_t plaintext[MAX_PAYLOAD_SIZE];
123 if (!this->decrypt_(raw, size, offset, plaintext)) {
124 ESP_LOGW(TAG, "Decryption failed (%u-byte frame) -- check the bindkey.", (unsigned) size);
125 return false;
126 }
127 // Only an authenticated frame may advance the duplicate filter. There is no replay protection: the
128 // counter is not persisted and restarts on a battery change, so a strictly increasing check could lock
129 // the sensor out until the next reboot.
130 this->last_frame_count_ = frame_count;
131 return this->parse_objects_(plaintext, size - offset - ENCRYPTED_TRAILER, reading);
132}
133
134bool XiaomiMCCGQ02HL::parse_objects_(const uint8_t *payload, size_t length, Reading &reading) {
135 bool found = false;
136 // Each object: id (uint16 LE), length (uint8), value.
137 while (length >= 3) {
138 const uint16_t id = encode_uint16(payload[1], payload[0]);
139 const uint8_t len = payload[2];
140 if (len < 1 || length < 3u + len)
141 break;
142 const uint8_t *value = payload + 3;
143
144 if ((id == OBJ_DOOR || id == OBJ_DOOR_ALT) && len == 1) {
145 // 0 = open, 1 = closed, 2 = left open past timeout, 3 = device reset
146 if (value[0] <= 2) {
147 reading.open = value[0] != 1;
148 found = true;
149 }
150 } else if ((id == OBJ_LIGHT || id == OBJ_LIGHT_ALT) && len == 1) {
151 reading.light = value[0] != 0;
152 found = true;
153 } else if ((id == OBJ_BATTERY || id == OBJ_BATTERY_ALT) && len == 1) {
154 reading.battery_level = value[0];
155 found = true;
156 } else {
157 ESP_LOGVV(TAG, "Ignoring object 0x%04X (%u bytes).", id, len);
158 }
159
160 payload += 3 + len;
161 length -= 3 + len;
162 }
163 return found;
164}
165
166} // namespace esphome::xiaomi_mccgq02hl
uint8_t raw[35]
Definition bl0939.h:0
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
void publish_state(bool new_state)
Publish a new state to the front-end.
bool decrypt_(const uint8_t *frame, size_t size, size_t offset, uint8_t *plaintext) const
bool parse_objects_(const uint8_t *payload, size_t length, Reading &reading)
bool parse_service_data_(const std::vector< uint8_t > &data, Reading &reading)
void uint64_to_mac_msb_first(uint64_t address, uint8_t out[6])
Unpack a uint64 BLE address into printable (MSB-first) byte order — the order bd_addr_t / esp_bd_addr...
Definition ble_device.h:169
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)
ESPHOME_LOG_TAG(TAG, "xiaomi_mccgq02hl")
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:370
uint16_t size
Definition helpers.cpp:34
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:1043
void publish_optional(E *entity, const optional< V > &value)
Publish value to entity when the entity is configured and the value is set.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1754
uint16_t length
Definition tt21100.cpp:0