15#ifdef USE_CAPTIVE_PORTAL
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;
31static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
32static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
34static bool network_is_connected() {
47 this->
set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
62 ESP_LOGCONFIG(TAG,
"Tuya:");
65 ESP_LOGCONFIG(TAG,
" Initialization failed. Current init_state: %u",
static_cast<uint8_t
>(this->
init_state_));
67 ESP_LOGCONFIG(TAG,
" Configuration will be reported when setup is complete. Current init_state: %u",
70 ESP_LOGCONFIG(TAG,
" If no further output is received, confirm that this is a supported Tuya device.");
76 ESP_LOGCONFIG(TAG,
" Datapoint %u: raw (value: %s)", info.id,
79 ESP_LOGCONFIG(TAG,
" Datapoint %u: switch (value: %s)", info.id, ONOFF(info.value_bool));
81 ESP_LOGCONFIG(TAG,
" Datapoint %u: int value (value: %d)", info.id, info.value_int);
83 ESP_LOGCONFIG(TAG,
" Datapoint %u: string value (value: %s)", info.id, info.value_string.c_str());
85 ESP_LOGCONFIG(TAG,
" Datapoint %u: enum (value: %d)", info.id, info.value_enum);
87 ESP_LOGCONFIG(TAG,
" Datapoint %u: bitmask (value: %" PRIx32
")", info.id, info.value_bitmask);
89 ESP_LOGCONFIG(TAG,
" Datapoint %u: unknown", info.id);
93 ESP_LOGCONFIG(TAG,
" GPIO Configuration: status: pin %d, reset: pin %d", this->
status_pin_reported_,
97 ESP_LOGCONFIG(TAG,
" Product: '%s'",
110 uint8_t new_byte = data[at];
114 return new_byte == 0x55;
117 return new_byte == 0xAA;
121 uint8_t version = data[2];
125 uint8_t command = data[3];
143 uint8_t rx_checksum = new_byte;
146 if (rx_checksum != calc_checksum) {
147 ESP_LOGW(TAG,
"Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
152 const uint8_t *message_data = data + 6;
153#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
155 ESP_LOGV(TAG,
"Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
176 if (this->
expected_response_.has_value() && this->expected_response_ == command_type) {
182 switch (command_type) {
184 ESP_LOGV(TAG,
"MCU Heartbeat (0x%02X)",
buffer[0]);
187 ESP_LOGI(TAG,
"MCU restarted");
198 for (
size_t i = 0; i <
len; i++) {
199 if (!std::isprint(
buffer[i])) {
205 this->
product_ = std::make_unique<char[]>(
len + 1);
229 ESP_LOGW(TAG,
"Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
235 ESP_LOGW(TAG,
"MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
240 ESP_LOGV(TAG,
"Configured WIFI_STATE periodic send");
254 const bool is_select = (
len >= 1);
261 uint8_t first = 0x00;
262 const char *mode_str =
"EZ";
263 if (is_select &&
buffer[0] == 0x01) {
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);
316 ESP_LOGW(TAG,
"LOCAL_TIME_QUERY is not handled because time is not configured");
332 ESP_LOGW(TAG,
"GMT_TIME_QUERY is not handled because time is not configured");
338 ESP_LOGW(TAG,
"Vacuum map upload requested, responding that it is not enabled.");
345 ESP_LOGV(TAG,
"Network status requested, reported as %i", wifi_status);
349 uint8_t subcommand =
buffer[0];
354 .payload = std::vector<uint8_t>{
356 ESP_LOGV(TAG,
"Reset status notification enabled");
360 ESP_LOGE(TAG,
"EXTENDED_SERVICES::MODULE_RESET is not handled");
364 ESP_LOGE(TAG,
"EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
368 ESP_LOGE(TAG,
"Invalid extended services subcommand (0x%02X) received", subcommand);
373 ESP_LOGE(TAG,
"Invalid command (0x%02X) received", command);
382 datapoint.value_uint = 0;
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);
392 datapoint.len = data_size;
394 switch (datapoint.type) {
396 datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
399 ESP_LOGD(TAG,
"Datapoint %u update to %s", datapoint.id,
404 if (data_size != 1) {
405 ESP_LOGW(TAG,
"Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
408 datapoint.value_bool = data[0];
409 ESP_LOGD(TAG,
"Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
412 if (data_size != 4) {
413 ESP_LOGW(TAG,
"Datapoint %u has bad integer len %zu", datapoint.id, data_size);
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);
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());
424 if (data_size != 1) {
425 ESP_LOGW(TAG,
"Datapoint %u has bad enum len %zu", datapoint.id, data_size);
428 datapoint.value_enum = data[0];
429 ESP_LOGD(TAG,
"Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
437 datapoint.value_bitmask =
encode_uint32(0, 0, data[0], data[1]);
440 datapoint.value_bitmask =
encode_uint32(data[0], data[1], data[2], data[3]);
443 ESP_LOGW(TAG,
"Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
446 ESP_LOGD(TAG,
"Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
449 ESP_LOGW(TAG,
"Datapoint %u has unknown type %#02hhX", datapoint.id,
static_cast<uint8_t
>(datapoint.type));
453 len -= data_size + 4;
454 buffer = data + data_size;
459 if (datapoint.id == i) {
460 ESP_LOGV(TAG,
"Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
471 if (other.id == datapoint.id) {
477 this->datapoints_.push_back(datapoint);
482 if (listener.datapoint_id == datapoint.id)
483 listener.on_datapoint.call(datapoint);
489 uint8_t len_hi = (uint8_t) (command.
payload.size() >> 8);
490 uint8_t len_lo = (uint8_t) (command.
payload.size() & 0xFF);
494 switch (command.
cmd) {
512#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
514 ESP_LOGV(TAG,
"Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u",
static_cast<uint8_t
>(command.
cmd),
516 static_cast<uint8_t
>(this->init_state_));
519 this->
write_array({0x55, 0xAA, version, (uint8_t) command.
cmd, len_hi, len_lo});
523 const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.
cmd + len_hi + len_lo;
540 ESP_LOGE(TAG,
"Initialization failed at init_state %u",
static_cast<uint8_t
>(this->
init_state_));
550 if (delay > COMMAND_DELAY && !this->
command_queue_.empty() && this->rx_message_.empty() &&
551 !this->expected_response_.has_value()) {
575 if (network_is_connected()) {
583#ifdef USE_CAPTIVE_PORTAL
609 ESP_LOGD(TAG,
"Sending WiFi Status");
625 if (!now.
is_valid() || now.
minute == this->last_force_time_sync_minute_)
632 std::vector<uint8_t> payload;
643 if (day_of_week == 0) {
648 ESP_LOGV(TAG,
"Sending local time");
650 ESP_LOGD(TAG,
"Sending local time");
655 ESP_LOGW(TAG,
"Sending missing local time");
656 payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
661 std::vector<uint8_t> payload;
670 ESP_LOGD(TAG,
"Sending gmt time");
674 ESP_LOGW(TAG,
"Sending missing gmt time");
675 payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
731 if (datapoint.id == datapoint_id)
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);
746 }
else if (!forced && datapoint->value_uint ==
value) {
747 ESP_LOGV(TAG,
"Not sending unchanged value");
751 std::vector<uint8_t> data;
754 data.push_back(
value >> 24);
755 data.push_back(
value >> 16);
758 data.push_back(
value >> 8);
761 data.push_back(
value >> 0);
764 ESP_LOGE(TAG,
"Unexpected datapoint length %u",
length);
773 optional<TuyaDatapoint> datapoint = this->
get_datapoint_(datapoint_id);
774 if (!datapoint.has_value()) {
775 ESP_LOGW(TAG,
"Setting unknown datapoint %u", datapoint_id);
777 ESP_LOGE(TAG,
"Attempt to set datapoint %u with incorrect type", datapoint_id);
779 }
else if (!forced && datapoint->value_raw ==
value) {
780 ESP_LOGV(TAG,
"Not sending unchanged value");
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);
792 ESP_LOGE(TAG,
"Attempt to set datapoint %u with incorrect type", datapoint_id);
794 }
else if (!forced && datapoint->value_string ==
value) {
795 ESP_LOGV(TAG,
"Not sending unchanged value");
798 std::vector<uint8_t> data;
799 for (
char const &c :
value) {
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);
818 .datapoint_id = datapoint_id,
819 .on_datapoint = func,
824 if (datapoint.id == datapoint_id)
825 func.call(datapoint);
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));
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
void digital_write(bool value) override
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)
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
optional< TuyaDatapoint > get_datapoint_(uint8_t datapoint_id)
void send_empty_command_(TuyaCommandType command)
uint8_t get_wifi_status_code_()
void dump_config() override
time::RealTimeClock * time_id_
CallbackManager< void()> initialized_callback_
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
TuyaInitState init_state_
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector< uint8_t > &value, bool forced)
void check_force_time_sync_()
InternalGPIOPin * status_pin_
void force_set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
uint8_t protocol_version_
void set_string_datapoint_value_(uint8_t datapoint_id, const std::string &value, bool forced)
void force_set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
uint32_t last_rx_char_timestamp_
void process_command_queue_()
void send_local_time_(bool periodic=false)
std::unique_ptr< char[]> product_
uint32_t last_command_timestamp_
std::vector< TuyaDatapointListener > listeners_
std::vector< TuyaCommand > command_queue_
std::vector< TuyaDatapoint > datapoints_
std::vector< uint8_t > ignore_mcu_update_on_datapoints_
std::vector< uint8_t > rx_message_
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len)
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value, uint8_t length, bool forced)
TuyaInitState get_init_state()
uint8_t last_force_time_sync_minute_
void handle_char_(uint8_t c)
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
void handle_datapoints_(const uint8_t *buffer, size_t len)
void send_command_(const TuyaCommand &command)
void force_set_boolean_datapoint_value(uint8_t datapoint_id, bool value)
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector< uint8_t > &value)
optional< TuyaCommandType > expected_response_
void send_raw_command_(TuyaCommand command)
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value)
void force_set_string_datapoint_value(uint8_t datapoint_id, const std::string &value)
bool time_sync_callback_registered_
void set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length)
void register_listener_(uint8_t datapoint_id, Callback< void(const TuyaDatapoint &)> func)
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value)
bool gmt_time_sync_callback_registered_
void register_local_time_sync_callback_()
void write_byte(uint8_t data)
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
void write_array(const uint8_t *data, size_t len)
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, ...)
TuyaExtendedServicesCommandType
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.
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...
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).
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".
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.
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
void HOT delay(uint32_t ms)
uint32_t IRAM_ATTR HOT millis()
Lightweight type-erased callback (8 bytes on 32-bit) that avoids std::function overhead.
A more user-friendly version of struct tm from time.h.
uint8_t minute
minutes after the hour [0-59]
uint8_t second
seconds after the minute [0-60]
uint8_t hour
hours since midnight [0-23]
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).
uint8_t day_of_month
day of the month [1-31]
uint8_t month
month; january=1 [1-12]
uint8_t day_of_week
day of the week; sunday=1 [1-7]
std::vector< uint8_t > payload
const TuyaDatapoint & expect_type(TuyaDatapointType expected) const
Log a warning when this datapoint is not of type expected, and return it.