ESPHome  2024.6.1
tuya.cpp
Go to the documentation of this file.
1 #include "tuya.h"
3 #include "esphome/core/gpio.h"
4 #include "esphome/core/helpers.h"
5 #include "esphome/core/log.h"
6 #include "esphome/core/util.h"
7 
8 #ifdef USE_WIFI
10 #endif
11 
12 #ifdef USE_CAPTIVE_PORTAL
14 #endif
15 
16 namespace esphome {
17 namespace tuya {
18 
19 static const char *const TAG = "tuya";
20 static const int COMMAND_DELAY = 10;
21 static const int RECEIVE_TIMEOUT = 300;
22 static const int MAX_RETRIES = 5;
23 
24 void Tuya::setup() {
25  this->set_interval("heartbeat", 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
26  if (this->status_pin_ != nullptr) {
27  this->status_pin_->digital_write(false);
28  }
29 }
30 
31 void Tuya::loop() {
32  while (this->available()) {
33  uint8_t c;
34  this->read_byte(&c);
35  this->handle_char_(c);
36  }
38 }
39 
41  ESP_LOGCONFIG(TAG, "Tuya:");
43  if (this->init_failed_) {
44  ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
45  } else {
46  ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
47  static_cast<uint8_t>(this->init_state_));
48  }
49  ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
50  return;
51  }
52  for (auto &info : this->datapoints_) {
53  if (info.type == TuyaDatapointType::RAW) {
54  ESP_LOGCONFIG(TAG, " Datapoint %u: raw (value: %s)", info.id, format_hex_pretty(info.value_raw).c_str());
55  } else if (info.type == TuyaDatapointType::BOOLEAN) {
56  ESP_LOGCONFIG(TAG, " Datapoint %u: switch (value: %s)", info.id, ONOFF(info.value_bool));
57  } else if (info.type == TuyaDatapointType::INTEGER) {
58  ESP_LOGCONFIG(TAG, " Datapoint %u: int value (value: %d)", info.id, info.value_int);
59  } else if (info.type == TuyaDatapointType::STRING) {
60  ESP_LOGCONFIG(TAG, " Datapoint %u: string value (value: %s)", info.id, info.value_string.c_str());
61  } else if (info.type == TuyaDatapointType::ENUM) {
62  ESP_LOGCONFIG(TAG, " Datapoint %u: enum (value: %d)", info.id, info.value_enum);
63  } else if (info.type == TuyaDatapointType::BITMASK) {
64  ESP_LOGCONFIG(TAG, " Datapoint %u: bitmask (value: %" PRIx32 ")", info.id, info.value_bitmask);
65  } else {
66  ESP_LOGCONFIG(TAG, " Datapoint %u: unknown", info.id);
67  }
68  }
69  if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
70  ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
71  this->reset_pin_reported_);
72  }
73  LOG_PIN(" Status Pin: ", this->status_pin_);
74  ESP_LOGCONFIG(TAG, " Product: '%s'", this->product_.c_str());
75 }
76 
78  uint32_t at = this->rx_message_.size() - 1;
79  auto *data = &this->rx_message_[0];
80  uint8_t new_byte = data[at];
81 
82  // Byte 0: HEADER1 (always 0x55)
83  if (at == 0)
84  return new_byte == 0x55;
85  // Byte 1: HEADER2 (always 0xAA)
86  if (at == 1)
87  return new_byte == 0xAA;
88 
89  // Byte 2: VERSION
90  // no validation for the following fields:
91  uint8_t version = data[2];
92  if (at == 2)
93  return true;
94  // Byte 3: COMMAND
95  uint8_t command = data[3];
96  if (at == 3)
97  return true;
98 
99  // Byte 4: LENGTH1
100  // Byte 5: LENGTH2
101  if (at <= 5) {
102  // no validation for these fields
103  return true;
104  }
105 
106  uint16_t length = (uint16_t(data[4]) << 8) | (uint16_t(data[5]));
107 
108  // wait until all data is read
109  if (at - 6 < length)
110  return true;
111 
112  // Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
113  uint8_t rx_checksum = new_byte;
114  uint8_t calc_checksum = 0;
115  for (uint32_t i = 0; i < 6 + length; i++)
116  calc_checksum += data[i];
117 
118  if (rx_checksum != calc_checksum) {
119  ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
120  return false;
121  }
122 
123  // valid message
124  const uint8_t *message_data = data + 6;
125  ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
126  format_hex_pretty(message_data, length).c_str(), static_cast<uint8_t>(this->init_state_));
127  this->handle_command_(command, version, message_data, length);
128 
129  // return false to reset rx buffer
130  return false;
131 }
132 
133 void Tuya::handle_char_(uint8_t c) {
134  this->rx_message_.push_back(c);
135  if (!this->validate_message_()) {
136  this->rx_message_.clear();
137  } else {
139  }
140 }
141 
142 void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
143  TuyaCommandType command_type = (TuyaCommandType) command;
144 
145  if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
146  this->expected_response_.reset();
147  this->command_queue_.erase(command_queue_.begin());
148  this->init_retries_ = 0;
149  }
150 
151  switch (command_type) {
153  ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
154  this->protocol_version_ = version;
155  if (buffer[0] == 0) {
156  ESP_LOGI(TAG, "MCU restarted");
158  }
162  }
163  break;
165  // check it is a valid string made up of printable characters
166  bool valid = true;
167  for (size_t i = 0; i < len; i++) {
168  if (!std::isprint(buffer[i])) {
169  valid = false;
170  break;
171  }
172  }
173  if (valid) {
174  this->product_ = std::string(reinterpret_cast<const char *>(buffer), len);
175  } else {
176  this->product_ = R"({"p":"INVALID"})";
177  }
181  }
182  break;
183  }
185  if (len >= 2) {
186  this->status_pin_reported_ = buffer[0];
187  this->reset_pin_reported_ = buffer[1];
188  }
189  if (this->init_state_ == TuyaInitState::INIT_CONF) {
190  // If mcu returned status gpio, then we can omit sending wifi state
191  if (this->status_pin_reported_ != -1) {
194  bool is_pin_equals =
195  this->status_pin_ != nullptr && this->status_pin_->get_pin() == this->status_pin_reported_;
196  // Configure status pin toggling (if reported and configured) or WIFI_STATE periodic send
197  if (is_pin_equals) {
198  ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_reported_);
199  this->set_interval("wifi", 1000, [this] { this->set_status_pin_(); });
200  } else {
201  ESP_LOGW(TAG, "Supplied status_pin does not equals the reported pin %i. TuyaMcu will work in limited mode.",
202  this->status_pin_reported_);
203  }
204  } else {
206  ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
207  this->set_interval("wifi", 1000, [this] { this->send_wifi_status_(); });
208  }
209  }
210  break;
211  }
213  if (this->init_state_ == TuyaInitState::INIT_WIFI) {
216  }
217  break;
219  ESP_LOGE(TAG, "WIFI_RESET is not handled");
220  break;
222  ESP_LOGE(TAG, "WIFI_SELECT is not handled");
223  break;
225  break;
229  this->set_timeout("datapoint_dump", 1000, [this] { this->dump_config(); });
230  this->initialized_callback_.call();
231  }
232  this->handle_datapoints_(buffer, len);
233  break;
235  break;
237  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
238  break;
240  this->send_command_(
241  TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
242  break;
244 #ifdef USE_TIME
245  if (this->time_id_ != nullptr) {
246  this->send_local_time_();
247 
248  if (!this->time_sync_callback_registered_) {
249  // tuya mcu supports time, so we let them know when our time changed
250  this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
251  this->time_sync_callback_registered_ = true;
252  }
253  } else
254 #endif
255  {
256  ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
257  }
258  break;
260  this->send_command_(
261  TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
262  ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
263  break;
265  uint8_t wifi_status = this->get_wifi_status_code_();
266 
267  this->send_command_(
268  TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
269  ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
270  break;
271  }
273  uint8_t subcommand = buffer[0];
274  switch ((TuyaExtendedServicesCommandType) subcommand) {
276  this->send_command_(
278  .payload = std::vector<uint8_t>{
279  static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
280  ESP_LOGV(TAG, "Reset status notification enabled");
281  break;
282  }
284  ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
285  break;
286  }
288  ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
289  break;
290  }
291  default:
292  ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
293  }
294  break;
295  }
296  default:
297  ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
298  }
299 }
300 
301 void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
302  while (len >= 4) {
303  TuyaDatapoint datapoint{};
304  datapoint.id = buffer[0];
305  datapoint.type = (TuyaDatapointType) buffer[1];
306  datapoint.value_uint = 0;
307 
308  size_t data_size = (buffer[2] << 8) + buffer[3];
309  const uint8_t *data = buffer + 4;
310  size_t data_len = len - 4;
311  if (data_size > data_len) {
312  ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
313  return;
314  }
315 
316  datapoint.len = data_size;
317 
318  switch (datapoint.type) {
320  datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
321  ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, format_hex_pretty(datapoint.value_raw).c_str());
322  break;
324  if (data_size != 1) {
325  ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
326  return;
327  }
328  datapoint.value_bool = data[0];
329  ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
330  break;
332  if (data_size != 4) {
333  ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
334  return;
335  }
336  datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
337  ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
338  break;
340  datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
341  ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
342  break;
344  if (data_size != 1) {
345  ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
346  return;
347  }
348  datapoint.value_enum = data[0];
349  ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
350  break;
352  switch (data_size) {
353  case 1:
354  datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
355  break;
356  case 2:
357  datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
358  break;
359  case 4:
360  datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
361  break;
362  default:
363  ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
364  return;
365  }
366  ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
367  break;
368  default:
369  ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
370  return;
371  }
372 
373  len -= data_size + 4;
374  buffer = data + data_size;
375 
376  // drop update if datapoint is in ignore_mcu_datapoint_update list
377  bool skip = false;
378  for (auto i : this->ignore_mcu_update_on_datapoints_) {
379  if (datapoint.id == i) {
380  ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
381  skip = true;
382  break;
383  }
384  }
385  if (skip)
386  continue;
387 
388  // Update internal datapoints
389  bool found = false;
390  for (auto &other : this->datapoints_) {
391  if (other.id == datapoint.id) {
392  other = datapoint;
393  found = true;
394  }
395  }
396  if (!found) {
397  this->datapoints_.push_back(datapoint);
398  }
399 
400  // Run through listeners
401  for (auto &listener : this->listeners_) {
402  if (listener.datapoint_id == datapoint.id)
403  listener.on_datapoint(datapoint);
404  }
405  }
406 }
407 
409  uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
410  uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
411  uint8_t version = 0;
412 
414  switch (command.cmd) {
417  break;
420  break;
423  break;
427  break;
428  default:
429  break;
430  }
431 
432  ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
433  version, format_hex_pretty(command.payload).c_str(), static_cast<uint8_t>(this->init_state_));
434 
435  this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
436  if (!command.payload.empty())
437  this->write_array(command.payload.data(), command.payload.size());
438 
439  uint8_t checksum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
440  for (auto &data : command.payload)
441  checksum += data;
442  this->write_byte(checksum);
443 }
444 
446  uint32_t now = millis();
447  uint32_t delay = now - this->last_command_timestamp_;
448 
449  if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
450  this->rx_message_.clear();
451  }
452 
453  if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
454  this->expected_response_.reset();
456  if (++this->init_retries_ >= MAX_RETRIES) {
457  this->init_failed_ = true;
458  ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
459  this->command_queue_.erase(command_queue_.begin());
460  this->init_retries_ = 0;
461  }
462  } else {
463  this->command_queue_.erase(command_queue_.begin());
464  }
465  }
466 
467  // Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
468  if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
469  !this->expected_response_.has_value()) {
470  this->send_raw_command_(command_queue_.front());
471  if (!this->expected_response_.has_value())
472  this->command_queue_.erase(command_queue_.begin());
473  }
474 }
475 
476 void Tuya::send_command_(const TuyaCommand &command) {
477  command_queue_.push_back(command);
479 }
480 
482  send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
483 }
484 
486  bool is_network_ready = network::is_connected() && remote_is_connected();
487  this->status_pin_->digital_write(is_network_ready);
488 }
489 
491  uint8_t status = 0x02;
492 
493  if (network::is_connected()) {
494  status = 0x03;
495 
496  // Protocol version 3 also supports specifying when connected to "the cloud"
497  if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
498  status = 0x04;
499  }
500  } else {
501 #ifdef USE_CAPTIVE_PORTAL
503  status = 0x01;
504  }
505 #endif
506  };
507 
508  return status;
509 }
510 
512 #ifdef USE_WIFI
513  if (wifi::global_wifi_component != nullptr)
515 #endif
516 
517  return 0;
518 }
519 
521  uint8_t status = this->get_wifi_status_code_();
522 
523  if (status == this->wifi_status_) {
524  return;
525  }
526 
527  ESP_LOGD(TAG, "Sending WiFi Status");
528  this->wifi_status_ = status;
529  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
530 }
531 
532 #ifdef USE_TIME
534  std::vector<uint8_t> payload;
535  ESPTime now = this->time_id_->now();
536  if (now.is_valid()) {
537  uint8_t year = now.year - 2000;
538  uint8_t month = now.month;
539  uint8_t day_of_month = now.day_of_month;
540  uint8_t hour = now.hour;
541  uint8_t minute = now.minute;
542  uint8_t second = now.second;
543  // Tuya days starts from Monday, esphome uses Sunday as day 1
544  uint8_t day_of_week = now.day_of_week - 1;
545  if (day_of_week == 0) {
546  day_of_week = 7;
547  }
548  ESP_LOGD(TAG, "Sending local time");
549  payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
550  } else {
551  // By spec we need to notify MCU that the time was not obtained if this is a response to a query
552  ESP_LOGW(TAG, "Sending missing local time");
553  payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
554  }
555  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
556 }
557 #endif
558 
559 void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
560  this->set_raw_datapoint_value_(datapoint_id, value, false);
561 }
562 
563 void Tuya::set_boolean_datapoint_value(uint8_t datapoint_id, bool value) {
564  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BOOLEAN, value, 1, false);
565 }
566 
567 void Tuya::set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value) {
568  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::INTEGER, value, 4, false);
569 }
570 
571 void Tuya::set_string_datapoint_value(uint8_t datapoint_id, const std::string &value) {
572  this->set_string_datapoint_value_(datapoint_id, value, false);
573 }
574 
575 void Tuya::set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value) {
576  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::ENUM, value, 1, false);
577 }
578 
579 void Tuya::set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length) {
580  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, false);
581 }
582 
583 void Tuya::force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
584  this->set_raw_datapoint_value_(datapoint_id, value, true);
585 }
586 
587 void Tuya::force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value) {
588  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BOOLEAN, value, 1, true);
589 }
590 
591 void Tuya::force_set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value) {
592  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::INTEGER, value, 4, true);
593 }
594 
595 void Tuya::force_set_string_datapoint_value(uint8_t datapoint_id, const std::string &value) {
596  this->set_string_datapoint_value_(datapoint_id, value, true);
597 }
598 
599 void Tuya::force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value) {
600  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::ENUM, value, 1, true);
601 }
602 
603 void Tuya::force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length) {
604  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, true);
605 }
606 
608  for (auto &datapoint : this->datapoints_) {
609  if (datapoint.id == datapoint_id)
610  return datapoint;
611  }
612  return {};
613 }
614 
615 void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
616  uint8_t length, bool forced) {
617  ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
618  optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
619  if (!datapoint.has_value()) {
620  ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
621  } else if (datapoint->type != datapoint_type) {
622  ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
623  return;
624  } else if (!forced && datapoint->value_uint == value) {
625  ESP_LOGV(TAG, "Not sending unchanged value");
626  return;
627  }
628 
629  std::vector<uint8_t> data;
630  switch (length) {
631  case 4:
632  data.push_back(value >> 24);
633  data.push_back(value >> 16);
634  case 2:
635  data.push_back(value >> 8);
636  case 1:
637  data.push_back(value >> 0);
638  break;
639  default:
640  ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
641  return;
642  }
643  this->send_datapoint_command_(datapoint_id, datapoint_type, data);
644 }
645 
646 void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
647  ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty(value).c_str());
648  optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
649  if (!datapoint.has_value()) {
650  ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
651  } else if (datapoint->type != TuyaDatapointType::RAW) {
652  ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
653  return;
654  } else if (!forced && datapoint->value_raw == value) {
655  ESP_LOGV(TAG, "Not sending unchanged value");
656  return;
657  }
658  this->send_datapoint_command_(datapoint_id, TuyaDatapointType::RAW, value);
659 }
660 
661 void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced) {
662  ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value.c_str());
663  optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
664  if (!datapoint.has_value()) {
665  ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
666  } else if (datapoint->type != TuyaDatapointType::STRING) {
667  ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
668  return;
669  } else if (!forced && datapoint->value_string == value) {
670  ESP_LOGV(TAG, "Not sending unchanged value");
671  return;
672  }
673  std::vector<uint8_t> data;
674  for (char const &c : value) {
675  data.push_back(c);
676  }
677  this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
678 }
679 
680 void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
681  std::vector<uint8_t> buffer;
682  buffer.push_back(datapoint_id);
683  buffer.push_back(static_cast<uint8_t>(datapoint_type));
684  buffer.push_back(data.size() >> 8);
685  buffer.push_back(data.size() >> 0);
686  buffer.insert(buffer.end(), data.begin(), data.end());
687 
688  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = buffer});
689 }
690 
691 void Tuya::register_listener(uint8_t datapoint_id, const std::function<void(TuyaDatapoint)> &func) {
692  auto listener = TuyaDatapointListener{
693  .datapoint_id = datapoint_id,
694  .on_datapoint = func,
695  };
696  this->listeners_.push_back(listener);
697 
698  // Run through existing datapoints
699  for (auto &datapoint : this->datapoints_) {
700  if (datapoint.id == datapoint_id)
701  func(datapoint);
702  }
703 }
704 
706 
707 } // namespace tuya
708 } // namespace esphome
TuyaExtendedServicesCommandType
Definition: tuya.h:66
virtual void digital_write(bool value)=0
ESPTime now()
Get the time in the currently defined timezone.
uint16_t year
Definition: date_entity.h:122
uint8_t protocol_version_
Definition: tuya.h:146
void set_interval(const std::string &name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition: component.cpp:52
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
Definition: tuya.cpp:575
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
Definition: tuya.cpp:559
uint8_t get_wifi_rssi_()
Definition: tuya.cpp:511
std::string format_hex_pretty(const uint8_t *data, size_t length)
Format the byte array data of length len in pretty-printed, human-readable hex.
Definition: helpers.cpp:361
uint8_t wifi_status_
Definition: tuya.h:159
void write_array(const uint8_t *data, size_t len)
Definition: uart.h:21
TuyaInitState init_state_
Definition: tuya.h:143
void setup() override
Definition: tuya.cpp:24
CallbackManager< void()> initialized_callback_
Definition: tuya.h:160
void write_byte(uint8_t data)
Definition: uart.h:19
TuyaCommandType
Definition: tuya.h:48
void handle_char_(uint8_t c)
Definition: tuya.cpp:133
time::RealTimeClock * time_id_
Definition: tuya.h:140
void handle_datapoints_(const uint8_t *buffer, size_t len)
Definition: tuya.cpp:301
A more user-friendly version of struct tm from time.h.
Definition: time.h:17
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector< uint8_t > &value, bool forced)
Definition: tuya.cpp:646
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:69
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
Definition: tuya.cpp:603
uint32_t last_command_timestamp_
Definition: tuya.h:150
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:186
void add_on_time_sync_callback(std::function< void()> callback)
void force_set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
Definition: tuya.cpp:595
void force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
Definition: tuya.cpp:583
void send_local_time_()
Definition: tuya.cpp:533
std::vector< uint8_t > ignore_mcu_update_on_datapoints_
Definition: tuya.h:156
TuyaDatapointType
Definition: tuya.h:19
void process_command_queue_()
Definition: tuya.cpp:445
bool has_value() const
Definition: optional.h:87
void register_listener(uint8_t datapoint_id, const std::function< void(TuyaDatapoint)> &func)
Definition: tuya.cpp:691
optional< TuyaCommandType > expected_response_
Definition: tuya.h:158
InternalGPIOPin * status_pin_
Definition: tuya.h:147
uint8_t get_wifi_status_code_()
Definition: tuya.cpp:490
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
uint8_t minute
std::vector< TuyaDatapointListener > listeners_
Definition: tuya.h:153
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
Definition: tuya.cpp:599
std::vector< TuyaDatapoint > datapoints_
Definition: tuya.h:154
void set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced)
Definition: tuya.cpp:661
CaptivePortal * global_captive_portal
virtual uint8_t get_pin() const =0
const char *const TAG
Definition: spi.cpp:8
std::vector< uint8_t > rx_message_
Definition: tuya.h:155
TuyaCommandType cmd
Definition: tuya.h:82
optional< TuyaDatapoint > get_datapoint_(uint8_t datapoint_id)
Definition: tuya.cpp:607
bool init_failed_
Definition: tuya.h:144
uint8_t second
seconds after the minute [0-60]
Definition: time.h:21
bool read_byte(uint8_t *data)
Definition: uart.h:29
uint8_t hour
TuyaInitState get_init_state()
Definition: tuya.cpp:705
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:35
uint8_t second
int reset_pin_reported_
Definition: tuya.h:149
uint8_t minute
minutes after the hour [0-59]
Definition: time.h:23
std::string product_
Definition: tuya.h:152
void send_wifi_status_()
Definition: tuya.cpp:520
uint8_t checksum
Definition: bl0939.h:35
WiFiComponent * global_wifi_component
void force_set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
Definition: tuya.cpp:591
bool is_valid() const
Check if this ESPTime is valid (all fields in range and year is greater than 2018) ...
Definition: time.h:61
uint8_t day_of_week
day of the week; sunday=1 [1-7]
Definition: time.h:27
uint16_t year
year
Definition: time.h:35
bool time_sync_callback_registered_
Definition: tuya.h:141
std::vector< uint8_t > payload
Definition: tuya.h:83
int status_pin_reported_
Definition: tuya.h:148
uint8_t status
Definition: bl0942.h:23
void loop() override
Definition: tuya.cpp:31
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
Definition: tuya.cpp:563
std::string size_t len
Definition: helpers.h:292
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
Definition: tuya.cpp:567
void set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
Definition: tuya.cpp:579
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector< uint8_t > data)
Definition: tuya.cpp:680
void send_raw_command_(TuyaCommand command)
Definition: tuya.cpp:408
bool validate_message_()
Definition: tuya.cpp:77
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
Definition: tuya.cpp:571
uint16_t length
Definition: tt21100.cpp:12
void send_command_(const TuyaCommand &command)
Definition: tuya.cpp:476
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
std::vector< TuyaCommand > command_queue_
Definition: tuya.h:157
void send_empty_command_(TuyaCommandType command)
Definition: tuya.cpp:481
uint8_t month
month; january=1 [1-12]
Definition: time.h:33
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value, uint8_t length, bool forced)
Definition: tuya.cpp:615
TuyaInitState
Definition: tuya.h:72
uint8_t hour
hours since midnight [0-23]
Definition: time.h:25
uint32_t last_rx_char_timestamp_
Definition: tuya.h:151
void force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
Definition: tuya.cpp:587
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len)
Definition: tuya.cpp:142
void dump_config() override
Definition: tuya.cpp:40
uint8_t day_of_month
day of the month [1-31]
Definition: time.h:29
uint8_t month
Definition: date_entity.h:123
void set_status_pin_()
Definition: tuya.cpp:485
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26