ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ecocomfort2_hub.cpp
Go to the documentation of this file.
2#ifdef USE_ESP32
3#include "ecocomfort2_hub.h"
5#include "esphome/core/log.h"
6
7#include <cmath>
8#include <cstdio>
9#include <cstring>
10
11namespace esphome::ecocomfort2 {
12
13ESPHOME_LOG_TAG(TAG, "ecocomfort2");
14
16#ifdef USE_BINARY_SENSOR
17 if (this->connected_binary_sensor_ != nullptr)
18 this->connected_binary_sensor_->publish_initial_state(false);
19#endif
20#ifdef USE_TIME
21 // The clock is written after each time-source sync
22 if (this->time_ != nullptr)
23 this->time_->add_on_time_sync_callback([this]() { this->sync_clock_(); });
24#endif
25}
26
27void Ecocomfort2Hub::update() {
28 if (!this->is_ready()) {
29 ESP_LOGD(TAG, "[%s] Not ready, skipping update", this->parent_->address_str());
30 return;
31 }
32 // The GATT client runs the requests one after the other
33 this->read_char_(this->char_handle_state_);
34 this->read_char_(this->char_handle_oper_);
35#ifdef USE_ECOCOMFORT2_SETTINGS
36 // The vendor app can change the settings too
37 this->read_settings_();
38#endif
39}
40
41bool Ecocomfort2Hub::write_char_(uint16_t handle, uint8_t *data, uint16_t len) {
42 auto status = esp_ble_gattc_write_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), handle, len, data,
43 ESP_GATT_WRITE_TYPE_NO_RSP, ESP_GATT_AUTH_REQ_NONE);
44 if (status != ESP_GATT_OK) {
45 ESP_LOGW(TAG, "[%s] Write to handle 0x%x failed, status=%d", this->parent_->address_str(), handle, status);
46 return false;
47 }
48 return true;
49}
50
52 auto status = esp_ble_gattc_read_char(this->parent_->get_gattc_if(), this->parent_->get_conn_id(), handle,
53 ESP_GATT_AUTH_REQ_NONE);
54 if (status != ESP_GATT_OK) {
55 ESP_LOGW(TAG, "[%s] Read request for handle 0x%x failed, status=%d", this->parent_->address_str(), handle, status);
56 return false;
57 }
58 return true;
59}
60
61void Ecocomfort2Hub::dump_config() {
62 ESP_LOGCONFIG(TAG,
63 "Ecocomfort2 Hub:\n"
64 " Address: %s",
65 this->parent_->address_str());
66 LOG_UPDATE_INTERVAL(this);
67#ifdef USE_TIME
68 ESP_LOGCONFIG(TAG, " Clock sync: %s", YESNO(this->time_ != nullptr));
69#endif
70#ifdef USE_SENSOR
71 LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
72 LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
73 LOG_SENSOR(" ", "VOC", this->voc_sensor_);
74 LOG_SENSOR(" ", "Direction", this->direction_sensor_);
75#endif
76#ifdef USE_BINARY_SENSOR
77 LOG_BINARY_SENSOR(" ", "Connected", this->connected_binary_sensor_);
78 LOG_BINARY_SENSOR(" ", "Boost", this->boost_binary_sensor_);
79#endif
80#ifdef USE_TEXT_SENSOR
81 LOG_TEXT_SENSOR(" ", "Firmware", this->firmware_text_sensor_);
82#endif
83#ifdef USE_ECOCOMFORT2_SETTINGS
84#ifdef USE_NUMBER
85 LOG_NUMBER(" ", "Humidity threshold",
87 LOG_NUMBER(" ", "Luminosity threshold",
89 LOG_NUMBER(" ", "VOC threshold", this->numbers_[static_cast<uint8_t>(NumberSetting::NUMBER_SETTING_VOC_THRESHOLD)]);
90 LOG_NUMBER(" ", "Temperature offset",
92 LOG_NUMBER(" ", "Humidity offset",
93 this->numbers_[static_cast<uint8_t>(NumberSetting::NUMBER_SETTING_HUMIDITY_OFFSET)]);
94#endif
95#ifdef USE_SWITCH
96 LOG_SWITCH(" ", "Humidity advanced",
98 LOG_SWITCH(" ", "VOC advanced", this->switches_[static_cast<uint8_t>(SwitchSetting::SWITCH_SETTING_VOC_ADVANCED)]);
99#endif
100#ifdef USE_SELECT
101 LOG_SELECT(" ", "Season", this->selects_[static_cast<uint8_t>(SelectSetting::SELECT_SETTING_SEASON)]);
102 LOG_SELECT(" ", "Free cooling", this->selects_[static_cast<uint8_t>(SelectSetting::SELECT_SETTING_FREE_COOLING)]);
103#endif
104#endif // USE_ECOCOMFORT2_SETTINGS
105}
106
107void Ecocomfort2Hub::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if,
108 esp_ble_gattc_cb_param_t *param) {
109 switch (event) {
110 case ESP_GATTC_DISCONNECT_EVT: {
111 ESP_LOGD(TAG, "[%s] Disconnected: reason=%d", this->parent_->address_str(), param->disconnect.reason);
114 this->status_set_warning();
115 this->char_handle_oper_ = 0;
116 this->char_handle_state_ = 0;
117 this->char_handle_info_ = 0;
118 this->char_handle_clock_ = 0;
119#ifdef USE_ECOCOMFORT2_SETTINGS
120 for (auto *settings : {&this->config_char_, &this->advanced_char_}) {
121 settings->handle = 0;
122 settings->known = settings->in_flight = settings->dirty = false;
123 }
124#endif
125 this->set_connected_(false);
126 this->publish_unknown_();
127 break;
128 }
129 case ESP_GATTC_SEARCH_CMPL_EVT: {
130 const auto service_uuid = espbt::ESPBTUUID::from_raw("f4b827c3-e660-4bc8-bdf6-3c8e9b845e0d");
131 const auto oper_uuid = espbt::ESPBTUUID::from_raw("b9d6f678-bc0d-4a73-90c8-60b0f07301f1");
132 const auto state_uuid = espbt::ESPBTUUID::from_raw("438d3433-7e5a-459a-a8e4-66343fad2bb0");
133 const auto info_uuid = espbt::ESPBTUUID::from_raw("f5f56229-dd4f-480f-a829-9189269d8b37");
134 const auto clock_uuid = espbt::ESPBTUUID::from_raw("82788997-49e4-4533-b949-7ed433678044");
135 // Keep the handles, not the characteristics: ble_client frees its services once all nodes are established.
136 auto *oper = this->parent_->get_characteristic(service_uuid, oper_uuid);
137 auto *state = this->parent_->get_characteristic(service_uuid, state_uuid);
138 if (oper == nullptr || state == nullptr) {
139 ESP_LOGW(TAG, "[%s] C_OPER or C_STATE characteristic not found, disconnecting", this->parent_->address_str());
140 this->parent_->disconnect();
141 break;
142 }
143 this->char_handle_oper_ = oper->handle;
144 this->char_handle_state_ = state->handle;
145 // The version and clock characteristics only feed optional features, so a unit without them still works
146 auto *info = this->parent_->get_characteristic(service_uuid, info_uuid);
147 this->char_handle_info_ = info != nullptr ? info->handle : 0;
148 auto *clock = this->parent_->get_characteristic(service_uuid, clock_uuid);
149 this->char_handle_clock_ = clock != nullptr ? clock->handle : 0;
150#ifdef USE_ECOCOMFORT2_SETTINGS
151 const auto config_uuid = espbt::ESPBTUUID::from_raw("d3dac48e-b4e1-4f3a-8715-326ddf1da89a");
152 const auto advanced_uuid = espbt::ESPBTUUID::from_raw("f8b2284e-61dd-44e3-a782-a93c9503ab2d");
153 auto *config = this->parent_->get_characteristic(service_uuid, config_uuid);
154 this->config_char_.handle = config != nullptr ? config->handle : 0;
155 auto *advanced = this->parent_->get_characteristic(service_uuid, advanced_uuid);
156 this->advanced_char_.handle = advanced != nullptr ? advanced->handle : 0;
157#endif
158 this->node_state = espbt::ClientState::ESTABLISHED;
159 this->status_set_warning();
160
161 // A bonded device may already have re-encrypted the link before discovery finished.
162 if (this->parent_->is_paired()) {
163 this->on_paired_();
164 break;
165 }
166 ESP_LOGI(TAG, "[%s] Requesting BLE encryption", this->parent_->address_str());
167 if (this->parent_->pair() != ESP_OK) {
168 ESP_LOGW(TAG, "[%s] BLE pair request failed, disconnecting", this->parent_->address_str());
169 this->parent_->disconnect();
170 break;
171 }
173 ESP_LOGW(TAG, "[%s] BLE authentication timed out, disconnecting", this->parent_->address_str());
174 this->parent_->disconnect();
175 });
176 break;
177 }
178 case ESP_GATTC_READ_CHAR_EVT: {
179 if (param->read.conn_id != this->parent_->get_conn_id()) {
180 break;
181 }
182 const uint16_t handle = param->read.handle;
183 if (handle == this->char_handle_oper_) {
184 if (this->read_ok_(param))
185 this->on_oper_(param->read.value, param->read.value_len);
186 } else if (handle == this->char_handle_state_) {
187 if (this->read_ok_(param))
188 this->on_state_(param->read.value, param->read.value_len);
189 } else if (handle == this->char_handle_info_) {
190 if (this->read_ok_(param))
191 this->on_info_(param->read.value, param->read.value_len);
192#ifdef USE_ECOCOMFORT2_SETTINGS
193 } else if (handle == this->config_char_.handle) {
194 if (this->settings_answer_current_(this->config_char_) && this->read_ok_(param))
195 this->on_config_(param->read.value, param->read.value_len);
196 } else if (handle == this->advanced_char_.handle) {
197 if (this->settings_answer_current_(this->advanced_char_) && this->read_ok_(param))
198 this->on_advanced_(param->read.value, param->read.value_len);
199#endif
200 }
201 break;
202 }
203 default:
204 break;
205 }
206}
207
208bool Ecocomfort2Hub::read_ok_(const esp_ble_gattc_cb_param_t *param) {
209 if (param->read.status == ESP_GATT_INSUF_ENCRYPTION || param->read.status == ESP_GATT_INSUF_AUTHENTICATION) {
210 // ble_client reconnects and pairs again
211 ESP_LOGW(TAG, "[%s] Encryption lost, disconnecting", this->parent_->address_str());
212 this->parent_->disconnect();
213 return false;
214 }
215 if (param->read.status != ESP_GATT_OK) {
216 ESP_LOGW(TAG, "[%s] Read of handle 0x%x failed, status=%d", this->parent_->address_str(), param->read.handle,
217 param->read.status);
218 return false;
219 }
220 return true;
221}
222
223void Ecocomfort2Hub::gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param) {
224 if (event != ESP_GAP_BLE_AUTH_CMPL_EVT || !this->parent_->check_addr(param->ble_security.auth_cmpl.bd_addr) ||
225 this->node_state != espbt::ClientState::ESTABLISHED) {
226 return;
227 }
228 if (!param->ble_security.auth_cmpl.success) {
230 ESP_LOGW(TAG, "[%s] BLE authentication failed, reason=%d, disconnecting", this->parent_->address_str(),
231 param->ble_security.auth_cmpl.fail_reason);
232 this->parent_->disconnect();
233 return;
234 }
235 this->on_paired_();
236}
237
240 this->status_clear_warning();
241 ESP_LOGI(TAG, "[%s] Encryption confirmed, device ready", this->parent_->address_str());
242 this->set_connected_(true);
243#ifdef USE_TIME
244 if (this->time_ != nullptr)
245 this->sync_clock_();
246#endif
247#ifdef USE_TEXT_SENSOR
248 if (this->firmware_text_sensor_ != nullptr && this->char_handle_info_ != 0)
249 this->read_char_(this->char_handle_info_);
250#endif
251 this->update();
252}
253
254void Ecocomfort2Hub::set_connected_(bool connected) {
255#ifdef USE_BINARY_SENSOR
256 PUBLISH_STATE(this->connected_binary_sensor_, connected);
257#endif
258}
259
260// Readings from a unit that is out of reach would otherwise look current for hours
262#ifdef USE_SENSOR
263 for (auto *sensor : {this->temperature_sensor_, this->humidity_sensor_, this->voc_sensor_, this->direction_sensor_}) {
264 PUBLISH_STATE(sensor, NAN);
265 }
266#endif
267#ifdef USE_BINARY_SENSOR
268 if (this->boost_binary_sensor_ != nullptr)
269 this->boost_binary_sensor_->invalidate_state();
270#endif
271}
272
273// C_OPER: mode byte, speed/flags byte
274void Ecocomfort2Hub::on_oper_(const uint8_t *data, uint16_t len) {
275 if (len < 2) {
276 ESP_LOGW(TAG, "[%s] C_OPER too short: %u bytes", this->parent_->address_str(), len);
277 return;
278 }
279 this->mode_ = data[0];
280 this->speed_ = data[1];
281 ESP_LOGD(TAG, "[%s] C_OPER: mode=0x%02x, speed=0x%02x", this->parent_->address_str(), this->mode_, this->speed_);
282#ifdef ECOCOMFORT2_CHILD_COUNT
283 for (auto *child : this->children_) {
284 child->on_status();
285 }
286#endif
287}
288
289// C_STATE: bytes 0-1 the mode and speed the unit runs; byte 1 also has the boost flag (0x40) and the advanced
290// control step (0x20). Byte 2 the air flow direction, bytes 3-4 temperature and 5-6 humidity in hundredths,
291// 7-8 VOC in ppb
292void Ecocomfort2Hub::on_state_(const uint8_t *data, uint16_t len) {
293 if (len < 9) {
294 ESP_LOGW(TAG, "[%s] C_STATE too short: %u bytes", this->parent_->address_str(), len);
295 return;
296 }
297 const float temperature = encode_value<int16_t>(&data[3]) / 100.0f;
298 const float humidity = encode_uint16(data[5], data[6]) / 100.0f;
299 const uint16_t voc = encode_uint16(data[7], data[8]);
300 ESP_LOGD(TAG, "[%s] C_STATE: mode=0x%02x, speed=0x%02x, %.2f °C, %.2f %%, %u ppb, direction=%u",
301 this->parent_->address_str(), data[0], data[1], temperature, humidity, voc, data[2]);
302#ifdef USE_BINARY_SENSOR
303 PUBLISH_STATE(this->boost_binary_sensor_, (data[1] & FLAG_BOOST) != 0);
304#endif
305#ifdef USE_SENSOR
306 PUBLISH_STATE(this->temperature_sensor_, temperature);
307 PUBLISH_STATE(this->humidity_sensor_, humidity);
308 PUBLISH_STATE(this->voc_sensor_, voc);
309 PUBLISH_STATE(this->direction_sensor_, data[2]);
310#endif
311}
312
313// C_INFO: firmware version packed as 4-bit major, 6-bit minor and 6-bit patch
314void Ecocomfort2Hub::on_info_(const uint8_t *data, uint16_t len) {
315 if (len < 2) {
316 ESP_LOGW(TAG, "[%s] C_INFO too short: %u bytes", this->parent_->address_str(), len);
317 return;
318 }
319 const uint16_t field = encode_uint16(data[0] & 0x0F, data[1]);
320 char version[12];
321 snprintf(version, sizeof(version), "%u.%u.%u", data[0] >> 4, field >> 6, field & 0x3F);
322 ESP_LOGD(TAG, "[%s] Firmware %s", this->parent_->address_str(), version);
323#ifdef USE_TEXT_SENSOR
324 PUBLISH_STATE(this->firmware_text_sensor_, version);
325#endif
326}
327
328#ifdef USE_TIME
329// C_CLOCK: two-digit year, month, day, weekday with Monday as 0, hour, minute, second, automatic DST flag
331 if (!this->is_ready() || this->char_handle_clock_ == 0)
332 return;
333 const ESPTime now = this->time_->now();
334 if (!now.is_valid())
335 return;
336 // ESPTime counts Sunday=1 .. Saturday=7, the unit Monday=0 .. Sunday=6
337 const uint8_t weekday = (now.day_of_week + 5) % 7;
338 // The time source already applies DST and every sync rewrites the clock, so the unit must not shift it again
339 uint8_t data[8]{
340 static_cast<uint8_t>(now.year % 100), now.month, now.day_of_month, weekday, now.hour, now.minute, now.second, 0};
341 ESP_LOGD(TAG, "[%s] Syncing clock to %04u-%02u-%02u %02u:%02u:%02u", this->parent_->address_str(), now.year,
342 now.month, now.day_of_month, now.hour, now.minute, now.second);
343 this->write_char_(this->char_handle_clock_, data, sizeof(data));
344}
345#endif
346
347void Ecocomfort2Hub::write_oper(uint8_t mode, uint8_t speed) {
348 if (!this->is_ready()) {
349 ESP_LOGW(TAG, "[%s] Not ready, cannot write C_OPER", this->parent_->address_str());
350 return;
351 }
352 uint8_t data[2]{mode, speed};
353 ESP_LOGD(TAG, "[%s] Writing C_OPER: mode=0x%02x, speed=0x%02x", this->parent_->address_str(), mode, speed);
354 if (!this->write_char_(this->char_handle_oper_, data, sizeof(data)))
355 return;
357}
358
359#ifdef USE_ECOCOMFORT2_SETTINGS
360// In a C_CONFIGURATION write, 0x7F in bytes 0-5 keeps the current value, as the vendor app does
361static constexpr uint8_t CONFIG_KEEP = 0x7F;
362// Threshold bytes: level 0-3 in the low bits, the advanced control flag in bit 7
363static constexpr uint8_t THRESHOLD_ADVANCED = 0x80;
364static constexpr uint8_t THRESHOLD_LEVEL_MASK = 0x7F;
365// Byte 4: season in the high nibble (0 winter, 1 summer), free cooling level 0-3 in the low nibble
366static constexpr uint8_t SEASON_BYTE = 4;
367static constexpr uint8_t SEASON_MASK = 0xF0;
368static constexpr uint8_t FREE_COOLING_MASK = 0x0F;
369static constexpr uint8_t SEASON_SUMMER = 0x10;
370// Nibble values that keep the current season or free cooling level
371static constexpr uint8_t KEEP_SEASON = 0x70;
372static constexpr uint8_t KEEP_FREE_COOLING = 0x0F;
373// The thresholds the humidity and VOC advanced flags belong to
374static constexpr NumberSetting ADVANCED_THRESHOLD[] = {NumberSetting::NUMBER_SETTING_HUMIDITY_THRESHOLD,
376
377// The thresholds are C_CONFIGURATION bytes 1-3
378static constexpr uint8_t threshold_byte(NumberSetting setting) { return static_cast<uint8_t>(setting) + 1; }
379
380// The unit answers within a few seconds; after this long an answer was lost (the BLE event pool was full) and
381// the read starts over, which can at worst accept one late answer as current until the next poll
382static constexpr uint32_t SETTINGS_READ_STALL_MS = 30000;
383
385 if (settings.in_flight) {
386 settings.dirty = true;
387 return;
388 }
389 if (this->read_char_(settings.handle)) {
390 settings.in_flight = true;
392 }
393}
394
395// Clears the read in flight. A write sent since makes its answer stale, so the read is sent again
397 settings.in_flight = false;
398 if (!settings.dirty)
399 return true;
400 settings.dirty = false;
401 this->request_settings_(settings);
402 return false;
403}
404
407 for (auto *settings : {&this->config_char_, &this->advanced_char_}) {
408 if (!settings->needed || settings->handle == 0)
409 continue;
410 if (settings->in_flight) {
411 if (now - settings->sent_ms <= SETTINGS_READ_STALL_MS)
412 continue;
413 ESP_LOGW(TAG, "[%s] Settings read not answered, retrying", this->parent_->address_str());
414 settings->in_flight = settings->dirty = false;
415 }
416 this->request_settings_(*settings);
417 }
418}
419
421 if (!settings.known) {
422 ESP_LOGW(TAG, "[%s] Settings not read yet", this->parent_->address_str());
423 }
424 return settings.known;
425}
426
427// C_CONFIGURATION: role, the humidity, luminosity and VOC thresholds, season and free cooling, then the
428// fields for a unit paired to another one, which are left alone
429void Ecocomfort2Hub::on_config_(const uint8_t *data, uint16_t len) {
430 if (len < sizeof(this->config_bytes_)) {
431 ESP_LOGW(TAG, "[%s] C_CONFIGURATION too short: %u bytes", this->parent_->address_str(), len);
432 return;
433 }
434 if (!this->config_char_.known || memcmp(this->config_bytes_, data, sizeof(this->config_bytes_)) != 0) {
435 ESP_LOGD(TAG, "[%s] C_CONFIGURATION: thresholds=0x%02x 0x%02x 0x%02x, season=0x%02x", this->parent_->address_str(),
436 data[1], data[2], data[3], data[SEASON_BYTE]);
437 }
438 memcpy(this->config_bytes_, data, sizeof(this->config_bytes_));
439 this->config_char_.known = true;
440 this->publish_config_();
441}
442
443// C_ADVANCED_SETTINGS: temperature and humidity offsets in hundredths, signed big-endian
444void Ecocomfort2Hub::on_advanced_(const uint8_t *data, uint16_t len) {
445 if (len < 4) {
446 ESP_LOGW(TAG, "[%s] C_ADVANCED_SETTINGS too short: %u bytes", this->parent_->address_str(), len);
447 return;
448 }
449 const int16_t temperature = encode_value<int16_t>(data);
450 const int16_t humidity = encode_value<int16_t>(data + 2);
451 if (!this->advanced_char_.known || this->offsets_[0] != temperature || this->offsets_[1] != humidity) {
452 ESP_LOGD(TAG, "[%s] C_ADVANCED_SETTINGS: offsets %d %d", this->parent_->address_str(), temperature, humidity);
453 }
454 this->offsets_[0] = temperature;
455 this->offsets_[1] = humidity;
456 this->advanced_char_.known = true;
457 this->publish_offsets_();
458}
459
460// Numbers and selects run their callbacks on every publish, so an unchanged value is skipped: an on_value
461// automation that writes another setting must not trigger itself again
462#ifdef USE_NUMBER
463static void publish_if_changed(number::Number *number, float value) {
464 if (number != nullptr && (!number->has_state() || number->state != value))
465 number->publish_state(value);
466}
467#endif
468#ifdef USE_SELECT
469static void publish_if_changed(select::Select *select, size_t index) {
470 if (select == nullptr)
471 return;
472 const auto current = select->active_index();
473 if (!current.has_value() || *current != index)
474 select->publish_state(index);
475}
476#endif
477
479#ifdef USE_NUMBER
480 for (uint8_t i = 0; i < static_cast<uint8_t>(NumberSetting::NUMBER_SETTING_TEMPERATURE_OFFSET); i++)
481 publish_if_changed(this->numbers_[i], this->config_bytes_[i + 1] & THRESHOLD_LEVEL_MASK);
482#endif
483#ifdef USE_SWITCH
484 for (uint8_t i = 0; i < static_cast<uint8_t>(SwitchSetting::SWITCH_SETTING_COUNT); i++) {
485 const uint8_t threshold = this->config_bytes_[threshold_byte(ADVANCED_THRESHOLD[i])];
486 // The flag only counts while the threshold is set
487 PUBLISH_STATE(this->switches_[i], (threshold & THRESHOLD_ADVANCED) && (threshold & THRESHOLD_LEVEL_MASK));
488 }
489#endif
490#ifdef USE_SELECT
491 const uint8_t &season_byte = this->config_bytes_[SEASON_BYTE];
492 auto *season = this->selects_[static_cast<uint8_t>(SelectSetting::SELECT_SETTING_SEASON)];
493 publish_if_changed(season, static_cast<size_t>((season_byte & SEASON_SUMMER) != 0));
494 // The unit keeps the free cooling level through winter but only runs it in summer. The season's on_value
495 // automations may have changed the season, so it is read again.
496 auto *free_cooling = this->selects_[static_cast<uint8_t>(SelectSetting::SELECT_SETTING_FREE_COOLING)];
497 const uint8_t level = (season_byte & SEASON_SUMMER) != 0 ? season_byte & FREE_COOLING_MASK : 0;
498 if (free_cooling != nullptr && free_cooling->has_index(level))
499 publish_if_changed(free_cooling, static_cast<size_t>(level));
500#endif
501}
502
504#ifdef USE_NUMBER
505 for (uint8_t i = 0; i < 2; i++) {
506 publish_if_changed(this->numbers_[static_cast<uint8_t>(NumberSetting::NUMBER_SETTING_TEMPERATURE_OFFSET) + i],
507 this->offsets_[i] / 100.0f);
508 }
509#endif
510}
511
512// The read sent after the write returns what it stored, and a read already in flight is sent again
513bool Ecocomfort2Hub::write_settings_(SettingsChar &settings, uint8_t *data, uint16_t len) {
514 if (!this->is_ready() || settings.handle == 0) {
515 ESP_LOGW(TAG, "[%s] Not ready, cannot change the setting", this->parent_->address_str());
516 return false;
517 }
518 if (!this->write_char_(settings.handle, data, len))
519 return false;
520 this->request_settings_(settings);
521 return true;
522}
523
524// The readback takes seconds, so the copy and entities follow the write now; it corrects a refused write
525void Ecocomfort2Hub::write_config_(uint8_t index, uint8_t value, uint8_t stored) {
526 // Bytes 6-11 hold the address of the main unit for a secondary one; the unit ignores them while the role byte
527 // is keep, and the vendor app sends them as 0x00 too
528 uint8_t data[12]{CONFIG_KEEP, CONFIG_KEEP, CONFIG_KEEP, CONFIG_KEEP, CONFIG_KEEP, CONFIG_KEEP};
529 data[index] = value;
530 ESP_LOGD(TAG, "[%s] Writing C_CONFIGURATION byte %u: 0x%02x", this->parent_->address_str(), index, value);
531 if (!this->write_settings_(this->config_char_, data, sizeof(data)))
532 return;
533 this->config_bytes_[index] = stored;
534 this->publish_config_();
535}
536
537void Ecocomfort2Hub::write_offsets_(int16_t temperature, int16_t humidity) {
538 const auto temperature_bytes = decode_value(static_cast<uint16_t>(temperature));
539 const auto humidity_bytes = decode_value(static_cast<uint16_t>(humidity));
540 uint8_t data[4]{temperature_bytes[0], temperature_bytes[1], humidity_bytes[0], humidity_bytes[1]};
541 ESP_LOGD(TAG, "[%s] Writing C_ADVANCED_SETTINGS: offsets %d %d", this->parent_->address_str(), temperature, humidity);
542 if (!this->write_settings_(this->advanced_char_, data, sizeof(data)))
543 return;
544 this->offsets_[0] = temperature;
545 this->offsets_[1] = humidity;
546 this->publish_offsets_();
547}
548
549#ifdef USE_NUMBER
550void Ecocomfort2Hub::write_number(NumberSetting setting, float value) {
552 // Both offsets go in one write, so the other one must be known
553 if (!this->settings_known_(this->advanced_char_))
554 return;
555 int16_t offsets[2]{this->offsets_[0], this->offsets_[1]};
556 offsets[setting == NumberSetting::NUMBER_SETTING_HUMIDITY_OFFSET] = static_cast<int16_t>(lroundf(value * 100.0f));
557 this->write_offsets_(offsets[0], offsets[1]);
558 return;
559 }
560 // A threshold keeps its advanced flag, which only exists while the threshold is set
561 if (!this->settings_known_(this->config_char_))
562 return;
563 const uint8_t index = threshold_byte(setting);
564 const uint8_t level = static_cast<uint8_t>(lroundf(value));
565 const bool advanced = (this->config_bytes_[index] & THRESHOLD_ADVANCED) != 0 && level > 0;
566 const uint8_t threshold = level | (advanced ? THRESHOLD_ADVANCED : 0);
567 this->write_config_(index, threshold, threshold);
568}
569#endif
570
571#ifdef USE_SWITCH
572void Ecocomfort2Hub::write_switch(SwitchSetting setting, bool state) {
573 if (!this->settings_known_(this->config_char_))
574 return;
575 const uint8_t index = threshold_byte(ADVANCED_THRESHOLD[static_cast<uint8_t>(setting)]);
576 const uint8_t level = this->config_bytes_[index] & THRESHOLD_LEVEL_MASK;
577 if (state && level == 0) {
578 ESP_LOGW(TAG, "[%s] Set the threshold before turning on advanced control", this->parent_->address_str());
579 return;
580 }
581 const uint8_t threshold = level | (state ? THRESHOLD_ADVANCED : 0);
582 this->write_config_(index, threshold, threshold);
583}
584#endif
585
586#ifdef USE_SELECT
587// The written byte keeps the other nibble with its keep value; the local copy takes the new nibble directly
588void Ecocomfort2Hub::write_select(SelectSetting setting, size_t index) {
589 if (!this->settings_known_(this->config_char_))
590 return;
591 const uint8_t season_byte = this->config_bytes_[SEASON_BYTE];
593 const uint8_t season = index == 1 ? SEASON_SUMMER : 0;
594 this->write_config_(SEASON_BYTE, season | KEEP_FREE_COOLING, season | (season_byte & FREE_COOLING_MASK));
595 return;
596 }
597 // The unit only runs free cooling in summer and keeps its level through winter, so even Off is refused then
598 if ((season_byte & SEASON_SUMMER) == 0) {
599 ESP_LOGW(TAG, "[%s] Free cooling is only available in summer", this->parent_->address_str());
600 return;
601 }
602 const uint8_t level = static_cast<uint8_t>(index);
603 this->write_config_(SEASON_BYTE, KEEP_SEASON | level, (season_byte & SEASON_MASK) | level);
604}
605#endif
606#endif // USE_ECOCOMFORT2_SETTINGS
607
608#ifdef ECOCOMFORT2_CHILD_COUNT
609void Ecocomfort2Hub::register_child(Ecocomfort2Client *obj) {
610 this->children_.push_back(obj);
611 obj->set_parent(this);
612}
613#endif
614
615} // namespace esphome::ecocomfort2
616
617#endif // USE_ESP32
BedjetMode mode
BedJet operating mode.
uint8_t status
Definition bl0942.h:8
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
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
bool has_state() const
bool settings_known_(const SettingsChar &settings)
static constexpr uint32_t READBACK_DELAY_MS
bool write_char_(uint16_t handle, uint8_t *data, uint16_t len)
void on_advanced_(const uint8_t *data, uint16_t len)
void write_config_(uint8_t index, uint8_t value, uint8_t stored)
Write one C_CONFIGURATION byte, leaving the others as they are, and keep stored as its local copy.
static constexpr uint32_t AUTH_TIMEOUT_ID
void on_state_(const uint8_t *data, uint16_t len)
void on_config_(const uint8_t *data, uint16_t len)
void on_info_(const uint8_t *data, uint16_t len)
void write_offsets_(int16_t temperature, int16_t humidity)
StaticVector< Ecocomfort2Client *, ECOCOMFORT2_CHILD_COUNT > children_
bool settings_answer_current_(SettingsChar &settings)
switch_::Switch * switches_[static_cast< uint8_t >(SwitchSetting::SWITCH_SETTING_COUNT)]
void request_settings_(SettingsChar &settings)
bool write_settings_(SettingsChar &settings, uint8_t *data, uint16_t len)
static constexpr uint32_t READBACK_TIMEOUT_ID
select::Select * selects_[static_cast< uint8_t >(SelectSetting::SELECT_SETTING_COUNT)]
bool read_ok_(const esp_ble_gattc_cb_param_t *param)
void on_oper_(const uint8_t *data, uint16_t len)
number::Number * numbers_[static_cast< uint8_t >(NumberSetting::NUMBER_SETTING_COUNT)]
static constexpr uint32_t AUTH_TIMEOUT_MS
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
Base-class for all numbers.
Definition number.h:29
void publish_state(float state)
Definition number.cpp:20
Base-class for all selects.
Definition select.h:28
optional< size_t > active_index() const
Return the (optional) index offset of the currently active option.
Definition select.cpp:45
void publish_state(const std::string &state)
Definition select.h:35
ESPTime now()
Get the time in the currently defined timezone.
void add_on_time_sync_callback(F &&callback)
int speed
Definition fan.h:3
bool state
Definition fan.h:2
ESPHOME_LOG_TAG(TAG, "ecocomfort2.fan")
uint32_t value
Definition hal.cpp:41
const void size_t len
Definition hal.h:68
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
Definition helpers.h:1064
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
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
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
A more user-friendly version of struct tm from time.h.
Definition time.h:23
uint8_t minute
minutes after the hour [0-59]
Definition time.h:32
uint8_t second
seconds after the minute [0-60]
Definition time.h:30
uint8_t hour
hours since midnight [0-23]
Definition time.h:34
bool is_valid(bool check_day_of_week=true, bool check_day_of_year=true) const
Check if this ESPTime is valid (year >= 2019 and the requested fields are in range).
Definition time.h:82
uint8_t day_of_month
day of the month [1-31]
Definition time.h:38
uint16_t year
year
Definition time.h:44
uint8_t month
month; january=1 [1-12]
Definition time.h:42
uint8_t day_of_week
day of the week; sunday=1 [1-7]
Definition time.h:36
One settings characteristic. Only one read is in flight at a time; a write sent meanwhile makes its a...
uint16_t temperature
Definition sun_gtil2.cpp:12
spi_device_handle_t handle