ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
tuya.cpp
Go to the documentation of this file.
1#include "tuya.h"
2#include "esphome/core/gpio.h"
4#include "esphome/core/log.h"
5#include "esphome/core/util.h"
6
7#ifdef USE_NETWORK
9#endif
10
11#ifdef USE_WIFI
13#endif
14
15#ifdef USE_CAPTIVE_PORTAL
17#endif
18
19namespace esphome::tuya {
20
21ESPHOME_LOG_TAG(TAG, "tuya");
22
23static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
24static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
25static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
26static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
27static const int COMMAND_DELAY = 10;
28static const int RECEIVE_TIMEOUT = 300;
29static const int MAX_RETRIES = 5;
30// Max bytes to log for datapoint values (larger values are truncated)
31static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
32static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
33
34static bool network_is_connected() {
35#ifdef USE_NETWORK
36 return network::is_connected();
37#else
38 return false;
39#endif
40}
41
43 this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
44#ifdef USE_TIME
45 if (this->force_time_sync_) {
47 this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
48 [this] { this->check_force_time_sync_(); });
49 }
50#endif
51 if (this->status_pin_ != nullptr) {
52 this->status_pin_->digital_write(false);
53 }
54}
55
56void Tuya::loop() {
57 this->read_available([this](uint8_t b) { this->handle_char_(b); });
59}
60
62 ESP_LOGCONFIG(TAG, "Tuya:");
64 if (this->init_failed_) {
65 ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
66 } else {
67 ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
68 static_cast<uint8_t>(this->init_state_));
69 }
70 ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
71 return;
72 }
73 for (auto &info : this->datapoints_) {
74 if (info.type == TuyaDatapointType::RAW) {
75 char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
76 ESP_LOGCONFIG(TAG, " Datapoint %u: raw (value: %s)", info.id,
77 format_hex_pretty_to(hex_buf, info.value_raw.data(), info.value_raw.size()));
78 } else if (info.type == TuyaDatapointType::BOOLEAN) {
79 ESP_LOGCONFIG(TAG, " Datapoint %u: switch (value: %s)", info.id, ONOFF(info.value_bool));
80 } else if (info.type == TuyaDatapointType::INTEGER) {
81 ESP_LOGCONFIG(TAG, " Datapoint %u: int value (value: %d)", info.id, info.value_int);
82 } else if (info.type == TuyaDatapointType::STRING) {
83 ESP_LOGCONFIG(TAG, " Datapoint %u: string value (value: %s)", info.id, info.value_string.c_str());
84 } else if (info.type == TuyaDatapointType::ENUM) {
85 ESP_LOGCONFIG(TAG, " Datapoint %u: enum (value: %d)", info.id, info.value_enum);
86 } else if (info.type == TuyaDatapointType::BITMASK) {
87 ESP_LOGCONFIG(TAG, " Datapoint %u: bitmask (value: %" PRIx32 ")", info.id, info.value_bitmask);
88 } else {
89 ESP_LOGCONFIG(TAG, " Datapoint %u: unknown", info.id);
90 }
91 }
92 if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
93 ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
95 }
96 LOG_PIN(" Status Pin: ", this->status_pin_);
97 ESP_LOGCONFIG(TAG, " Product: '%s'",
98 this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
99 : (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
100#ifdef USE_TIME
101 if (this->time_id_ != nullptr) {
102 ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
103 }
104#endif
105}
106
108 uint32_t at = this->rx_message_.size() - 1;
109 auto *data = &this->rx_message_[0];
110 uint8_t new_byte = data[at];
111
112 // Byte 0: HEADER1 (always 0x55)
113 if (at == 0)
114 return new_byte == 0x55;
115 // Byte 1: HEADER2 (always 0xAA)
116 if (at == 1)
117 return new_byte == 0xAA;
118
119 // Byte 2: VERSION
120 // no validation for the following fields:
121 uint8_t version = data[2];
122 if (at == 2)
123 return true;
124 // Byte 3: COMMAND
125 uint8_t command = data[3];
126 if (at == 3)
127 return true;
128
129 // Byte 4: LENGTH1
130 // Byte 5: LENGTH2
131 if (at <= 5) {
132 // no validation for these fields
133 return true;
134 }
135
136 uint16_t length = encode_uint16(data[4], data[5]);
137
138 // wait until all data is read
139 if (at - 6 < length)
140 return true;
141
142 // Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
143 uint8_t rx_checksum = new_byte;
144 const uint8_t calc_checksum = sum_bytes(data, 6 + length);
145
146 if (rx_checksum != calc_checksum) {
147 ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
148 return false;
149 }
150
151 // valid message
152 const uint8_t *message_data = data + 6;
153#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
154 char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
155 ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
156 format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
157#endif
158 this->handle_command_(command, version, message_data, length);
159
160 // return false to reset rx buffer
161 return false;
162}
163
164void Tuya::handle_char_(uint8_t c) {
165 this->rx_message_.push_back(c);
166 if (!this->validate_message_()) {
167 this->rx_message_.clear();
168 } else {
170 }
171}
172
173void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
174 TuyaCommandType command_type = (TuyaCommandType) command;
175
176 if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
177 this->expected_response_.reset();
178 this->command_queue_.erase(command_queue_.begin());
179 this->init_retries_ = 0;
180 }
181
182 switch (command_type) {
184 ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
185 this->protocol_version_ = version;
186 if (buffer[0] == 0) {
187 ESP_LOGI(TAG, "MCU restarted");
189 }
193 }
194 break;
196 // check it is a valid string made up of printable characters
197 bool valid = true;
198 for (size_t i = 0; i < len; i++) {
199 if (!std::isprint(buffer[i])) {
200 valid = false;
201 break;
202 }
203 }
204 if (valid) {
205 this->product_ = std::make_unique<char[]>(len + 1);
206 memcpy(this->product_.get(), buffer, len);
207 } else {
208 this->product_.reset();
209 }
210 this->product_invalid_ = !valid;
214 }
215 break;
216 }
218 if (len >= 2) {
219 this->status_pin_reported_ = buffer[0];
220 this->reset_pin_reported_ = buffer[1];
221 }
223 // If mcu returned status gpio, then we can omit sending wifi state
224 if (this->status_pin_reported_ != -1) {
227 if (this->status_pin_ != nullptr) {
228 if (this->status_pin_->get_pin() != this->status_pin_reported_) {
229 ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
231 }
232 ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
233 this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
234 } else {
235 ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
237 }
238 } else {
240 ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
241 this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
242 }
243 }
244 break;
245 }
250 }
251 break;
254 const bool is_select = (len >= 1);
255 // Send WIFI_SELECT ACK
258 ack.payload.clear();
259 this->send_command_(ack);
260 // Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
261 uint8_t first = 0x00;
262 const char *mode_str = "EZ";
263 if (is_select && buffer[0] == 0x01) {
264 first = 0x01;
265 mode_str = "AP";
266 }
267 // Send WIFI_STATE response, MCU exits pairing mode
268 TuyaCommand st;
270 st.payload.resize(1);
271 st.payload[0] = first;
272 this->send_command_(st);
273 st.payload[0] = 0x02;
274 this->send_command_(st);
275 st.payload[0] = 0x03;
276 this->send_command_(st);
277 st.payload[0] = 0x04;
278 this->send_command_(st);
279 ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
280 is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
281 break;
282 }
284 break;
289 this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_config(); });
290 this->initialized_callback_.call();
291 }
292 this->handle_datapoints_(buffer, len);
293
294 if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
295 this->send_command_(
296 TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
297 }
298 break;
300 break;
302 this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
303 break;
305 this->send_command_(
306 TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
307 break;
309#ifdef USE_TIME
310 if (this->time_id_ != nullptr) {
311 this->send_local_time_();
313 } else
314#endif
315 {
316 ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
317 }
318 break;
320#ifdef USE_TIME
321 if (this->time_id_ != nullptr) {
322 this->send_gmt_time_();
323
325 // tuya mcu supports time, so we let them know when our time changed
326 this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
328 }
329 } else
330#endif
331 {
332 ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
333 }
334 break;
336 this->send_command_(
337 TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
338 ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
339 break;
341 uint8_t wifi_status = this->get_wifi_status_code_();
342
343 this->send_command_(
344 TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
345 ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
346 break;
347 }
349 uint8_t subcommand = buffer[0];
350 switch ((TuyaExtendedServicesCommandType) subcommand) {
352 this->send_command_(
354 .payload = std::vector<uint8_t>{
355 static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
356 ESP_LOGV(TAG, "Reset status notification enabled");
357 break;
358 }
360 ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
361 break;
362 }
364 ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
365 break;
366 }
367 default:
368 ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
369 }
370 break;
371 }
372 default:
373 ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
374 }
375}
376
377void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
378 while (len >= 4) {
379 TuyaDatapoint datapoint{};
380 datapoint.id = buffer[0];
381 datapoint.type = (TuyaDatapointType) buffer[1];
382 datapoint.value_uint = 0;
383
384 size_t data_size = encode_uint16(buffer[2], buffer[3]);
385 const uint8_t *data = buffer + 4;
386 size_t data_len = len - 4;
387 if (data_size > data_len) {
388 ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
389 return;
390 }
391
392 datapoint.len = data_size;
393
394 switch (datapoint.type) {
396 datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
397 {
398 char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
399 ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
400 format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
401 }
402 break;
404 if (data_size != 1) {
405 ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
406 return;
407 }
408 datapoint.value_bool = data[0];
409 ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
410 break;
412 if (data_size != 4) {
413 ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
414 return;
415 }
416 datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
417 ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
418 break;
420 datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
421 ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
422 break;
424 if (data_size != 1) {
425 ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
426 return;
427 }
428 datapoint.value_enum = data[0];
429 ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
430 break;
432 switch (data_size) {
433 case 1:
434 datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
435 break;
436 case 2:
437 datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
438 break;
439 case 4:
440 datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
441 break;
442 default:
443 ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
444 return;
445 }
446 ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
447 break;
448 default:
449 ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
450 return;
451 }
452
453 len -= data_size + 4;
454 buffer = data + data_size;
455
456 // drop update if datapoint is in ignore_mcu_datapoint_update list
457 bool skip = false;
458 for (auto i : this->ignore_mcu_update_on_datapoints_) {
459 if (datapoint.id == i) {
460 ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
461 skip = true;
462 break;
463 }
464 }
465 if (skip)
466 continue;
467
468 // Update internal datapoints
469 bool found = false;
470 for (auto &other : this->datapoints_) {
471 if (other.id == datapoint.id) {
472 other = datapoint;
473 found = true;
474 }
475 }
476 if (!found) {
477 this->datapoints_.push_back(datapoint);
478 }
479
480 // Run through listeners
481 for (auto &listener : this->listeners_) {
482 if (listener.datapoint_id == datapoint.id)
483 listener.on_datapoint.call(datapoint);
484 }
485 }
486}
487
489 uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
490 uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
491 uint8_t version = 0;
492
494 switch (command.cmd) {
497 break;
500 break;
503 break;
507 break;
508 default:
509 break;
510 }
511
512#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
513 char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
514 ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
515 version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
516 static_cast<uint8_t>(this->init_state_));
517#endif
518
519 this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
520 if (!command.payload.empty())
521 this->write_array(command.payload.data(), command.payload.size());
522
523 const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
524 this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
525}
526
528 uint32_t now = millis();
530
531 if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
532 this->rx_message_.clear();
533 }
534
535 if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
536 this->expected_response_.reset();
538 if (++this->init_retries_ >= MAX_RETRIES) {
539 this->init_failed_ = true;
540 ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
541 this->command_queue_.erase(command_queue_.begin());
542 this->init_retries_ = 0;
543 }
544 } else {
545 this->command_queue_.erase(command_queue_.begin());
546 }
547 }
548
549 // Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
550 if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
551 !this->expected_response_.has_value()) {
552 this->send_raw_command_(command_queue_.front());
553 if (!this->expected_response_.has_value())
554 this->command_queue_.erase(command_queue_.begin());
555 }
556}
557
558void Tuya::send_command_(const TuyaCommand &command) {
559 command_queue_.push_back(command);
561}
562
564 send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
565}
566
568 bool is_network_ready = network_is_connected() && remote_is_connected();
569 this->status_pin_->digital_write(is_network_ready);
570}
571
573 uint8_t status = 0x02;
574
575 if (network_is_connected()) {
576 status = 0x03;
577
578 // Protocol version 3 also supports specifying when connected to "the cloud"
579 if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
580 status = 0x04;
581 }
582 } else {
583#ifdef USE_CAPTIVE_PORTAL
585 status = 0x01;
586 }
587#endif
588 };
589
590 return status;
591}
592
594#ifdef USE_WIFI
595 if (wifi::global_wifi_component != nullptr)
597#endif
598
599 return 0;
600}
601
603 uint8_t status = this->get_wifi_status_code_();
604
605 if (status == this->wifi_status_) {
606 return;
607 }
608
609 ESP_LOGD(TAG, "Sending WiFi Status");
610 this->wifi_status_ = status;
611 this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
612}
613
614#ifdef USE_TIME
617 return;
618 }
619 this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
621}
622
624 ESPTime now = this->time_id_->now();
625 if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
626 return;
628 this->send_local_time_(true);
629}
630
631void Tuya::send_local_time_(bool periodic) {
632 std::vector<uint8_t> payload;
633 ESPTime now = this->time_id_->now();
634 if (now.is_valid()) {
635 uint8_t year = now.year - 2000;
636 uint8_t month = now.month;
637 uint8_t day_of_month = now.day_of_month;
638 uint8_t hour = now.hour;
639 uint8_t minute = now.minute;
640 uint8_t second = now.second;
641 // Tuya days starts from Monday, esphome uses Sunday as day 1
642 uint8_t day_of_week = now.day_of_week - 1;
643 if (day_of_week == 0) {
644 day_of_week = 7;
645 }
646 // The forced send repeats every minute, so it stays out of the debug log
647 if (periodic) {
648 ESP_LOGV(TAG, "Sending local time");
649 } else {
650 ESP_LOGD(TAG, "Sending local time");
651 }
652 payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
653 } else {
654 // By spec we need to notify MCU that the time was not obtained if this is a response to a query
655 ESP_LOGW(TAG, "Sending missing local time");
656 payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
657 }
658 this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
659}
661 std::vector<uint8_t> payload;
662 ESPTime now = this->time_id_->utcnow();
663 if (now.is_valid()) {
664 uint8_t year = now.year - 2000;
665 uint8_t month = now.month;
666 uint8_t day_of_month = now.day_of_month;
667 uint8_t hour = now.hour;
668 uint8_t minute = now.minute;
669 uint8_t second = now.second;
670 ESP_LOGD(TAG, "Sending gmt time");
671 payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
672 } else {
673 // By spec we need to notify MCU that the time was not obtained if this is a response to a query
674 ESP_LOGW(TAG, "Sending missing gmt time");
675 payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
676 }
677 this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
678}
679#endif
680
681void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
682 this->set_raw_datapoint_value_(datapoint_id, value, false);
683}
684
685void Tuya::set_boolean_datapoint_value(uint8_t datapoint_id, bool value) {
686 this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BOOLEAN, value, 1, false);
687}
688
690 this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::INTEGER, value, 4, false);
691}
692
693void Tuya::set_string_datapoint_value(uint8_t datapoint_id, const std::string &value) {
694 this->set_string_datapoint_value_(datapoint_id, value, false);
695}
696
697void Tuya::set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value) {
698 this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::ENUM, value, 1, false);
699}
700
701void Tuya::set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length) {
703}
704
705void Tuya::force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
706 this->set_raw_datapoint_value_(datapoint_id, value, true);
707}
708
709void Tuya::force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value) {
711}
712
715}
716
717void Tuya::force_set_string_datapoint_value(uint8_t datapoint_id, const std::string &value) {
718 this->set_string_datapoint_value_(datapoint_id, value, true);
719}
720
721void Tuya::force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value) {
722 this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::ENUM, value, 1, true);
723}
724
725void Tuya::force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length) {
727}
728
729optional<TuyaDatapoint> Tuya::get_datapoint_(uint8_t datapoint_id) {
730 for (auto &datapoint : this->datapoints_) {
731 if (datapoint.id == datapoint_id)
732 return datapoint;
733 }
734 return {};
735}
736
737void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
738 uint8_t length, bool forced) {
739 ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
740 optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
741 if (!datapoint.has_value()) {
742 ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
743 } else if (datapoint->type != datapoint_type) {
744 ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
745 return;
746 } else if (!forced && datapoint->value_uint == value) {
747 ESP_LOGV(TAG, "Not sending unchanged value");
748 return;
749 }
750
751 std::vector<uint8_t> data;
752 switch (length) {
753 case 4:
754 data.push_back(value >> 24);
755 data.push_back(value >> 16);
756 [[fallthrough]];
757 case 2:
758 data.push_back(value >> 8);
759 [[fallthrough]];
760 case 1:
761 data.push_back(value >> 0);
762 break;
763 default:
764 ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
765 return;
766 }
767 this->send_datapoint_command_(datapoint_id, datapoint_type, data);
768}
769
770void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
771 char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
772 ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty_to(hex_buf, value.data(), value.size()));
773 optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
774 if (!datapoint.has_value()) {
775 ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
776 } else if (datapoint->type != TuyaDatapointType::RAW) {
777 ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
778 return;
779 } else if (!forced && datapoint->value_raw == value) {
780 ESP_LOGV(TAG, "Not sending unchanged value");
781 return;
782 }
784}
785
786void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced) {
787 ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value.c_str());
788 optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
789 if (!datapoint.has_value()) {
790 ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
791 } else if (datapoint->type != TuyaDatapointType::STRING) {
792 ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
793 return;
794 } else if (!forced && datapoint->value_string == value) {
795 ESP_LOGV(TAG, "Not sending unchanged value");
796 return;
797 }
798 std::vector<uint8_t> data;
799 for (char const &c : value) {
800 data.push_back(c);
801 }
802 this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
803}
804
805void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
806 std::vector<uint8_t> buffer;
807 buffer.push_back(datapoint_id);
808 buffer.push_back(static_cast<uint8_t>(datapoint_type));
809 buffer.push_back(data.size() >> 8);
810 buffer.push_back(data.size() >> 0);
811 buffer.insert(buffer.end(), data.begin(), data.end());
812
814}
815
816void Tuya::register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func) {
817 this->listeners_.push_back(TuyaDatapointListener{
818 .datapoint_id = datapoint_id,
819 .on_datapoint = func,
820 });
821
822 // Run through existing datapoints
823 for (auto &datapoint : this->datapoints_) {
824 if (datapoint.id == datapoint_id)
825 func.call(datapoint);
826 }
827}
828
830 if (this->type != expected) {
831 ESP_LOGW(TAG, "Tuya sensor %u expected datapoint type %#02hhX but got %#02hhX", this->id,
832 static_cast<uint8_t>(expected), static_cast<uint8_t>(this->type));
833 }
834 return *this;
835}
836
838
839} // namespace esphome::tuya
uint8_t status
Definition bl0942.h:8
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 set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
void digital_write(bool value) override
Definition gpio.cpp:215
ESPTime now()
Get the time in the currently defined timezone.
ESPTime utcnow()
Get the time without any time zone or DST corrections.
void add_on_time_sync_callback(F &&callback)
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector< uint8_t > data)
Definition tuya.cpp:805
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
Definition tuya.cpp:693
optional< TuyaDatapoint > get_datapoint_(uint8_t datapoint_id)
Definition tuya.cpp:729
void send_empty_command_(TuyaCommandType command)
Definition tuya.cpp:563
void setup() override
Definition tuya.cpp:42
uint8_t get_wifi_rssi_()
Definition tuya.cpp:593
uint8_t get_wifi_status_code_()
Definition tuya.cpp:572
void dump_config() override
Definition tuya.cpp:61
time::RealTimeClock * time_id_
Definition tuya.h:153
CallbackManager< void()> initialized_callback_
Definition tuya.h:177
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
Definition tuya.cpp:685
bool force_time_sync_
Definition tuya.h:154
TuyaInitState init_state_
Definition tuya.h:159
int status_pin_reported_
Definition tuya.h:164
bool product_invalid_
Definition tuya.h:176
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector< uint8_t > &value, bool forced)
Definition tuya.cpp:770
bool validate_message_()
Definition tuya.cpp:107
void check_force_time_sync_()
Definition tuya.cpp:623
InternalGPIOPin * status_pin_
Definition tuya.h:163
void force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
Definition tuya.cpp:705
uint8_t protocol_version_
Definition tuya.h:162
void set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced)
Definition tuya.cpp:786
void force_set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
Definition tuya.cpp:713
uint32_t last_rx_char_timestamp_
Definition tuya.h:167
void process_command_queue_()
Definition tuya.cpp:527
void send_local_time_(bool periodic=false)
Definition tuya.cpp:631
void send_gmt_time_()
Definition tuya.cpp:660
std::unique_ptr< char[]> product_
Definition tuya.h:168
uint32_t last_command_timestamp_
Definition tuya.h:166
std::vector< TuyaDatapointListener > listeners_
Definition tuya.h:169
std::vector< TuyaCommand > command_queue_
Definition tuya.h:173
std::vector< TuyaDatapoint > datapoints_
Definition tuya.h:170
std::vector< uint8_t > ignore_mcu_update_on_datapoints_
Definition tuya.h:172
std::vector< uint8_t > rx_message_
Definition tuya.h:171
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len)
Definition tuya.cpp:173
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
Definition tuya.cpp:697
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value, uint8_t length, bool forced)
Definition tuya.cpp:737
TuyaInitState get_init_state()
Definition tuya.cpp:837
uint8_t last_force_time_sync_minute_
Definition tuya.h:155
void set_status_pin_()
Definition tuya.cpp:567
void handle_char_(uint8_t c)
Definition tuya.cpp:164
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
Definition tuya.cpp:725
void handle_datapoints_(const uint8_t *buffer, size_t len)
Definition tuya.cpp:377
void send_wifi_status_()
Definition tuya.cpp:602
void send_command_(const TuyaCommand &command)
Definition tuya.cpp:558
void force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
Definition tuya.cpp:709
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
Definition tuya.cpp:681
optional< TuyaCommandType > expected_response_
Definition tuya.h:174
void send_raw_command_(TuyaCommand command)
Definition tuya.cpp:488
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
Definition tuya.cpp:721
void force_set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
Definition tuya.cpp:717
bool time_sync_callback_registered_
Definition tuya.h:156
void set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
Definition tuya.cpp:701
int reset_pin_reported_
Definition tuya.h:165
uint8_t wifi_status_
Definition tuya.h:175
void register_listener_(uint8_t datapoint_id, Callback< void(const TuyaDatapoint &)> func)
Definition tuya.cpp:816
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
Definition tuya.cpp:689
bool gmt_time_sync_callback_registered_
Definition tuya.h:157
void loop() override
Definition tuya.cpp:56
void register_local_time_sync_callback_()
Definition tuya.cpp:615
void write_byte(uint8_t data)
Definition uart.h:22
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
void write_array(const uint8_t *data, size_t len)
Definition uart.h:30
uint8_t month
Definition date_entity.h:1
uint16_t year
Definition date_entity.h:0
uint8_t second
uint8_t minute
uint8_t hour
uint32_t buffer
Definition gif.cpp:50
CaptivePortal * global_captive_portal
ESPHOME_LOG_TAG(TAG, "cover")
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
TuyaExtendedServicesCommandType
Definition tuya.h:72
TuyaCommandType
Definition tuya.h:51
TuyaDatapointType
Definition tuya.h:19
WiFiComponent * global_wifi_component
bool remote_is_connected()
Return whether the node has any form of "remote" connection via the API or to an MQTT broker.
Definition util.cpp:13
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
char * format_hex_pretty_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length, char separator)
Format byte array as uppercase hex to buffer (base implementation).
Definition helpers.cpp:498
constexpr size_t format_hex_pretty_size(size_t byte_count)
Calculate buffer size needed for format_hex_pretty_to with separator: "XX:XX:...:XX\0".
Definition helpers.h:1687
constexpr uint32_t encode_uint32(uint8_t byte1, uint8_t byte2, uint8_t byte3, uint8_t byte4)
Encode a 32-bit value given four bytes in most to least significant byte order.
Definition helpers.h:1051
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 HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
bool valid
static void uint32_t
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
Definition helpers.h:1893
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
TuyaCommandType cmd
Definition tuya.h:88
std::vector< uint8_t > payload
Definition tuya.h:89
const TuyaDatapoint & expect_type(TuyaDatapointType expected) const
Log a warning when this datapoint is not of type expected, and return it.
Definition tuya.cpp:829
TuyaDatapointType type
Definition tuya.h:30
uint8_t ack
uint16_t length
Definition tt21100.cpp:0