ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
mitsubishi_cn105.cpp
Go to the documentation of this file.
1#include "mitsubishi_cn105.h"
2
3#include <algorithm>
4#include <array>
5#include <cmath>
7
9
10ESPHOME_LOG_TAG(TAG, "mitsubishi_cn105.driver");
11
12static constexpr uint32_t RESPONSE_TIMEOUT_MS = 2000;
13
14static constexpr size_t REQUEST_PAYLOAD_LEN = 0x10;
15static constexpr size_t HEADER_LEN = 5;
16static constexpr uint8_t PREAMBLE = 0xFC;
17static constexpr uint8_t HEADER_BYTE_1 = 0x01;
18static constexpr uint8_t HEADER_BYTE_2 = 0x30;
19
20static constexpr uint8_t PACKET_TYPE_CONNECT_REQUEST = 0x5A;
21static constexpr uint8_t PACKET_TYPE_CONNECT_RESPONSE = 0x7A;
22static constexpr std::array<uint8_t, 2> CONNECT_REQUEST_PAYLOAD = {0xCA, 0x01};
23
24static constexpr uint8_t PACKET_TYPE_STATUS_REQUEST = 0x42;
25static constexpr uint8_t PACKET_TYPE_STATUS_RESPONSE = 0x62;
26static constexpr uint8_t STATUS_MSG_NONE = 0x00;
27static constexpr uint8_t STATUS_MSG_SETTINGS = 0x02;
28static constexpr uint8_t STATUS_MSG_ROOM_TEMPERATURE = 0x03;
29static constexpr uint8_t STATUS_MSG_OPERATING_STATUS = 0x06;
30
31static constexpr uint8_t PACKET_TYPE_WRITE_SETTINGS_REQUEST = 0x41;
32static constexpr uint8_t PACKET_TYPE_WRITE_SETTINGS_RESPONSE = 0x61;
33
34// After a power-off or a mode change that ends the run, 0x06 is read this often while the unit winds down.
35static constexpr uint32_t WIND_DOWN_READ_INTERVAL_MS = 10000;
36
37static constexpr uint8_t checksum(const uint8_t *bytes, size_t length) {
38 return static_cast<uint8_t>(0xFC - sum_bytes(bytes, length));
39}
40
41template<std::size_t PayloadSize>
42static constexpr auto make_packet(uint8_t type, const std::array<uint8_t, PayloadSize> &payload) {
43 const size_t full_len = PayloadSize + HEADER_LEN + 1;
44 std::array<uint8_t, full_len> packet{PREAMBLE, type, HEADER_BYTE_1, HEADER_BYTE_2, static_cast<uint8_t>(PayloadSize)};
45 std::copy_n(payload.begin(), PayloadSize, packet.begin() + HEADER_LEN);
46 packet.back() = checksum(packet.data(), packet.size() - 1);
47 return packet;
48}
49
50static constexpr auto CONNECT_PACKET = make_packet(PACKET_TYPE_CONNECT_REQUEST, CONNECT_REQUEST_PAYLOAD);
51
53
55 switch (this->state_) {
57 // Defer the next request to a later loop iteration; some units might not respond if a request is sent
58 // immediately after a response. See https://github.com/esphome/esphome/issues/18099. No minimum RX-to-TX delay
59 // is enforced.
61 return false;
62
64 if (this->pending_updates_.any()) {
68 // Publishes a hold started by the write
69 return this->take_status_changed_();
70 }
71 if (this->has_timed_out_(this->update_interval_ms_)) {
73 return false;
74 }
75 break;
76
80 if (this->has_timed_out_(RESPONSE_TIMEOUT_MS)) {
81 // Some units never answer 0x06: end the chain without reconnecting, and stop asking after a few misses.
82 // A dead link is still caught by the next 0x02 timeout.
83 if (this->state_ == State::UPDATING_STATUS && this->current_status_msg_type_ == STATUS_MSG_OPERATING_STATUS) {
85 ESP_LOGI(TAG, "No operating status response, climate action stays idle");
86 this->wind_down_reads_ = 0;
87 }
88 this->frame_parser_.reset();
90 return this->take_status_changed_();
91 }
93 return false;
94 }
95 break;
96
97 default:
98 break;
99 }
100
101 return this->frame_parser_.read_and_parse(this->device_, [this](uint8_t type, const uint8_t *payload, size_t len) {
102 return this->process_rx_packet_(type, payload, len);
103 });
104}
105
107 if (should_transition(this->state_, new_state)) {
108 ESP_LOGV(TAG, "Did transition: %s -> %s", LOG_STR_ARG(state_to_string(this->state_)),
109 LOG_STR_ARG(state_to_string(new_state)));
110 this->state_ = new_state;
111 this->did_transition_(new_state);
112 } else {
113 ESP_LOGV(TAG, "Ignoring unexpected transition %s -> %s", LOG_STR_ARG(state_to_string(this->state_)),
114 LOG_STR_ARG(state_to_string(new_state)));
115 }
116}
117
119 switch (to) {
121 return from == State::NOT_CONNECTED || from == State::READ_TIMEOUT;
122
123 case State::CONNECTED:
124 return from == State::CONNECTING;
125
128
130 return from == State::UPDATING_STATUS;
131
133 return from == State::CONNECTED || from == State::STATUS_UPDATED;
134
136 return from == State::STATUS_UPDATED || from == State::SETTINGS_APPLIED;
137
140
143
145 return from == State::APPLYING_SETTINGS;
146
148 return from == State::UPDATING_STATUS || from == State::APPLYING_SETTINGS || from == State::CONNECTING;
149
151 return false;
152 }
153 return false;
154}
155
157 switch (to) {
159 this->send_packet_(CONNECT_PACKET);
160 break;
161
162 case State::CONNECTED:
163 this->current_status_msg_type_ = STATUS_MSG_SETTINGS;
165 break;
166
168 this->update_status_();
169 break;
170
172 // When present, pending settings are applied from WAITING_FOR_SCHEDULED_STATUS_UPDATE during the next update(),
173 // deferring transmission to a later loop iteration; some units might not respond if a request is sent
174 // immediately after a response, causing the request to time out.
175 const bool should_apply_pending_settings = this->pending_updates_.any() && this->is_status_initialized();
176 const uint8_t next_msg_type = this->next_status_msg_type_();
177 if (!should_apply_pending_settings && next_msg_type != STATUS_MSG_NONE && this->should_request_telemetry_()) {
178 this->current_status_msg_type_ = next_msg_type;
180 break;
181 }
182 if (next_msg_type == STATUS_MSG_NONE) {
183 // The telemetry chain completed. An early refresh keeps the regular schedule and is spent until the next
184 // regular read, so a flapping setting cannot cause more than one extra read per interval.
185 if (this->is_telemetry_interval_elapsed_()) {
187 this->has_telemetry_update_ = true;
191 }
192 }
194 break;
195 }
196
200 this->current_status_msg_type_ = STATUS_MSG_SETTINGS;
202 break;
203
205 this->apply_settings_();
206 break;
207
210 break;
211
213 this->frame_parser_.reset();
216 break;
217
221 break;
222 }
223}
224
228
233
237
238// An early 0x06 read after a mode or power change, or the next read while the unit winds down.
241 (this->wind_down_reads_ != 0 && (get_loop_time_ms() - this->wind_down_read_ms_) >= WIND_DOWN_READ_INTERVAL_MS);
242}
243
244// A switch keeps the run going when the new mode drives it the same way: AUTO keeps any direction, and HEAT or COOL
245// continue a run of that direction. A run in AUTO of unknown direction counts as continuing.
246static constexpr bool continues_run(MitsubishiCN105::Mode from, MitsubishiCN105::Mode to,
248 using Mode = MitsubishiCN105::Mode;
249 using RunDirection = MitsubishiCN105::RunDirection;
250 if (to == Mode::AUTO) {
251 return direction != RunDirection::RUN_DIRECTION_NONE;
252 }
253 const RunDirection implied = to == Mode::HEAT ? RunDirection::RUN_DIRECTION_HEATING
254 : to == Mode::COOL ? RunDirection::RUN_DIRECTION_COOLING
255 : RunDirection::RUN_DIRECTION_NONE;
256 return implied != RunDirection::RUN_DIRECTION_NONE &&
257 (direction == implied || (from == Mode::AUTO && direction == RunDirection::RUN_DIRECTION_NONE));
258}
259
260// The unit keeps reporting "running" while it winds down from a run that a power-off or a mode change ended.
261// A change during a hold neither restarts nor ends it, since operating is already false.
262bool MitsubishiCN105::hold_if_run_ended_(bool was_on, Mode was_mode) {
263 if (!this->status_.operating || !was_on || this->is_operating_status_unsupported_()) {
264 return false;
265 }
266 if (this->status_.power_on &&
267 (was_mode == this->status_.mode || continues_run(was_mode, this->status_.mode, this->run_direction_))) {
268 return false;
269 }
270 this->status_.operating = false;
271 this->wind_down_reads_ = 1;
272 // The first read is due right away
273 this->wind_down_read_ms_ = get_loop_time_ms() - WIND_DOWN_READ_INTERVAL_MS;
274 return true;
275}
276
277// Called before a local power or mode change, so a change reverted before it is sent does not start a hold.
279 if (!this->pending_updates_.contains(PropertyId::POWER) && !this->pending_updates_.contains(PropertyId::MODE)) {
281 this->unsent_from_mode_ = this->status_.mode;
282 }
283}
284
285// AUTO keeps the direction of a run, and infers it from room vs. target temperature only when the run starts: a run
286// that starts at a tie stays without a direction, as the unit may still be overshooting either way.
288 if (!this->status_.power_on || !this->status_.operating) {
290 return;
291 }
292 switch (this->status_.mode) {
293 case Mode::HEAT:
295 break;
296 case Mode::COOL:
298 break;
299 case Mode::AUTO:
300 if (this->run_direction_ != RunDirection::RUN_DIRECTION_NONE || was_operating) {
301 break;
302 }
303 if (this->status_.room_temperature > this->status_.target_temperature) {
305 } else if (this->status_.room_temperature < this->status_.target_temperature) {
307 }
308 break;
309 default:
311 break;
312 }
313}
314
315// A mode or power change makes the operating status stale, so read it again without waiting for the interval.
316// A wind-down hold has its own reads.
323
325 switch (this->current_status_msg_type_) {
326 case STATUS_MSG_SETTINGS:
327 // An early refresh only needs the operating status.
328 return this->is_early_telemetry_refresh_() ? STATUS_MSG_OPERATING_STATUS : STATUS_MSG_ROOM_TEMPERATURE;
329 case STATUS_MSG_ROOM_TEMPERATURE:
330 return this->is_operating_status_unsupported_() ? STATUS_MSG_NONE : STATUS_MSG_OPERATING_STATUS;
331 default:
332 return STATUS_MSG_NONE;
333 }
334}
335
336// Changes are reported once the request chain ends, so a cycle publishes once with all of its responses applied.
339 return false;
340 }
341 const bool changed = this->status_changed_;
342 this->status_changed_ = false;
343 return changed;
344}
345
346void MitsubishiCN105::send_packet_(std::span<const uint8_t> packet) {
347 FrameParser::dump_buffer_vv("TX", packet.data(), packet.size());
348 this->device_.write_array(packet.data(), packet.size());
350}
351
353 std::array<uint8_t, REQUEST_PAYLOAD_LEN> payload{this->current_status_msg_type_};
354 this->send_packet_(make_packet(PACKET_TYPE_STATUS_REQUEST, payload));
355}
356
357bool MitsubishiCN105::process_rx_packet_(uint8_t type, const uint8_t *payload, size_t len) {
358 switch (type) {
359 case PACKET_TYPE_CONNECT_RESPONSE:
361 return false;
362
363 case PACKET_TYPE_STATUS_RESPONSE:
364 return this->process_status_packet_(payload, len);
365
366 case PACKET_TYPE_WRITE_SETTINGS_RESPONSE:
368 return false;
369
370 default:
371 ESP_LOGVV(TAG, "RX unknown packet type 0x%02X", type);
372 return false;
373 }
374}
375
376bool MitsubishiCN105::process_status_packet_(const uint8_t *payload, size_t len) {
377 if (len == 0) {
378 ESP_LOGVV(TAG, "RX status packet too short");
379 return false;
380 }
381
382 const auto previous = this->status_;
383 const auto msg_type = payload[0];
384 if (!this->parse_status_payload_(msg_type, payload + 1, len - 1)) {
385 return false;
386 }
387
388 const bool power_or_mode_changed = previous.power_on != this->status_.power_on || previous.mode != this->status_.mode;
389 if (power_or_mode_changed) {
390 this->hold_if_run_ended_(previous.power_on, previous.mode);
392 }
393 this->update_run_direction_(previous.operating);
394
395 if (msg_type == this->current_status_msg_type_) {
397 }
398
399 bool changed = power_or_mode_changed || previous.fan_mode != this->status_.fan_mode ||
400 previous.target_temperature != this->status_.target_temperature ||
401 previous.vane_mode != this->status_.vane_mode ||
402 previous.wide_vane_mode != this->status_.wide_vane_mode;
403
404 if (this->is_telemetry_polling_enabled()) {
405 changed |=
406 previous.room_temperature != this->status_.room_temperature || previous.operating != this->status_.operating;
407 }
408
409 this->status_changed_ |= changed;
410 return this->take_status_changed_();
411}
412
413bool MitsubishiCN105::parse_status_payload_(uint8_t msg_type, const uint8_t *payload, size_t len) {
414 Property::Decoder<UpdateFlags> decoder{std::span{payload, len}, this->property_context_, this->pending_updates_};
415 switch (msg_type) {
416 case STATUS_MSG_SETTINGS:
417 if (!decoder.decode_settings(this->status_)) {
418 ESP_LOGVV(TAG, "RX settings payload too short");
419 return false;
420 }
421 return true;
422
423 case STATUS_MSG_ROOM_TEMPERATURE:
424 if (!decoder.decode_room_temperature(this->status_)) {
425 ESP_LOGVV(TAG, "RX room temperature payload too short");
426 return false;
427 }
428 return true;
429
430 case STATUS_MSG_OPERATING_STATUS:
431 if (!decoder.decode_operating_status(this->status_)) {
432 ESP_LOGVV(TAG, "RX operating status payload too short");
433 return false;
434 }
435 this->operating_status_misses_ = 0;
436 // The hold ends at the first "stopped" report, or after WIND_DOWN_HELD_READS reads
437 if (this->wind_down_reads_ != 0 && this->status_.operating && this->wind_down_reads_ <= WIND_DOWN_HELD_READS) {
438 ESP_LOGV(TAG, "Ignoring running report during wind-down");
439 this->status_.operating = false;
440 this->wind_down_reads_++;
442 } else {
443 this->wind_down_reads_ = 0;
444 }
445 return true;
446
447 default:
448 ESP_LOGVV(TAG, "RX unsupported status msg type 0x%02X", msg_type);
449 return false;
450 }
451}
452
454 if (std::isnan(temperature)) {
455 ESP_LOGD(TAG, "Ignoring NaN remote temperature");
456 return;
457 }
459 ESP_LOGD(TAG, "Ignoring out-of-range remote temperature: %.1f", temperature);
460 return;
461 }
462 this->set_remote_temperature_half_deg_(static_cast<uint8_t>(std::round(temperature * 2.0f)));
463}
464
468
469void MitsubishiCN105::set_remote_temperature_half_deg_(uint8_t temperature_half_deg) {
470 this->remote_temperature_half_deg_ = temperature_half_deg;
472}
473
474void MitsubishiCN105::set_power(bool power_on) {
476 this->status_.power_on = power_on;
478}
479
482 ESP_LOGD(TAG, "Setting temperature out-of-range: %.1f", target_temperature);
483 return;
484 }
487}
488
492 ESP_LOGD(TAG, "Ignoring invalid mode: %u", static_cast<uint8_t>(mode));
493 }
494}
495
498 ESP_LOGD(TAG, "Ignoring invalid fan mode: %u", static_cast<uint8_t>(fan_mode));
499 }
500}
501
503 if (!Property::VaneMode::validate_and_set(vane_mode, this->status_, this->pending_updates_)) {
504 ESP_LOGD(TAG, "Ignoring invalid vane mode: %u", static_cast<uint8_t>(vane_mode));
505 }
506}
507
509 if (!Property::WideVaneMode::validate_and_set(wide_vane_mode, this->status_, this->pending_updates_)) {
510 ESP_LOGD(TAG, "Ignoring invalid wide vane mode: %u", static_cast<uint8_t>(wide_vane_mode));
511 }
512}
513
515 std::array<uint8_t, REQUEST_PAYLOAD_LEN> payload{};
516 Property::Encoder<UpdateFlags> encoder{payload.data(), this->property_context_, this->pending_updates_};
517 if (this->pending_updates_.contains(PropertyId::POWER) || this->pending_updates_.contains(PropertyId::MODE)) {
520 }
521 // Local changes reach the hold and the run direction only once they are sent; they never start a run
523
524 // Apply all other pending settings first; handle REMOTE_TEMPERATURE last
526 encoder.encode_remote_temperature(this->remote_temperature_half_deg_);
527 } else {
528 encoder.encode_settings(this->status_);
529 }
530
531 this->send_packet_(make_packet(PACKET_TYPE_WRITE_SETTINGS_REQUEST, payload));
532}
533
535 switch (state) {
537 return LOG_STR("Not connected");
539 return LOG_STR("Connecting");
540 case State::CONNECTED:
541 return LOG_STR("Connected");
543 return LOG_STR("UpdatingStatus");
545 return LOG_STR("StatusUpdated");
547 return LOG_STR("DeferredStatusRequest");
549 return LOG_STR("ScheduleNextStatusUpdate");
551 return LOG_STR("WaitingForScheduledStatusUpdate");
553 return LOG_STR("ApplyingSettings");
555 return LOG_STR("SettingsApplied");
557 return LOG_STR("ReadTimeout");
558 }
559 return LOG_STR("Unknown");
560}
561
562template<typename Callback>
564 uint8_t watchdog = 64;
565 while (device.available() > 0 && watchdog-- > 0) {
566 uint8_t &value = this->read_buffer_[this->read_pos_];
567 if (!device.read_byte(&value)) {
568 ESP_LOGW(TAG, "UART read failed while data available");
569 return false;
570 }
571
572 switch (++this->read_pos_) {
573 case 1:
574 if (value != PREAMBLE) {
575 this->reset_and_dump_buffer_("RX ignoring preamble");
576 }
577 continue;
578
579 case 2:
580 continue;
581
582 case 3:
583 if (value != HEADER_BYTE_1) {
584 this->reset_and_dump_buffer_("RX invalid: header 1 mismatch");
585 }
586 continue;
587
588 case 4:
589 if (value != HEADER_BYTE_2) {
590 this->reset_and_dump_buffer_("RX invalid: header 2 mismatch");
591 }
592 continue;
593
594 case HEADER_LEN:
595 static_assert(READ_BUFFER_SIZE > HEADER_LEN);
596 if (this->read_buffer_[HEADER_LEN - 1] >= READ_BUFFER_SIZE - HEADER_LEN) {
597 this->reset_and_dump_buffer_("RX invalid: payload too large");
598 }
599 continue;
600
601 default:
602 break;
603 }
604
605 const size_t len_without_checksum = HEADER_LEN + static_cast<size_t>(this->read_buffer_[HEADER_LEN - 1]);
606 if (this->read_pos_ <= len_without_checksum) {
607 continue;
608 }
609
610 if (checksum(this->read_buffer_, len_without_checksum) != value) {
611 this->reset_and_dump_buffer_("RX invalid: checksum mismatch");
612 continue;
613 }
614
615 dump_buffer_vv("RX", this->read_buffer_, this->read_pos_);
616 const bool processed =
617 callback(this->read_buffer_[1], this->read_buffer_ + HEADER_LEN, len_without_checksum - HEADER_LEN);
618 this->read_pos_ = 0;
619 return processed;
620 }
621
622 return false;
623}
624
626 dump_buffer_vv(prefix, this->read_buffer_, this->read_pos_);
627 this->read_pos_ = 0;
628}
629
630void MitsubishiCN105::FrameParser::dump_buffer_vv(const char *prefix, const uint8_t *data, size_t len) {
631 ESP_LOGVV_HEX(TAG, data, len, READ_BUFFER_SIZE, "%s (%zu): %s", prefix, len);
632}
633
634} // namespace esphome::mitsubishi_cn105
BedjetMode mode
BedJet operating mode.
uint8_t checksum
Definition bl0906.h:3
bool read_and_parse(uart::UARTDevice &device, Callback &&callback)
static void dump_buffer_vv(const char *prefix, const uint8_t *data, size_t len)
bool process_status_packet_(const uint8_t *payload, size_t len)
static bool should_transition(State from, State to)
static constexpr uint8_t OPERATING_STATUS_MAX_MISSES
void set_remote_temperature_half_deg_(uint8_t temperature_half_deg)
bool process_rx_packet_(uint8_t type, const uint8_t *payload, size_t len)
bool has_timed_out_(uint32_t timeout) const
static constexpr uint8_t REMOTE_TEMPERATURE_DISABLED
bool hold_if_run_ended_(bool was_on, Mode was_mode)
void send_packet_(std::span< const uint8_t > packet)
static const LogString * state_to_string(State state)
void set_target_temperature(float target_temperature)
bool parse_status_payload_(uint8_t msg_type, const uint8_t *payload, size_t len)
bool read_byte(uint8_t *data)
Definition uart.h:39
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
float target_temperature
Definition climate.h:0
ClimateFanMode fan_mode
Definition climate.h:3
uint8_t type
FanDirection direction
Definition fan.h:5
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "mitsubishi_cn105.driver")
constexpr uint8_t sum_bytes(const uint8_t *data, size_t len, uint8_t sum=0)
Add up the bytes of data with size len, truncated to 8 bits: the checksum many serial and IR protocol...
Definition helpers.h:939
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
static void uint32_t
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
Definition helpers.h:1893
static bool validate_and_set(Value value, Status &status, Mask &mask)
uint16_t temperature
Definition sun_gtil2.cpp:12
uint16_t length
Definition tt21100.cpp:0