diff --git a/esphome/components/tuya/tuya.cpp b/esphome/components/tuya/tuya.cpp index 3058d82cc4..15ab4b6dc3 100644 --- a/esphome/components/tuya/tuya.cpp +++ b/esphome/components/tuya/tuya.cpp @@ -303,6 +303,22 @@ void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buff ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured"); } break; + case TuyaCommandType::GMT_TIME_QUERY: +#ifdef USE_TIME + if (this->time_id_ != nullptr) { + this->send_gmt_time_(); + + if (!this->gmt_time_sync_callback_registered_) { + // tuya mcu supports time, so we let them know when our time changed + this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); }); + this->gmt_time_sync_callback_registered_ = true; + } + } else +#endif + { + ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured"); + } + break; case TuyaCommandType::VACUUM_MAP_UPLOAD: this->send_command_( TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector{0x01}}); @@ -609,6 +625,25 @@ void Tuya::send_local_time_() { } this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload}); } +void Tuya::send_gmt_time_() { + std::vector payload; + ESPTime now = this->time_id_->utcnow(); + if (now.is_valid()) { + uint8_t year = now.year - 2000; + uint8_t month = now.month; + uint8_t day_of_month = now.day_of_month; + uint8_t hour = now.hour; + uint8_t minute = now.minute; + uint8_t second = now.second; + ESP_LOGD(TAG, "Sending gmt time"); + payload = std::vector{0x01, year, month, day_of_month, hour, minute, second}; + } else { + // By spec we need to notify MCU that the time was not obtained if this is a response to a query + ESP_LOGW(TAG, "Sending missing gmt time"); + payload = std::vector{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + } + this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload}); +} #endif void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector &value) { diff --git a/esphome/components/tuya/tuya.h b/esphome/components/tuya/tuya.h index 4e7ab5c7f9..b8bf4e0ab1 100644 --- a/esphome/components/tuya/tuya.h +++ b/esphome/components/tuya/tuya.h @@ -54,6 +54,7 @@ enum class TuyaCommandType : uint8_t { DATAPOINT_DELIVER = 0x06, DATAPOINT_REPORT_ASYNC = 0x07, DATAPOINT_QUERY = 0x08, + GMT_TIME_QUERY = 0x0C, WIFI_TEST = 0x0E, LOCAL_TIME_QUERY = 0x1C, DATAPOINT_REPORT_SYNC = 0x22, @@ -138,8 +139,10 @@ class Tuya final : public Component, public uart::UARTDevice { #ifdef USE_TIME void send_local_time_(); + void send_gmt_time_(); time::RealTimeClock *time_id_{nullptr}; bool time_sync_callback_registered_{false}; + bool gmt_time_sync_callback_registered_{false}; #endif TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT; bool init_failed_{false};