18#ifdef USE_CAPTIVE_PORTAL
26static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
27static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
28static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
29static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
30static const int COMMAND_DELAY = 10;
31static constexpr uint32_t RECEIVE_TIMEOUT = 300;
32static const int MAX_RETRIES = 5;
33static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
35static bool network_is_connected() {
48 this->
set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
58 auto handler = [
this](
const uint8_t *frame,
size_t len) {
return this->
handle_frame_(frame,
len); };
74 ESP_LOGCONFIG(TAG,
"Tuya:");
77 ESP_LOGCONFIG(TAG,
" Initialization failed. Current init_state: %u",
static_cast<uint8_t
>(this->
init_state_));
79 ESP_LOGCONFIG(TAG,
" Configuration will be reported when setup is complete. Current init_state: %u",
82 ESP_LOGCONFIG(TAG,
" If no further output is received, confirm that this is a supported Tuya device.");
87 ESP_LOGCONFIG(TAG,
" GPIO Configuration: status: pin %d, reset: pin %d", this->
status_pin_reported_,
91 ESP_LOGCONFIG(TAG,
" Product: '%s'",
102 ESP_LOGW(TAG,
"Skipped a %u byte frame, longer than the %u byte buffer",
static_cast<unsigned>(
len),
103 static_cast<unsigned>(MAX_FRAME_SIZE));
108 const uint8_t rx_checksum = frame[
len - 1];
109 const uint8_t calc_checksum =
sum_bytes(frame,
len - 1);
110 if (rx_checksum != calc_checksum) {
111 ESP_LOGW(TAG,
"Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
114 const uint8_t version = frame[2];
115 const uint8_t command = frame[3];
118#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
120 ESP_LOGV(TAG,
"Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
130 if (this->
expected_response_.has_value() && this->expected_response_ == command_type) {
136 switch (command_type) {
138 ESP_LOGV(TAG,
"MCU Heartbeat (0x%02X)",
buffer[0]);
141 ESP_LOGI(TAG,
"MCU restarted");
152 for (
size_t i = 0; i <
len; i++) {
153 if (!std::isprint(
buffer[i])) {
159 this->
product_ = std::make_unique<char[]>(
len + 1);
183 ESP_LOGW(TAG,
"Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
189 ESP_LOGW(TAG,
"MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
194 ESP_LOGV(TAG,
"Configured WIFI_STATE periodic send");
208 const bool is_select = (
len >= 1);
215 uint8_t first = 0x00;
216 const char *mode_str =
"EZ";
217 if (is_select &&
buffer[0] == 0x01) {
233 ESP_LOGI(TAG,
"%s received (%s), replied with WIFI_STATE confirming connection established",
234 is_select ? LOG_STR_LITERAL(
"WIFI_SELECT") : LOG_STR_LITERAL(
"WIFI_RESET"), mode_str);
270 ESP_LOGW(TAG,
"LOCAL_TIME_QUERY is not handled because time is not configured");
286 ESP_LOGW(TAG,
"GMT_TIME_QUERY is not handled because time is not configured");
292 ESP_LOGW(TAG,
"Vacuum map upload requested, responding that it is not enabled.");
299 ESP_LOGV(TAG,
"Network status requested, reported as %i", wifi_status);
303 uint8_t subcommand =
buffer[0];
308 .payload = std::vector<uint8_t>{
310 ESP_LOGV(TAG,
"Reset status notification enabled");
314 ESP_LOGE(TAG,
"EXTENDED_SERVICES::MODULE_RESET is not handled");
318 ESP_LOGE(TAG,
"EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
322 ESP_LOGE(TAG,
"Invalid extended services subcommand (0x%02X) received", subcommand);
327 ESP_LOGE(TAG,
"Invalid command (0x%02X) received", command);
336 datapoint.value_uint = 0;
339 const uint8_t *data =
buffer + 4;
340 size_t data_len =
len - 4;
341 if (data_size > data_len) {
342 ESP_LOGW(TAG,
"Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
346 datapoint.len = data_size;
348 switch (datapoint.type) {
350 datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
353 ESP_LOGD(TAG,
"Datapoint %u update to %s", datapoint.id,
358 if (data_size != 1) {
359 ESP_LOGW(TAG,
"Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
362 datapoint.value_bool = data[0];
363 ESP_LOGD(TAG,
"Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
366 if (data_size != 4) {
367 ESP_LOGW(TAG,
"Datapoint %u has bad integer len %zu", datapoint.id, data_size);
370 datapoint.value_uint =
encode_uint32(data[0], data[1], data[2], data[3]);
371 ESP_LOGD(TAG,
"Datapoint %u update to %d", datapoint.id, datapoint.value_int);
374 datapoint.value_string = std::string(
reinterpret_cast<const char *
>(data), data_size);
375 ESP_LOGD(TAG,
"Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
378 if (data_size != 1) {
379 ESP_LOGW(TAG,
"Datapoint %u has bad enum len %zu", datapoint.id, data_size);
382 datapoint.value_enum = data[0];
383 ESP_LOGD(TAG,
"Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
391 datapoint.value_bitmask =
encode_uint32(0, 0, data[0], data[1]);
394 datapoint.value_bitmask =
encode_uint32(data[0], data[1], data[2], data[3]);
397 ESP_LOGW(TAG,
"Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
400 ESP_LOGD(TAG,
"Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
403 ESP_LOGW(TAG,
"Datapoint %u has unknown type %#02hhX", datapoint.id,
static_cast<uint8_t
>(datapoint.type));
407 len -= data_size + 4;
408 buffer = data + data_size;
415 uint8_t len_hi = (uint8_t) (command.
payload.size() >> 8);
416 uint8_t len_lo = (uint8_t) (command.
payload.size() & 0xFF);
420 switch (command.
cmd) {
438#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
440 ESP_LOGV(TAG,
"Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u",
static_cast<uint8_t
>(command.
cmd),
442 static_cast<uint8_t
>(this->init_state_));
445 this->
write_array({0x55, 0xAA, version, (uint8_t) command.
cmd, len_hi, len_lo});
449 const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.
cmd + len_hi + len_lo;
458 if (this->
expected_response_.has_value() && delay > RECEIVE_TIMEOUT && !this->reader_.receiving()) {
463 ESP_LOGE(TAG,
"Initialization failed at init_state %u",
static_cast<uint8_t
>(this->
init_state_));
475 if (delay > COMMAND_DELAY && !this->
command_queue_.empty() && !this->reader_.receiving() && !this->handling_frame_ &&
476 !this->expected_response_.has_value()) {
495 std::vector<uint8_t>
buffer;
497 buffer.push_back(datapoint_id);
498 buffer.push_back(
static_cast<uint8_t
>(datapoint_type));
514 if (network_is_connected()) {
522#ifdef USE_CAPTIVE_PORTAL
548 ESP_LOGD(TAG,
"Sending WiFi Status");
564 if (!now.
is_valid() || now.
minute == this->last_force_time_sync_minute_)
571 std::vector<uint8_t> payload;
582 if (day_of_week == 0) {
587 ESP_LOGV(TAG,
"Sending local time");
589 ESP_LOGD(TAG,
"Sending local time");
594 ESP_LOGW(TAG,
"Sending missing local time");
595 payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
600 std::vector<uint8_t> payload;
609 ESP_LOGD(TAG,
"Sending gmt time");
613 ESP_LOGW(TAG,
"Sending missing gmt time");
614 payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void set_interval(const char *name, uint32_t interval, SchedulerCallback &&f)
Set an interval function with a const char* name.
void set_timeout(const char *name, uint32_t timeout, SchedulerCallback &&f)
Set a timeout 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 dump_config() override
Prints each child entity's dump; a transport that overrides it prints its own block first,...
void handle_datapoint_(const TuyaDatapoint &datapoint)
Store a datapoint received from the MCU and notify listeners.
bool gmt_time_sync_callback_registered_
time::RealTimeClock * time_id_
uint8_t last_force_time_sync_minute_
void send_command_(TuyaCommand command)
uint8_t protocol_version_
optional< TuyaCommandType > expected_response_
void register_local_time_sync_callback_()
void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data, size_t len) override
void send_local_time_(bool periodic=false)
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len)
bool time_sync_callback_registered_
void send_raw_command_(TuyaCommand command)
TuyaInitState get_init_state()
TuyaInitState init_state_
InternalGPIOPin * status_pin_
void process_command_queue_()
LengthFrameReader< MAX_FRAME_SIZE, TuyaFrame > reader_
void dump_config() override
void send_empty_command_(TuyaCommandType command)
bool handle_frame_(const uint8_t *frame, size_t len)
Returns false for a frame that fails the checksum.
std::vector< TuyaCommand > command_queue_
void handle_datapoints_(const uint8_t *buffer, size_t len)
uint32_t last_command_timestamp_
std::unique_ptr< char[]> product_
void check_force_time_sync_()
uint8_t get_wifi_status_code_()
void write_byte(uint8_t data)
void write_array(const uint8_t *data, size_t len)
bool read_frames(R &reader, F &&handle, uint32_t now, uint32_t &last_rx, uint32_t gap_ms=250)
Feed the waiting bytes to a LengthFrameReader; on a pass with none, gap_ms after last_rx,...
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
void warn_too_long(size_t len)
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()
Application App
Global storage of Application pointer - only one Application can exist.
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 >= internal::MIN_VALID_YEAR and the requested fields are in rang...
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]
static constexpr size_t PAYLOAD_AT
std::vector< uint8_t > payload