ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
daikin_madoka.cpp
Go to the documentation of this file.
1#include "daikin_madoka.h"
2
3#include <algorithm>
4#include <cinttypes>
6#include "esphome/core/log.h"
7
8#ifdef USE_ESP32
9
11
12using namespace esphome::climate;
13
14ESPHOME_LOG_TAG(TAG, "daikin_madoka");
15
16static constexpr uint16_t CMD_GET_SETTING_STATUS = 0x0020;
17static constexpr uint16_t CMD_SET_SETTING_STATUS = 0x4020;
18static constexpr uint16_t CMD_GET_OPERATION_MODE = 0x0030;
19static constexpr uint16_t CMD_SET_OPERATION_MODE = 0x4030;
20static constexpr uint16_t CMD_GET_SETPOINT = 0x0040;
21static constexpr uint16_t CMD_SET_SETPOINT = 0x4040;
22static constexpr uint16_t CMD_GET_FAN_SPEED = 0x0050;
23static constexpr uint16_t CMD_SET_FAN_SPEED = 0x4050;
24static constexpr uint16_t CMD_GET_SENSOR_INFORMATION = 0x0110;
25static constexpr uint16_t CMD_SET_FLAG = 0x4000;
26
27// Indexed by the device's operation mode byte
28static constexpr std::array<ClimateMode, 5> DEVICE_MODES{CLIMATE_MODE_FAN_ONLY, CLIMATE_MODE_DRY,
30static constexpr uint8_t DEVICE_MODE_HEAT = 4;
31// Publishes the parsed state when the poll's last reply, SENSOR_INFORMATION, does not arrive
32static constexpr uint32_t PUBLISH_DELAY_MS = 800;
33
34void DaikinMadoka::dump_config() { LOG_CLIMATE(TAG, "Daikin Madoka Climate Controller", this); }
35
36// Replies arrive in order, so the last one, SENSOR_INFORMATION, ends the poll and publishes at once
37static constexpr std::array<uint16_t, 5> POLL_CMDS{CMD_GET_SETTING_STATUS, CMD_GET_OPERATION_MODE, CMD_GET_SETPOINT,
38 CMD_GET_FAN_SPEED, CMD_GET_SENSOR_INFORMATION};
39static constexpr std::array<uint8_t, 2> NO_ARGS{0x00, 0x00};
40
41static uint32_t get_command_cooldown(uint16_t cmd) {
42 switch (cmd) {
43 case CMD_GET_SETTING_STATUS:
44 case CMD_GET_OPERATION_MODE:
45 case CMD_GET_SETPOINT:
46 case CMD_GET_FAN_SPEED:
47 case CMD_GET_SENSOR_INFORMATION:
48 return 50;
49 case CMD_SET_SETTING_STATUS:
50 return 200;
51 case CMD_SET_OPERATION_MODE:
52 return 600;
53 case CMD_SET_SETPOINT:
54 return 400;
55 case CMD_SET_FAN_SPEED:
56 return 200;
57 default:
58 return 100;
59 }
60}
61
63 if (this->node_state != espbt::ClientState::ESTABLISHED) {
64 this->publish_state(); // Update state to reflect that the device is disconnected
65 return;
66 }
67
68 auto mode_opt = call.get_mode();
69 if (mode_opt.has_value()) {
70 const ClimateMode mode = mode_opt.value();
71 if (mode == CLIMATE_MODE_OFF) {
72 this->enqueue_query_(CMD_SET_SETTING_STATUS, std::array<uint8_t, 3>{0x20, 0x01, 0});
73 } else {
74 const auto *it = std::find(DEVICE_MODES.begin(), DEVICE_MODES.end(), mode);
75 if (it == DEVICE_MODES.end()) {
76 ESP_LOGW(TAG, "Unsupported mode: %d", mode);
77 } else {
78 const auto device_mode = static_cast<uint8_t>(it - DEVICE_MODES.begin());
79 this->enqueue_query_(CMD_SET_OPERATION_MODE, std::array<uint8_t, 3>{0x20, 0x01, device_mode});
80 this->enqueue_query_(CMD_SET_SETTING_STATUS, std::array<uint8_t, 3>{0x20, 0x01, 1});
81 }
82 }
83 }
84 QueryArgs setpoint_args;
85 if (auto high = call.get_target_temperature_high(); high.has_value()) {
86 append_setpoint(setpoint_args, 0x20, *high);
87 }
88 if (auto low = call.get_target_temperature_low(); low.has_value()) {
89 append_setpoint(setpoint_args, 0x21, *low);
90 }
91 if (!setpoint_args.empty()) {
92 this->enqueue_query_(CMD_SET_SETPOINT, setpoint_args);
93 }
94 auto fan_mode_opt = call.get_fan_mode();
95 if (fan_mode_opt.has_value()) {
96 uint8_t fan_mode = fan_mode_opt.value();
97 uint8_t fan_mode_out = 255;
98 switch (fan_mode) {
100 fan_mode_out = 0;
101 break;
103 fan_mode_out = 1;
104 break;
106 fan_mode_out = 3;
107 break;
109 fan_mode_out = 5;
110 break;
111 default:
112 ESP_LOGW(TAG, "Unsupported fan mode: %d", fan_mode);
113 break;
114 }
115 if (fan_mode_out != 255) {
116 // Sets the cooling (0x20) and heating (0x21) fan speeds together
117 this->enqueue_query_(CMD_SET_FAN_SPEED,
118 std::array<uint8_t, 6>{0x20, 0x01, fan_mode_out, 0x21, 0x01, fan_mode_out});
119 }
120 }
121 this->update();
122}
123
124void DaikinMadoka::fail_connection_(const LogString *reason) {
125 ESP_LOGW(TAG, "[%s] %s, disconnecting", this->parent_->address_str(), LOG_STR_ARG(reason));
126 this->status_set_warning(reason);
127 this->parent_->disconnect();
128}
129
130void DaikinMadoka::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
131 switch (event) {
132 case ESP_GAP_BLE_NC_REQ_EVT:
133 if (!this->parent()->check_addr(param->ble_security.key_notif.bd_addr))
134 return;
135 esp_ble_confirm_reply(param->ble_security.key_notif.bd_addr, true);
136 ESP_LOGI(TAG, "ESP_GAP_BLE_NC_REQ_EVT, the passkey Notify number: %06" PRIu32,
137 param->ble_security.key_notif.passkey);
138 break;
139 case ESP_GAP_BLE_AUTH_CMPL_EVT: {
140 if (!this->parent()->check_addr(param->ble_security.auth_cmpl.bd_addr))
141 return;
142 if (!param->ble_security.auth_cmpl.success) {
143 ESP_LOGW(TAG, "Authentication failed, reason: 0x%x", param->ble_security.auth_cmpl.fail_reason);
144 this->fail_connection_(LOG_STR("Pairing failed"));
145 break;
146 }
147 auto *nfy = this->parent_->get_characteristic(MADOKA_SERVICE_UUID, NOTIFY_CHARACTERISTIC_UUID);
148 auto *wwr = this->parent_->get_characteristic(MADOKA_SERVICE_UUID, WWR_CHARACTERISTIC_UUID);
149 if (nfy == nullptr || wwr == nullptr) {
150 this->fail_connection_(LOG_STR("Madoka control service not found"));
151 break;
152 }
153 this->notify_handle_ = nfy->handle;
154 this->wwr_handle_ = wwr->handle;
155
156 if (this->parent_->register_for_notify(nfy->handle) != ESP_OK) {
157 this->fail_connection_(LOG_STR("Notify registration failed"));
158 }
159 break;
160 }
161 default:
162 break;
163 }
164}
165
166void DaikinMadoka::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
167 esp_ble_gattc_cb_param_t *param) {
168 switch (event) {
169 case ESP_GATTC_DISCONNECT_EVT: {
170 this->notify_handle_ = 0;
171 this->wwr_handle_ = 0;
172
173 this->current_temperature = NAN;
174 this->target_temperature_high = NAN;
175 this->target_temperature_low = NAN;
177 this->fan_mode.reset();
178 this->publish_state();
179
180 this->assembler_.reset();
183 this->query_cooldown_ = false;
184 this->query_queue_.clear();
185 this->poll_pending_ = false;
186 this->get_in_flight_ = false;
187 break;
188 }
189 case ESP_GATTC_WRITE_DESCR_EVT:
190 // The only descriptor written is the notification one, so polls get no replies without it
191 if (param->write.status != ESP_GATT_OK) {
192 ESP_LOGE(TAG, "Failed writing the notification descriptor, status = 0x%x", param->write.status);
193 this->fail_connection_(LOG_STR("Notification descriptor write failed"));
194 }
195 break;
196 case ESP_GATTC_SEARCH_CMPL_EVT: {
197 if (esp_ble_set_encryption(this->parent_->get_remote_bda(), ESP_BLE_SEC_ENCRYPT_MITM) != ESP_OK) {
198 this->fail_connection_(LOG_STR("Encryption request failed"));
199 }
200 break;
201 }
202 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
203 if (param->reg_for_notify.handle != this->notify_handle_) {
204 break;
205 }
206 if (param->reg_for_notify.status != ESP_GATT_OK) {
207 this->fail_connection_(LOG_STR("Notify registration failed"));
208 break;
209 }
210 this->node_state = espbt::ClientState::ESTABLISHED;
211 this->status_clear_warning();
212 this->update();
213 break;
214 }
215 case ESP_GATTC_NOTIFY_EVT: {
216 if (param->notify.handle != this->notify_handle_) {
217 ESP_LOGW(TAG, "Different notify handle");
218 break;
219 }
220 this->process_incoming_chunk_(std::span<const uint8_t>{param->notify.value, param->notify.value_len});
221 break;
222 }
223 default:
224 break;
225 }
226}
227
229 ESP_LOGV(TAG, "Got update request...");
230 if (this->node_state != espbt::ClientState::ESTABLISHED) {
231 ESP_LOGV(TAG, "...but device is disconnected");
232 return;
233 }
234 this->poll_pending_ = true;
235 if (!this->query_cooldown_)
236 this->send_next_query_();
237}
238
239void DaikinMadoka::process_incoming_chunk_(std::span<const uint8_t> chunk) {
240 switch (this->assembler_.feed(chunk)) {
242 this->parse_cb_(this->assembler_.message());
243 break;
245 ESP_LOGW(TAG, "Chunk discarded: invalid length");
246 break;
248 ESP_LOGW(TAG, "Chunk discarded: invalid chunk id %u", chunk[0]);
249 break;
251 ESP_LOGW(TAG, "Message discarded: too long");
252 break;
254 break;
255 }
256}
257
258void DaikinMadoka::enqueue_query_(uint16_t cmd, std::span<const uint8_t> args) {
259 Query *same = nullptr;
260 Query *mode_behind = nullptr;
261 for (Query &queued : this->query_queue_) {
262 if (queued.cmd == cmd) {
263 same = &queued;
264 } else if (cmd == CMD_SET_SETTING_STATUS && queued.cmd == CMD_SET_OPERATION_MODE && same != nullptr) {
265 mode_behind = &queued;
266 }
267 }
268 // A command queued again keeps its one entry with the newest values, so the backlog stays bounded
269 if (same != nullptr) {
270 // Power-on has to follow the mode queued with it, so a mode queued behind an older status
271 // entry takes that entry's place
272 if (mode_behind != nullptr) {
273 std::swap(*same, *mode_behind);
274 same = mode_behind;
275 }
276 if (merge_args(same->args, args))
277 return;
278 }
279 Query query{.cmd = cmd, .args = {}};
280 query.args.resize(args.size());
281 std::copy(args.begin(), args.end(), query.args.begin());
282 if (!this->query_queue_.push(query)) {
283 ESP_LOGW(TAG, "Query queue full, dropping command 0x%04X", cmd);
284 }
285}
286
288 // BLE being disabled resets the client without a disconnect event, so the queue stops here
289 if (this->node_state != espbt::ClientState::ESTABLISHED) {
290 this->query_queue_.clear();
291 this->query_cooldown_ = false;
292 this->poll_pending_ = false;
293 this->get_in_flight_ = false;
294 return;
295 }
296 if (this->query_queue_.empty()) {
297 if (!this->poll_pending_) {
298 this->query_cooldown_ = false;
299 return;
300 }
301 this->poll_pending_ = false;
302 // Chunks left from a partly lost reply must not combine with this batch's replies
303 this->assembler_.reset();
304 for (auto cmd : POLL_CMDS) {
305 this->enqueue_query_(cmd, NO_ARGS);
306 }
307 }
308 const Query &query = this->query_queue_.front();
309 const uint16_t cmd = query.cmd;
310 const bool is_set = (cmd & CMD_SET_FLAG) != 0;
311 // A GET's reply may still be arriving when the next command goes out, so a SET resets only when none is
312 if (is_set && !this->get_in_flight_)
313 this->assembler_.reset();
314 // On a failed write the query stays queued for the next pass
315 if (this->write_query_(query)) {
316 this->query_queue_.pop();
317 this->get_in_flight_ = !is_set;
318 }
319 this->query_cooldown_ = true;
320 this->set_timeout(QUERY_TIMEOUT_ID, get_command_cooldown(cmd), [this]() { this->send_next_query_(); });
321}
322
324 static_assert(MAX_QUERY_ARGS + MESSAGE_HEADER_SIZE <= MAX_CHUNK_SIZE - 1, "A query must fit in one chunk");
325 // Chunk id 0, then the message: length, reserved byte, command, args
326 std::array<uint8_t, MAX_CHUNK_SIZE> frame;
327 const uint8_t msg_len = MESSAGE_HEADER_SIZE + query.args.size();
328 const auto cmd = decode_value<uint16_t>(query.cmd);
329 frame[0] = 0;
330 frame[1] = msg_len;
331 frame[2] = 0;
332 frame[3] = cmd[0];
333 frame[4] = cmd[1];
334 std::copy(query.args.begin(), query.args.end(), frame.begin() + 1 + MESSAGE_HEADER_SIZE);
335
336 ESP_LOGV(TAG, "Writing query. ID: 0x%04X, len: %u", query.cmd, msg_len + 1);
337 ESP_LOGV_HEX(TAG, frame.data(), msg_len + 1, MAX_CHUNK_SIZE, "%s");
338
339 esp_err_t err =
340 esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), this->wwr_handle_,
341 msg_len + 1, frame.data(), ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
342 if (err != ESP_OK) {
343 ESP_LOGW(TAG, "[%s] Writing command 0x%04X failed, status=%d", this->parent_->address_str(), query.cmd, err);
344 return false;
345 }
346 return true;
347}
348
350 if (!this->power_on_) {
351 this->mode = CLIMATE_MODE_OFF;
352 } else if (this->device_mode_ < DEVICE_MODES.size()) {
353 this->mode = DEVICE_MODES[this->device_mode_];
354 }
355}
356
357void DaikinMadoka::parse_cb_(std::span<const uint8_t> msg) {
358 if (!is_valid_message(msg)) {
359 ESP_LOGW(TAG, "Discarding message: invalid length");
360 return;
361 }
362
363 ESP_LOGV(TAG, "Parsing message. ID: 0x%04X, len: %u", message_function_id(msg), msg.size());
364 ESP_LOGV_HEX(TAG, msg.data(), msg.size(), 256, "%s");
365
366 switch (message_function_id(msg)) {
367 case CMD_GET_SETTING_STATUS: {
368 if (auto value = find_arg(msg, 0x20); value.size() == 1) {
369 this->power_on_ = value[0] == 1;
371 }
372 break;
373 }
374 case CMD_GET_OPERATION_MODE: {
375 if (auto value = find_arg(msg, 0x20); value.size() == 1) {
376 this->device_mode_ = value[0];
378 }
379 break;
380 }
381 case CMD_GET_SETPOINT: {
382 if (auto high = find_arg(msg, 0x20); high.size() == 2) {
384 }
385 if (auto low = find_arg(msg, 0x21); low.size() == 2) {
387 }
388 break;
389 }
390 case CMD_GET_FAN_SPEED: {
391 // Heat mode uses the heating fan speed (0x21); the other modes use the cooling one (0x20)
392 auto value = find_arg(msg, this->device_mode_ == DEVICE_MODE_HEAT ? 0x21 : 0x20);
393 if (value.size() != 1) {
394 break;
395 }
396 switch (value[0]) {
397 case 0:
399 break;
400 case 1:
402 break;
403 case 2:
404 case 3:
405 case 4:
407 break;
408 case 5:
410 break;
411 default:
412 break;
413 }
414 break;
415 }
416 case CMD_GET_SENSOR_INFORMATION: {
417 if (auto value = find_arg(msg, 0x40); value.size() == 1) {
418 this->current_temperature = static_cast<float>(value[0]);
419 }
421 this->publish_state();
422 return;
423 }
424 default:
425 return;
426 }
427 this->set_timeout(PUBLISH_TIMEOUT_ID, PUBLISH_DELAY_MS, [this]() { this->publish_state(); });
428}
429
430} // namespace esphome::daikin_madoka
431
432#endif
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:309
size_t size() const
Definition helpers.h:373
bool empty() const
Definition helpers.h:375
void resize(size_t n)
Definition helpers.h:353
This class is used to encode all control actions on a climate device.
Definition climate.h:31
ClimateMode mode
The active mode of the climate device.
Definition climate.h:317
optional< ClimateFanMode > fan_mode
The active fan mode of the climate device.
Definition climate.h:311
float target_temperature_low
The minimum target temperature of the climate device, for climate devices with split target temperatu...
Definition climate.h:301
float current_temperature
The current temperature of the climate device, as reported from the integration.
Definition climate.h:291
void publish_state()
Publish the state of the climate device, to be called from integrations.
Definition climate.cpp:432
float target_temperature_high
The maximum target temperature of the climate device, for climate devices with split target temperatu...
Definition climate.h:303
void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) override
StaticRingBuffer< Query, QUERY_QUEUE_SIZE > query_queue_
void enqueue_query_(uint16_t cmd, std::span< const uint8_t > args)
void control(const climate::ClimateCall &call) override
static constexpr uint32_t QUERY_TIMEOUT_ID
bool write_query_(const Query &query)
void process_incoming_chunk_(std::span< const uint8_t > chunk)
void fail_connection_(const LogString *reason)
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
void parse_cb_(std::span< const uint8_t > msg)
static constexpr uint32_t PUBLISH_TIMEOUT_ID
ChunkResult feed(std::span< const uint8_t > chunk)
std::span< const uint8_t > message() const
esp_err_t register_for_notify(uint16_t char_handle)
Register for notifications, holding the service release until the registration completes.
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
ESPHOME_LOG_TAG(TAG, "climate")
ClimateMode
Enum for all modes a climate device can be in.
@ CLIMATE_MODE_DRY
The climate device is set to dry/humidity mode.
@ CLIMATE_MODE_FAN_ONLY
The climate device only has the fan enabled, no heating or cooling is taking place.
@ CLIMATE_MODE_HEAT
The climate device is set to heat to reach the target temperature.
@ CLIMATE_MODE_COOL
The climate device is set to cool to reach the target temperature.
@ CLIMATE_MODE_HEAT_COOL
The climate device is set to heat/cool to reach the target temperature.
@ CLIMATE_MODE_OFF
The climate device is off.
@ CLIMATE_FAN_MEDIUM
The fan mode is set to Medium.
@ CLIMATE_FAN_AUTO
The fan mode is set to Auto.
@ CLIMATE_FAN_LOW
The fan mode is set to Low.
@ CLIMATE_FAN_HIGH
The fan mode is set to High.
bool is_valid_message(std::span< const uint8_t > msg)
True when the length byte matches and the header (length, reserved, function id) is present.
void append_setpoint(QueryArgs &args, uint8_t id, float temperature)
Appends a setpoint record {id, 2, msb, lsb}, clamped to the supported range.
std::span< const uint8_t > find_arg(std::span< const uint8_t > msg, uint8_t id)
Returns the value of argument id, or an empty span when it is absent, has no value or the records are...
uint16_t message_function_id(std::span< const uint8_t > msg)
bool merge_args(QueryArgs &args, std::span< const uint8_t > incoming)
Merges the records {id, len, value...} of incoming into args: a record whose id is already present is...
float decode_setpoint(std::span< const uint8_t > value)
Decodes a two byte setpoint value; the caller checks the size.
uint32_t value
Definition hal.cpp:41
constexpr std::array< uint8_t, sizeof(T)> decode_value(T val)
Decode a value into its constituent bytes (from most to least significant).
Definition helpers.h:1101
static void uint32_t