ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
mitsubishi_cn105.cpp
Go to the documentation of this file.
1#include "mitsubishi_cn105.h"
3
4#include <algorithm>
5#include <array>
6#include <cmath>
8
10
11ESPHOME_LOG_TAG(TAG, "mitsubishi_cn105.driver");
12
13static constexpr uint32_t RESPONSE_TIMEOUT_MS = 2000;
14
15static constexpr size_t REQUEST_PAYLOAD_LEN = 0x10;
16
17static constexpr uint8_t PACKET_TYPE_CONNECT_REQUEST = 0x5A;
18static constexpr uint8_t PACKET_TYPE_CONNECT_RESPONSE = 0x7A;
19static constexpr std::array<uint8_t, 2> CONNECT_REQUEST_PAYLOAD = {0xCA, 0x01};
20
21static constexpr uint8_t PACKET_TYPE_STATUS_REQUEST = 0x42;
22static constexpr uint8_t PACKET_TYPE_STATUS_RESPONSE = 0x62;
23static constexpr uint8_t STATUS_MSG_NONE = 0x00;
24static constexpr uint8_t STATUS_MSG_SETTINGS = 0x02;
25static constexpr uint8_t STATUS_MSG_ROOM_TEMPERATURE = 0x03;
26static constexpr uint8_t STATUS_MSG_OPERATING_STATUS = 0x06;
27
28static constexpr uint8_t PACKET_TYPE_WRITE_SETTINGS_REQUEST = 0x41;
29static constexpr uint8_t PACKET_TYPE_WRITE_SETTINGS_RESPONSE = 0x61;
30
31// After a power-off or a mode change that ends the run, 0x06 is read this often while the unit winds down.
32static constexpr uint32_t WIND_DOWN_READ_INTERVAL_MS = 10000;
33
34static constexpr uint8_t checksum(const uint8_t *bytes, size_t length) {
35 return static_cast<uint8_t>(0xFC - sum_bytes(bytes, length));
36}
37
38static void dump_buffer_vv(const char *prefix, const uint8_t *data, size_t len) {
39 ESP_LOGVV_HEX(TAG, data, len, MAX_FRAME_SIZE, "%s (%zu): %s", prefix, len);
40}
41
42template<std::size_t PayloadSize>
43static constexpr auto make_packet(uint8_t type, const std::array<uint8_t, PayloadSize> &payload) {
44 const size_t full_len = PayloadSize + HEADER_LEN + 1;
45 std::array<uint8_t, full_len> packet{PREAMBLE, type, HEADER_BYTE_1, HEADER_BYTE_2, static_cast<uint8_t>(PayloadSize)};
46 std::copy_n(payload.begin(), PayloadSize, packet.begin() + HEADER_LEN);
47 packet.back() = checksum(packet.data(), packet.size() - 1);
48 return packet;
49}
50
51static constexpr auto CONNECT_PACKET = make_packet(PACKET_TYPE_CONNECT_REQUEST, CONNECT_REQUEST_PAYLOAD);
52
54
56 switch (this->state_) {
58 // Defer the next request to a later loop iteration; some units might not respond if a request is sent
59 // immediately after a response. See https://github.com/esphome/esphome/issues/18099. No minimum RX-to-TX delay
60 // is enforced.
62 return false;
63
65 if (this->pending_updates_.any()) {
69 // Publishes a hold started by the write
70 return this->take_status_changed_();
71 }
72 if (this->has_timed_out_(this->update_interval_ms_)) {
74 return false;
75 }
76 break;
77
81 if (this->has_timed_out_(RESPONSE_TIMEOUT_MS)) {
82 // Some units never answer 0x06: end the chain without reconnecting, and stop asking after a few misses.
83 // A dead link is still caught by the next 0x02 timeout.
84 if (this->state_ == State::UPDATING_STATUS && this->current_status_msg_type_ == STATUS_MSG_OPERATING_STATUS) {
86 ESP_LOGI(TAG, "No operating status response, climate action stays idle");
87 this->wind_down_reads_ = 0;
88 }
89 this->reader_.reset();
91 return this->take_status_changed_();
92 }
94 return false;
95 }
96 break;
97
98 default:
99 break;
100 }
101
102 bool changed = false;
103 const auto handle = [this, &changed](const uint8_t *frame, size_t len) {
104 const size_t len_without_checksum = len - 1;
105 if (checksum(frame, len_without_checksum) != frame[len_without_checksum]) {
106 dump_buffer_vv("RX invalid: checksum mismatch", frame, len);
107 return false;
108 }
109 dump_buffer_vv("RX", frame, len);
110 changed |= this->process_rx_packet_(frame[1], frame + HEADER_LEN, len_without_checksum - HEADER_LEN);
111 return true;
112 };
113 if (!this->device_.read_frames(this->reader_, handle, get_loop_time_ms(), this->last_rx_ms_)) {
114 ESP_LOGW(TAG, "UART read failed while data available");
115 }
116 return changed;
117}
118
120 if (should_transition(this->state_, new_state)) {
121 ESP_LOGV(TAG, "Did transition: %s -> %s", LOG_STR_ARG(state_to_string(this->state_)),
122 LOG_STR_ARG(state_to_string(new_state)));
123 this->state_ = new_state;
124 this->did_transition_(new_state);
125 } else {
126 ESP_LOGV(TAG, "Ignoring unexpected transition %s -> %s", LOG_STR_ARG(state_to_string(this->state_)),
127 LOG_STR_ARG(state_to_string(new_state)));
128 }
129}
130
132 switch (to) {
134 return from == State::NOT_CONNECTED || from == State::READ_TIMEOUT;
135
136 case State::CONNECTED:
137 return from == State::CONNECTING;
138
141
143 return from == State::UPDATING_STATUS;
144
146 return from == State::CONNECTED || from == State::STATUS_UPDATED;
147
149 return from == State::STATUS_UPDATED || from == State::SETTINGS_APPLIED;
150
153
156
158 return from == State::APPLYING_SETTINGS;
159
161 return from == State::UPDATING_STATUS || from == State::APPLYING_SETTINGS || from == State::CONNECTING;
162
164 return false;
165 }
166 return false;
167}
168
170 switch (to) {
172 this->send_packet_(CONNECT_PACKET);
173 break;
174
175 case State::CONNECTED:
176 this->current_status_msg_type_ = STATUS_MSG_SETTINGS;
178 break;
179
181 this->update_status_();
182 break;
183
185 // When present, pending settings are applied from WAITING_FOR_SCHEDULED_STATUS_UPDATE during the next update(),
186 // deferring transmission to a later loop iteration; some units might not respond if a request is sent
187 // immediately after a response, causing the request to time out.
188 const bool should_apply_pending_settings = this->pending_updates_.any() && this->is_status_initialized();
189 const uint8_t next_msg_type = this->next_status_msg_type_();
190 if (!should_apply_pending_settings && next_msg_type != STATUS_MSG_NONE && this->should_request_telemetry_()) {
191 this->current_status_msg_type_ = next_msg_type;
193 break;
194 }
195 if (next_msg_type == STATUS_MSG_NONE) {
196 // The telemetry chain completed. An early refresh keeps the regular schedule and is spent until the next
197 // regular read, so a flapping setting cannot cause more than one extra read per interval.
198 if (this->is_telemetry_interval_elapsed_()) {
200 this->has_telemetry_update_ = true;
204 }
205 }
207 break;
208 }
209
213 this->current_status_msg_type_ = STATUS_MSG_SETTINGS;
215 break;
216
218 this->apply_settings_();
219 break;
220
223 break;
224
226 this->reader_.reset();
229 break;
230
234 break;
235 }
236}
237
241
246
250
251// An early 0x06 read after a mode or power change, or the next read while the unit winds down.
254 (this->wind_down_reads_ != 0 && (get_loop_time_ms() - this->wind_down_read_ms_) >= WIND_DOWN_READ_INTERVAL_MS);
255}
256
257// A switch keeps the run going when the new mode drives it the same way: AUTO keeps any direction, and HEAT or COOL
258// continue a run of that direction. A run in AUTO of unknown direction counts as continuing.
259static constexpr bool continues_run(MitsubishiCN105::Mode from, MitsubishiCN105::Mode to,
261 using Mode = MitsubishiCN105::Mode;
262 using RunDirection = MitsubishiCN105::RunDirection;
263 if (to == Mode::AUTO) {
264 return direction != RunDirection::RUN_DIRECTION_NONE;
265 }
266 const RunDirection implied = to == Mode::HEAT ? RunDirection::RUN_DIRECTION_HEATING
267 : to == Mode::COOL ? RunDirection::RUN_DIRECTION_COOLING
268 : RunDirection::RUN_DIRECTION_NONE;
269 return implied != RunDirection::RUN_DIRECTION_NONE &&
270 (direction == implied || (from == Mode::AUTO && direction == RunDirection::RUN_DIRECTION_NONE));
271}
272
273// The unit keeps reporting "running" while it winds down from a run that a power-off or a mode change ended.
274// A change during a hold neither restarts nor ends it, since operating is already false.
275bool MitsubishiCN105::hold_if_run_ended_(bool was_on, Mode was_mode) {
276 if (!this->status_.operating || !was_on || this->is_operating_status_unsupported_()) {
277 return false;
278 }
279 if (this->status_.power_on &&
280 (was_mode == this->status_.mode || continues_run(was_mode, this->status_.mode, this->run_direction_))) {
281 return false;
282 }
283 this->status_.operating = false;
284 this->wind_down_reads_ = 1;
285 // The first read is due right away
286 this->wind_down_read_ms_ = get_loop_time_ms() - WIND_DOWN_READ_INTERVAL_MS;
287 return true;
288}
289
290// Called before a local power or mode change, so a change reverted before it is sent does not start a hold.
292 if (!this->pending_updates_.contains(PropertyId::POWER) && !this->pending_updates_.contains(PropertyId::MODE)) {
294 this->unsent_from_mode_ = this->status_.mode;
295 }
296}
297
298// AUTO keeps the direction of a run, and infers it from room vs. target temperature only when the run starts: a run
299// that starts at a tie stays without a direction, as the unit may still be overshooting either way.
301 if (!this->status_.power_on || !this->status_.operating) {
303 return;
304 }
305 switch (this->status_.mode) {
306 case Mode::HEAT:
308 break;
309 case Mode::COOL:
311 break;
312 case Mode::AUTO:
313 if (this->run_direction_ != RunDirection::RUN_DIRECTION_NONE || was_operating) {
314 break;
315 }
316 if (this->status_.room_temperature > this->status_.target_temperature) {
318 } else if (this->status_.room_temperature < this->status_.target_temperature) {
320 }
321 break;
322 default:
324 break;
325 }
326}
327
328// A mode or power change makes the operating status stale, so read it again without waiting for the interval.
329// A wind-down hold has its own reads.
336
338 switch (this->current_status_msg_type_) {
339 case STATUS_MSG_SETTINGS:
340 // An early refresh only needs the operating status.
341 return this->is_early_telemetry_refresh_() ? STATUS_MSG_OPERATING_STATUS : STATUS_MSG_ROOM_TEMPERATURE;
342 case STATUS_MSG_ROOM_TEMPERATURE:
343 return this->is_operating_status_unsupported_() ? STATUS_MSG_NONE : STATUS_MSG_OPERATING_STATUS;
344 default:
345 return STATUS_MSG_NONE;
346 }
347}
348
349// Changes are reported once the request chain ends, so a cycle publishes once with all of its responses applied.
352 return false;
353 }
354 const bool changed = this->status_changed_;
355 this->status_changed_ = false;
356 return changed;
357}
358
359void MitsubishiCN105::send_packet_(std::span<const uint8_t> packet) {
360 dump_buffer_vv("TX", packet.data(), packet.size());
361 this->device_.write_array(packet.data(), packet.size());
363}
364
366 std::array<uint8_t, REQUEST_PAYLOAD_LEN> payload{this->current_status_msg_type_};
367 this->send_packet_(make_packet(PACKET_TYPE_STATUS_REQUEST, payload));
368}
369
370bool MitsubishiCN105::process_rx_packet_(uint8_t type, const uint8_t *payload, size_t len) {
371 switch (type) {
372 case PACKET_TYPE_CONNECT_RESPONSE:
374 return false;
375
376 case PACKET_TYPE_STATUS_RESPONSE:
377 return this->process_status_packet_(payload, len);
378
379 case PACKET_TYPE_WRITE_SETTINGS_RESPONSE:
381 return false;
382
383 default:
384 ESP_LOGVV(TAG, "RX unknown packet type 0x%02X", type);
385 return false;
386 }
387}
388
389bool MitsubishiCN105::process_status_packet_(const uint8_t *payload, size_t len) {
390 if (len == 0) {
391 ESP_LOGVV(TAG, "RX status packet too short");
392 return false;
393 }
394
395 const auto previous = this->status_;
396 const auto msg_type = payload[0];
397 if (!this->parse_status_payload_(msg_type, payload + 1, len - 1)) {
398 return false;
399 }
400
401 const bool power_or_mode_changed = previous.power_on != this->status_.power_on || previous.mode != this->status_.mode;
402 if (power_or_mode_changed) {
403 this->hold_if_run_ended_(previous.power_on, previous.mode);
405 }
406 this->update_run_direction_(previous.operating);
407
408 if (msg_type == this->current_status_msg_type_) {
410 }
411
412 bool changed = power_or_mode_changed || previous.fan_mode != this->status_.fan_mode ||
413 previous.target_temperature != this->status_.target_temperature ||
414 previous.vane_mode != this->status_.vane_mode ||
415 previous.wide_vane_mode != this->status_.wide_vane_mode;
416
417 if (this->is_telemetry_polling_enabled()) {
418 changed |=
419 previous.room_temperature != this->status_.room_temperature || previous.operating != this->status_.operating;
420 }
421
422 this->status_changed_ |= changed;
423 return this->take_status_changed_();
424}
425
426bool MitsubishiCN105::parse_status_payload_(uint8_t msg_type, const uint8_t *payload, size_t len) {
427 Property::Decoder<UpdateFlags> decoder{std::span{payload, len}, this->property_context_, this->pending_updates_};
428 switch (msg_type) {
429 case STATUS_MSG_SETTINGS:
430 if (!decoder.decode_settings(this->status_)) {
431 ESP_LOGVV(TAG, "RX settings payload too short");
432 return false;
433 }
434 return true;
435
436 case STATUS_MSG_ROOM_TEMPERATURE:
437 if (!decoder.decode_room_temperature(this->status_)) {
438 ESP_LOGVV(TAG, "RX room temperature payload too short");
439 return false;
440 }
441 return true;
442
443 case STATUS_MSG_OPERATING_STATUS:
444 if (!decoder.decode_operating_status(this->status_)) {
445 ESP_LOGVV(TAG, "RX operating status payload too short");
446 return false;
447 }
448 this->operating_status_misses_ = 0;
449 // The hold ends at the first "stopped" report, or after WIND_DOWN_HELD_READS reads
450 if (this->wind_down_reads_ != 0 && this->status_.operating && this->wind_down_reads_ <= WIND_DOWN_HELD_READS) {
451 ESP_LOGV(TAG, "Ignoring running report during wind-down");
452 this->status_.operating = false;
453 this->wind_down_reads_++;
455 } else {
456 this->wind_down_reads_ = 0;
457 }
458 return true;
459
460 default:
461 ESP_LOGVV(TAG, "RX unsupported status msg type 0x%02X", msg_type);
462 return false;
463 }
464}
465
467 if (std::isnan(temperature)) {
468 ESP_LOGD(TAG, "Ignoring NaN remote temperature");
469 return;
470 }
472 ESP_LOGD(TAG, "Ignoring out-of-range remote temperature: %.1f", temperature);
473 return;
474 }
475 this->set_remote_temperature_half_deg_(static_cast<uint8_t>(std::round(temperature * 2.0f)));
476}
477
481
482void MitsubishiCN105::set_remote_temperature_half_deg_(uint8_t temperature_half_deg) {
483 this->remote_temperature_half_deg_ = temperature_half_deg;
485}
486
487void MitsubishiCN105::set_power(bool power_on) {
489 this->status_.power_on = power_on;
491}
492
495 ESP_LOGD(TAG, "Setting temperature out-of-range: %.1f", target_temperature);
496 return;
497 }
500}
501
505 ESP_LOGD(TAG, "Ignoring invalid mode: %u", static_cast<uint8_t>(mode));
506 }
507}
508
511 ESP_LOGD(TAG, "Ignoring invalid fan mode: %u", static_cast<uint8_t>(fan_mode));
512 }
513}
514
516 if (!Property::VaneMode::validate_and_set(vane_mode, this->status_, this->pending_updates_)) {
517 ESP_LOGD(TAG, "Ignoring invalid vane mode: %u", static_cast<uint8_t>(vane_mode));
518 }
519}
520
522 if (!Property::WideVaneMode::validate_and_set(wide_vane_mode, this->status_, this->pending_updates_)) {
523 ESP_LOGD(TAG, "Ignoring invalid wide vane mode: %u", static_cast<uint8_t>(wide_vane_mode));
524 }
525}
526
528 std::array<uint8_t, REQUEST_PAYLOAD_LEN> payload{};
529 Property::Encoder<UpdateFlags> encoder{payload.data(), this->property_context_, this->pending_updates_};
530 if (this->pending_updates_.contains(PropertyId::POWER) || this->pending_updates_.contains(PropertyId::MODE)) {
533 }
534 // Local changes reach the hold and the run direction only once they are sent; they never start a run
536
537 // Apply all other pending settings first; handle REMOTE_TEMPERATURE last
539 encoder.encode_remote_temperature(this->remote_temperature_half_deg_);
540 } else {
541 encoder.encode_settings(this->status_);
542 }
543
544 this->send_packet_(make_packet(PACKET_TYPE_WRITE_SETTINGS_REQUEST, payload));
545}
546
547// Indexed by State
548PROGMEM_STRING_TABLE(StateStrings, "Not connected", "Connecting", "Connected", "UpdatingStatus", "StatusUpdated",
549 "DeferredStatusRequest", "ScheduleNextStatusUpdate", "WaitingForScheduledStatusUpdate",
550 "ApplyingSettings", "SettingsApplied", "ReadTimeout", "Unknown");
551
552const LogString *MitsubishiCN105::state_to_string(State state) { return StateStrings::get_log_str(state); }
553
554} // namespace esphome::mitsubishi_cn105
BedjetMode mode
BedJet operating mode.
uint8_t checksum
Definition bl0906.h:3
void reset()
Forget the partial frame, for a request/response protocol starting a new exchange.
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)
LengthFrameReader< MAX_FRAME_SIZE, Frame > reader_
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)
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
bool read_frames(R &reader, F &&handle, uint32_t now, uint32_t &last_rx, uint32_t gap_ms=250)
Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx,...
Definition uart.h:96
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
PROGMEM_STRING_TABLE(StateStrings, "Not connected", "Connecting", "Connected", "UpdatingStatus", "StatusUpdated", "DeferredStatusRequest", "ScheduleNextStatusUpdate", "WaitingForScheduledStatusUpdate", "ApplyingSettings", "SettingsApplied", "ReadTimeout", "Unknown")
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:1086
const void size_t len
Definition hal.h:68
static void uint32_t
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
spi_device_handle_t handle