ESPHome  2024.4.0
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  }
272  default:
273  ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
274  }
275 }
276 
277 void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
278  while (len >= 4) {
279  TuyaDatapoint datapoint{};
280  datapoint.id = buffer[0];
281  datapoint.type = (TuyaDatapointType) buffer[1];
282  datapoint.value_uint = 0;
283 
284  size_t data_size = (buffer[2] << 8) + buffer[3];
285  const uint8_t *data = buffer + 4;
286  size_t data_len = len - 4;
287  if (data_size > data_len) {
288  ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
289  return;
290  }
291 
292  datapoint.len = data_size;
293 
294  switch (datapoint.type) {
296  datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
297  ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, format_hex_pretty(datapoint.value_raw).c_str());
298  break;
300  if (data_size != 1) {
301  ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
302  return;
303  }
304  datapoint.value_bool = data[0];
305  ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
306  break;
308  if (data_size != 4) {
309  ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
310  return;
311  }
312  datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
313  ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
314  break;
316  datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
317  ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
318  break;
320  if (data_size != 1) {
321  ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
322  return;
323  }
324  datapoint.value_enum = data[0];
325  ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
326  break;
328  switch (data_size) {
329  case 1:
330  datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
331  break;
332  case 2:
333  datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
334  break;
335  case 4:
336  datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
337  break;
338  default:
339  ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
340  return;
341  }
342  ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
343  break;
344  default:
345  ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
346  return;
347  }
348 
349  len -= data_size + 4;
350  buffer = data + data_size;
351 
352  // drop update if datapoint is in ignore_mcu_datapoint_update list
353  bool skip = false;
354  for (auto i : this->ignore_mcu_update_on_datapoints_) {
355  if (datapoint.id == i) {
356  ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
357  skip = true;
358  break;
359  }
360  }
361  if (skip)
362  continue;
363 
364  // Update internal datapoints
365  bool found = false;
366  for (auto &other : this->datapoints_) {
367  if (other.id == datapoint.id) {
368  other = datapoint;
369  found = true;
370  }
371  }
372  if (!found) {
373  this->datapoints_.push_back(datapoint);
374  }
375 
376  // Run through listeners
377  for (auto &listener : this->listeners_) {
378  if (listener.datapoint_id == datapoint.id)
379  listener.on_datapoint(datapoint);
380  }
381  }
382 }
383 
385  uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
386  uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
387  uint8_t version = 0;
388 
390  switch (command.cmd) {
393  break;
396  break;
399  break;
403  break;
404  default:
405  break;
406  }
407 
408  ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
409  version, format_hex_pretty(command.payload).c_str(), static_cast<uint8_t>(this->init_state_));
410 
411  this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
412  if (!command.payload.empty())
413  this->write_array(command.payload.data(), command.payload.size());
414 
415  uint8_t checksum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
416  for (auto &data : command.payload)
417  checksum += data;
418  this->write_byte(checksum);
419 }
420 
422  uint32_t now = millis();
423  uint32_t delay = now - this->last_command_timestamp_;
424 
425  if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
426  this->rx_message_.clear();
427  }
428 
429  if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
430  this->expected_response_.reset();
432  if (++this->init_retries_ >= MAX_RETRIES) {
433  this->init_failed_ = true;
434  ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
435  this->command_queue_.erase(command_queue_.begin());
436  this->init_retries_ = 0;
437  }
438  } else {
439  this->command_queue_.erase(command_queue_.begin());
440  }
441  }
442 
443  // Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
444  if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
445  !this->expected_response_.has_value()) {
446  this->send_raw_command_(command_queue_.front());
447  if (!this->expected_response_.has_value())
448  this->command_queue_.erase(command_queue_.begin());
449  }
450 }
451 
452 void Tuya::send_command_(const TuyaCommand &command) {
453  command_queue_.push_back(command);
455 }
456 
458  send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
459 }
460 
462  bool is_network_ready = network::is_connected() && remote_is_connected();
463  this->status_pin_->digital_write(is_network_ready);
464 }
465 
467  uint8_t status = 0x02;
468 
469  if (network::is_connected()) {
470  status = 0x03;
471 
472  // Protocol version 3 also supports specifying when connected to "the cloud"
473  if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
474  status = 0x04;
475  }
476  } else {
477 #ifdef USE_CAPTIVE_PORTAL
479  status = 0x01;
480  }
481 #endif
482  };
483 
484  return status;
485 }
486 
488 #ifdef USE_WIFI
489  if (wifi::global_wifi_component != nullptr)
491 #endif
492 
493  return 0;
494 }
495 
497  uint8_t status = this->get_wifi_status_code_();
498 
499  if (status == this->wifi_status_) {
500  return;
501  }
502 
503  ESP_LOGD(TAG, "Sending WiFi Status");
504  this->wifi_status_ = status;
505  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
506 }
507 
508 #ifdef USE_TIME
510  std::vector<uint8_t> payload;
511  ESPTime now = this->time_id_->now();
512  if (now.is_valid()) {
513  uint8_t year = now.year - 2000;
514  uint8_t month = now.month;
515  uint8_t day_of_month = now.day_of_month;
516  uint8_t hour = now.hour;
517  uint8_t minute = now.minute;
518  uint8_t second = now.second;
519  // Tuya days starts from Monday, esphome uses Sunday as day 1
520  uint8_t day_of_week = now.day_of_week - 1;
521  if (day_of_week == 0) {
522  day_of_week = 7;
523  }
524  ESP_LOGD(TAG, "Sending local time");
525  payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
526  } else {
527  // By spec we need to notify MCU that the time was not obtained if this is a response to a query
528  ESP_LOGW(TAG, "Sending missing local time");
529  payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
530  }
531  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
532 }
533 #endif
534 
535 void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
536  this->set_raw_datapoint_value_(datapoint_id, value, false);
537 }
538 
539 void Tuya::set_boolean_datapoint_value(uint8_t datapoint_id, bool value) {
540  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BOOLEAN, value, 1, false);
541 }
542 
543 void Tuya::set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value) {
544  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::INTEGER, value, 4, false);
545 }
546 
547 void Tuya::set_string_datapoint_value(uint8_t datapoint_id, const std::string &value) {
548  this->set_string_datapoint_value_(datapoint_id, value, false);
549 }
550 
551 void Tuya::set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value) {
552  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::ENUM, value, 1, false);
553 }
554 
555 void Tuya::set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length) {
556  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, false);
557 }
558 
559 void Tuya::force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
560  this->set_raw_datapoint_value_(datapoint_id, value, true);
561 }
562 
563 void Tuya::force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value) {
564  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BOOLEAN, value, 1, true);
565 }
566 
567 void Tuya::force_set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value) {
568  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::INTEGER, value, 4, true);
569 }
570 
571 void Tuya::force_set_string_datapoint_value(uint8_t datapoint_id, const std::string &value) {
572  this->set_string_datapoint_value_(datapoint_id, value, true);
573 }
574 
575 void Tuya::force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value) {
576  this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::ENUM, value, 1, true);
577 }
578 
579 void Tuya::force_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, true);
581 }
582 
584  for (auto &datapoint : this->datapoints_) {
585  if (datapoint.id == datapoint_id)
586  return datapoint;
587  }
588  return {};
589 }
590 
591 void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
592  uint8_t length, bool forced) {
593  ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
594  optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
595  if (!datapoint.has_value()) {
596  ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
597  } else if (datapoint->type != datapoint_type) {
598  ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
599  return;
600  } else if (!forced && datapoint->value_uint == value) {
601  ESP_LOGV(TAG, "Not sending unchanged value");
602  return;
603  }
604 
605  std::vector<uint8_t> data;
606  switch (length) {
607  case 4:
608  data.push_back(value >> 24);
609  data.push_back(value >> 16);
610  case 2:
611  data.push_back(value >> 8);
612  case 1:
613  data.push_back(value >> 0);
614  break;
615  default:
616  ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
617  return;
618  }
619  this->send_datapoint_command_(datapoint_id, datapoint_type, data);
620 }
621 
622 void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
623  ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty(value).c_str());
624  optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
625  if (!datapoint.has_value()) {
626  ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
627  } else if (datapoint->type != TuyaDatapointType::RAW) {
628  ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
629  return;
630  } else if (!forced && datapoint->value_raw == value) {
631  ESP_LOGV(TAG, "Not sending unchanged value");
632  return;
633  }
634  this->send_datapoint_command_(datapoint_id, TuyaDatapointType::RAW, value);
635 }
636 
637 void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced) {
638  ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value.c_str());
639  optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
640  if (!datapoint.has_value()) {
641  ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
642  } else if (datapoint->type != TuyaDatapointType::STRING) {
643  ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
644  return;
645  } else if (!forced && datapoint->value_string == value) {
646  ESP_LOGV(TAG, "Not sending unchanged value");
647  return;
648  }
649  std::vector<uint8_t> data;
650  for (char const &c : value) {
651  data.push_back(c);
652  }
653  this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
654 }
655 
656 void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
657  std::vector<uint8_t> buffer;
658  buffer.push_back(datapoint_id);
659  buffer.push_back(static_cast<uint8_t>(datapoint_type));
660  buffer.push_back(data.size() >> 8);
661  buffer.push_back(data.size() >> 0);
662  buffer.insert(buffer.end(), data.begin(), data.end());
663 
664  this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = buffer});
665 }
666 
667 void Tuya::register_listener(uint8_t datapoint_id, const std::function<void(TuyaDatapoint)> &func) {
668  auto listener = TuyaDatapointListener{
669  .datapoint_id = datapoint_id,
670  .on_datapoint = func,
671  };
672  this->listeners_.push_back(listener);
673 
674  // Run through existing datapoints
675  for (auto &datapoint : this->datapoints_) {
676  if (datapoint.id == datapoint_id)
677  func(datapoint);
678  }
679 }
680 
682 
683 } // namespace tuya
684 } // namespace esphome
virtual void digital_write(bool value)=0
ESPTime now()
Get the time in the currently defined timezone.
uint16_t year
Definition: date_entity.h:108
uint8_t protocol_version_
Definition: tuya.h:139
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:551
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
Definition: tuya.cpp:535
uint8_t get_wifi_rssi_()
Definition: tuya.cpp:487
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:152
void write_array(const uint8_t *data, size_t len)
Definition: uart.h:21
TuyaInitState init_state_
Definition: tuya.h:136
void setup() override
Definition: tuya.cpp:24
CallbackManager< void()> initialized_callback_
Definition: tuya.h:153
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:133
uint8_t minute
Definition: time_entity.h:148
void handle_datapoints_(const uint8_t *buffer, size_t len)
Definition: tuya.cpp:277
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:622
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:579
uint32_t last_command_timestamp_
Definition: tuya.h:143
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:571
void force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
Definition: tuya.cpp:559
void send_local_time_()
Definition: tuya.cpp:509
std::vector< uint8_t > ignore_mcu_update_on_datapoints_
Definition: tuya.h:149
TuyaDatapointType
Definition: tuya.h:19
void process_command_queue_()
Definition: tuya.cpp:421
bool has_value() const
Definition: optional.h:87
void register_listener(uint8_t datapoint_id, const std::function< void(TuyaDatapoint)> &func)
Definition: tuya.cpp:667
optional< TuyaCommandType > expected_response_
Definition: tuya.h:151
InternalGPIOPin * status_pin_
Definition: tuya.h:140
uint8_t get_wifi_status_code_()
Definition: tuya.cpp:466
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
std::vector< TuyaDatapointListener > listeners_
Definition: tuya.h:146
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:575
std::vector< TuyaDatapoint > datapoints_
Definition: tuya.h:147
void set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced)
Definition: tuya.cpp:637
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:148
TuyaCommandType cmd
Definition: tuya.h:75
optional< TuyaDatapoint > get_datapoint_(uint8_t datapoint_id)
Definition: tuya.cpp:583
bool init_failed_
Definition: tuya.h:137
uint8_t second
seconds after the minute [0-60]
Definition: time.h:21
bool read_byte(uint8_t *data)
Definition: uart.h:29
TuyaInitState get_init_state()
Definition: tuya.cpp:681
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
int reset_pin_reported_
Definition: tuya.h:142
uint8_t minute
minutes after the hour [0-59]
Definition: time.h:23
std::string product_
Definition: tuya.h:145
void send_wifi_status_()
Definition: tuya.cpp:496
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:567
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
uint8_t second
Definition: time_entity.h:149
uint16_t year
year
Definition: time.h:35
bool time_sync_callback_registered_
Definition: tuya.h:134
std::vector< uint8_t > payload
Definition: tuya.h:76
uint8_t hour
Definition: time_entity.h:147
int status_pin_reported_
Definition: tuya.h:141
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:539
std::string size_t len
Definition: helpers.h:292
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
Definition: tuya.cpp:543
void set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
Definition: tuya.cpp:555
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector< uint8_t > data)
Definition: tuya.cpp:656
void send_raw_command_(TuyaCommand command)
Definition: tuya.cpp:384
bool validate_message_()
Definition: tuya.cpp:77
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
Definition: tuya.cpp:547
uint16_t length
Definition: tt21100.cpp:12
void send_command_(const TuyaCommand &command)
Definition: tuya.cpp:452
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:150
void send_empty_command_(TuyaCommandType command)
Definition: tuya.cpp:457
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:591
TuyaInitState
Definition: tuya.h:65
uint8_t hour
hours since midnight [0-23]
Definition: time.h:25
uint32_t last_rx_char_timestamp_
Definition: tuya.h:144
void force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
Definition: tuya.cpp:563
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:109
void set_status_pin_()
Definition: tuya.cpp:461
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26