Skip to content

Commit ab1c35f

Browse files
committed
Fix 1970 date after crash/watchdog/brownout reset on ESP32
Currently, time is only set to ~2024 when it powers on cleanly. When time is lost, this results in time dropping to 1970. Save time as backup to RTC slow memory. Should fix time staying accurate during brownouts etc.
1 parent cdd3d5f commit ab1c35f

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

src/helpers/ESP32Board.h

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -128,29 +128,50 @@ class ESP32Board : public mesh::MainBoard {
128128
}
129129
};
130130

131+
static RTC_NOINIT_ATTR uint32_t _rtc_backup_time;
132+
static RTC_NOINIT_ATTR uint32_t _rtc_backup_magic;
133+
#define RTC_BACKUP_MAGIC 0xAA55CC33
134+
#define RTC_TIME_MIN 1772323200 // 1 Mar 2026
135+
131136
class ESP32RTCClock : public mesh::RTCClock {
132137
public:
133138
ESP32RTCClock() { }
134139
void begin() {
135140
esp_reset_reason_t reason = esp_reset_reason();
136-
if (reason == ESP_RST_POWERON) {
137-
// start with some date/time in the recent past
138-
struct timeval tv;
139-
tv.tv_sec = 1715770351; // 15 May 2024, 8:50pm
140-
tv.tv_usec = 0;
141-
settimeofday(&tv, NULL);
141+
if (reason == ESP_RST_DEEPSLEEP) {
142+
return; // ESP-IDF preserves system time across deep sleep
143+
}
144+
// All other resets (power-on, crash, WDT, brownout) lose system time.
145+
// Restore from RTC backup if valid, otherwise use hardcoded seed.
146+
struct timeval tv;
147+
if (_rtc_backup_magic == RTC_BACKUP_MAGIC && _rtc_backup_time > RTC_TIME_MIN) {
148+
tv.tv_sec = _rtc_backup_time;
149+
} else {
150+
tv.tv_sec = 1772323200; // 1 Mar 2026
142151
}
152+
tv.tv_usec = 0;
153+
settimeofday(&tv, NULL);
143154
}
144155
uint32_t getCurrentTime() override {
145156
time_t _now;
146157
time(&_now);
147158
return _now;
148159
}
149-
void setCurrentTime(uint32_t time) override {
160+
void setCurrentTime(uint32_t time) override {
150161
struct timeval tv;
151162
tv.tv_sec = time;
152163
tv.tv_usec = 0;
153164
settimeofday(&tv, NULL);
165+
_rtc_backup_time = time;
166+
_rtc_backup_magic = RTC_BACKUP_MAGIC;
167+
}
168+
void tick() override {
169+
time_t now;
170+
time(&now);
171+
if (now > RTC_TIME_MIN && (uint32_t)now != _rtc_backup_time) {
172+
_rtc_backup_time = (uint32_t)now;
173+
_rtc_backup_magic = RTC_BACKUP_MAGIC;
174+
}
154175
}
155176
};
156177

0 commit comments

Comments
 (0)