From 584b722e7ed81c116faba601f46f20d952031a45 Mon Sep 17 00:00:00 2001 From: Javier Peletier Date: Wed, 5 Oct 2022 03:52:45 +0200 Subject: [PATCH] Fix time/automation (cron) wdt crash when time jumps ahead too much (#3844) --- esphome/components/time/automation.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/esphome/components/time/automation.cpp b/esphome/components/time/automation.cpp index 7e16d7141f..af2b6c720c 100644 --- a/esphome/components/time/automation.cpp +++ b/esphome/components/time/automation.cpp @@ -6,6 +6,8 @@ namespace esphome { namespace time { static const char *const TAG = "automation"; +static const int MAX_TIMESTAMP_DRIFT = 900; // how far can the clock drift before we consider + // there has been a drastic time synchronization void CronTrigger::add_second(uint8_t second) { this->seconds_[second] = true; } void CronTrigger::add_minute(uint8_t minute) { this->minutes_[minute] = true; } @@ -23,12 +25,17 @@ void CronTrigger::loop() { return; if (this->last_check_.has_value()) { - if (*this->last_check_ > time && this->last_check_->timestamp - time.timestamp > 900) { + if (*this->last_check_ > time && this->last_check_->timestamp - time.timestamp > MAX_TIMESTAMP_DRIFT) { // We went back in time (a lot), probably caused by time synchronization ESP_LOGW(TAG, "Time has jumped back!"); } else if (*this->last_check_ >= time) { // already handled this one return; + } else if (time > *this->last_check_ && time.timestamp - this->last_check_->timestamp > MAX_TIMESTAMP_DRIFT) { + // We went ahead in time (a lot), probably caused by time synchronization + ESP_LOGW(TAG, "Time has jumped ahead!"); + this->last_check_ = time; + return; } while (true) {