Skip to content

Commit 5c85ac1

Browse files
committed
ESP8266: add NTP sync timeout
1 parent 8c7a834 commit 5c85ac1

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

src/utility/time/TimeService.cpp

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ time_t cvt_time(char const * time);
4343
* CONSTANTS
4444
**************************************************************************************/
4545

46+
#ifdef ARDUINO_ARCH_ESP8266
47+
static unsigned long const AIOT_TIMESERVICE_ESP8266_NTP_SYNC_TIMEOUT_ms = 86400000;
48+
#endif
4649
static time_t const EPOCH_AT_COMPILE_TIME = cvt_time(__DATE__);
4750
static time_t const EPOCH = 0;
4851

@@ -57,8 +60,9 @@ TimeService::TimeService()
5760
, _timezone_offset(0)
5861
, _timezone_dst_until(0)
5962
#ifdef ARDUINO_ARCH_ESP8266
60-
, _soft_rtc_value(0)
61-
, _soft_rtc_offset(0)
63+
, _last_ntp_sync_tick(0)
64+
, _last_rtc_update_tick(0)
65+
, _rtc(0)
6266
#endif
6367
{
6468

@@ -110,19 +114,27 @@ unsigned long TimeService::getTime()
110114
}
111115
return time(NULL);
112116
#elif ARDUINO_ARCH_ESP8266
113-
if(!_is_rtc_configured || millis() < _soft_rtc_offset)
117+
unsigned long const now = millis();
118+
bool const is_ntp_sync_timeout = (now - _last_ntp_sync_tick) > AIOT_TIMESERVICE_ESP8266_NTP_SYNC_TIMEOUT_ms;
119+
if(!_is_rtc_configured || is_ntp_sync_timeout)
114120
{
115121
_is_rtc_configured = false;
116122
unsigned long utc = getRemoteTime();
117123
if(EPOCH_AT_COMPILE_TIME != utc)
118124
{
119-
_soft_rtc_value = utc;
120-
_soft_rtc_offset = millis();
125+
_rtc = utc;
126+
_last_ntp_sync_tick = now;
127+
_last_rtc_update_tick = now;
121128
_is_rtc_configured = true;
122129
}
123130
return utc;
124131
}
125-
return _soft_rtc_value + ((millis() - _soft_rtc_offset) / 1000);
132+
unsigned long const elapsed_s = (now - _last_rtc_update_tick) / 1000;
133+
if(elapsed_s) {
134+
_rtc += elapsed_s;
135+
_last_rtc_update_tick = now;
136+
}
137+
return _rtc;
126138
#else
127139
return getRemoteTime();
128140
#endif

src/utility/time/TimeService.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,9 @@ class TimeService
6161
long _timezone_offset;
6262
unsigned long _timezone_dst_until;
6363
#ifdef ARDUINO_ARCH_ESP8266
64-
unsigned long _soft_rtc_value;
65-
unsigned long _soft_rtc_offset;
64+
unsigned long _last_ntp_sync_tick;
65+
unsigned long _last_rtc_update_tick;
66+
unsigned long _rtc;
6667
#endif
6768

6869
unsigned long getRemoteTime();

0 commit comments

Comments
 (0)