[time] Add `USE_TIME_TIMEZONE` define (#9290)

This commit is contained in:
Jesse Hills 2025-07-03 01:51:25 +12:00 committed by GitHub
parent 289aedcfe2
commit 9b3ece4caf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 25 additions and 2 deletions

View File

@ -268,7 +268,19 @@ def validate_tz(value: str) -> str:
TIME_SCHEMA = cv.Schema(
{
cv.Optional(CONF_TIMEZONE, default=detect_tz): validate_tz,
cv.SplitDefault(
CONF_TIMEZONE,
esp8266=detect_tz,
esp32=detect_tz,
rp2040=detect_tz,
bk72xx=detect_tz,
rtl87xx=detect_tz,
ln882x=detect_tz,
host=detect_tz,
): cv.All(
cv.only_with_framework(["arduino", "esp-idf", "host"]),
validate_tz,
),
cv.Optional(CONF_ON_TIME): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(CronTrigger),
@ -293,7 +305,9 @@ TIME_SCHEMA = cv.Schema(
async def setup_time_core_(time_var, config):
cg.add(time_var.set_timezone(config[CONF_TIMEZONE]))
if timezone := config.get(CONF_TIMEZONE):
cg.add(time_var.set_timezone(timezone))
cg.add_define("USE_TIME_TIMEZONE")
for conf in config.get(CONF_ON_TIME, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], time_var)

View File

@ -35,8 +35,10 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
ret = settimeofday(&timev, nullptr);
}
#ifdef USE_TIME_TIMEZONE
// Move timezone back to local timezone.
this->apply_timezone_();
#endif
if (ret != 0) {
ESP_LOGW(TAG, "setimeofday() failed with code %d", ret);
@ -49,10 +51,12 @@ void RealTimeClock::synchronize_epoch_(uint32_t epoch) {
this->time_sync_callback_.call();
}
#ifdef USE_TIME_TIMEZONE
void RealTimeClock::apply_timezone_() {
setenv("TZ", this->timezone_.c_str(), 1);
tzset();
}
#endif
} // namespace time
} // namespace esphome

View File

@ -20,6 +20,7 @@ class RealTimeClock : public PollingComponent {
public:
explicit RealTimeClock();
#ifdef USE_TIME_TIMEZONE
/// Set the time zone.
void set_timezone(const std::string &tz) {
this->timezone_ = tz;
@ -28,6 +29,7 @@ class RealTimeClock : public PollingComponent {
/// Get the time zone currently in use.
std::string get_timezone() { return this->timezone_; }
#endif
/// Get the time in the currently defined timezone.
ESPTime now() { return ESPTime::from_epoch_local(this->timestamp_now()); }
@ -46,8 +48,10 @@ class RealTimeClock : public PollingComponent {
/// Report a unix epoch as current time.
void synchronize_epoch_(uint32_t epoch);
#ifdef USE_TIME_TIMEZONE
std::string timezone_{};
void apply_timezone_();
#endif
CallbackManager<void()> time_sync_callback_;
};

View File

@ -116,6 +116,7 @@
#define USE_OTA_PASSWORD
#define USE_OTA_STATE_CALLBACK
#define USE_OTA_VERSION 2
#define USE_TIME_TIMEZONE
#define USE_WIFI
#define USE_WIFI_AP
#define USE_WIREGUARD