@@ -43,6 +43,9 @@ time_t cvt_time(char const * time);
43
43
* CONSTANTS
44
44
**************************************************************************************/
45
45
46
+ #ifdef ARDUINO_ARCH_ESP8266
47
+ static unsigned long const AIOT_TIMESERVICE_ESP8266_NTP_SYNC_TIMEOUT_ms = 86400000 ;
48
+ #endif
46
49
static time_t const EPOCH_AT_COMPILE_TIME = cvt_time(__DATE__);
47
50
static time_t const EPOCH = 0 ;
48
51
@@ -57,8 +60,9 @@ TimeService::TimeService()
57
60
, _timezone_offset(0 )
58
61
, _timezone_dst_until(0 )
59
62
#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 )
62
66
#endif
63
67
{
64
68
@@ -110,19 +114,27 @@ unsigned long TimeService::getTime()
110
114
}
111
115
return time (NULL );
112
116
#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)
114
120
{
115
121
_is_rtc_configured = false ;
116
122
unsigned long utc = getRemoteTime ();
117
123
if (EPOCH_AT_COMPILE_TIME != utc)
118
124
{
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;
121
128
_is_rtc_configured = true ;
122
129
}
123
130
return utc;
124
131
}
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;
126
138
#else
127
139
return getRemoteTime ();
128
140
#endif
0 commit comments