@@ -117,69 +117,21 @@ TimeService::TimeService()
117
117
void TimeService::begin (ConnectionHandler * con_hdl)
118
118
{
119
119
_con_hdl = con_hdl;
120
- #ifdef ARDUINO_ARCH_SAMD
121
- rtc.begin ();
122
- #endif
120
+ initRTC ();
123
121
}
124
122
125
123
unsigned long TimeService::getTime ()
126
124
{
127
- #ifdef ARDUINO_ARCH_SAMD
128
- if (!_is_rtc_configured)
129
- {
130
- unsigned long utc = getRemoteTime ();
131
- if (EPOCH_AT_COMPILE_TIME != utc)
132
- {
133
- rtc.setEpoch (utc);
134
- _is_rtc_configured = true ;
135
- }
136
- return utc;
125
+ /* Check if it's time to sync */
126
+ unsigned long const current_tick = millis ();
127
+ bool const is_ntp_sync_timeout = (current_tick - _last_ntp_sync_tick) > AIOT_TIMESERVICE_NTP_SYNC_TIMEOUT_ms;
128
+ if (!_is_rtc_configured || is_ntp_sync_timeout) {
129
+ sync ();
137
130
}
138
- return rtc.getEpoch ();
139
- #elif ARDUINO_ARCH_MBED
140
- if (!_is_rtc_configured)
141
- {
142
- unsigned long utc = getRemoteTime ();
143
- if (EPOCH_AT_COMPILE_TIME != utc)
144
- {
145
- set_time (utc);
146
- _is_rtc_configured = true ;
147
- }
148
- return utc;
149
- }
150
- return time (NULL );
151
- #elif ARDUINO_ARCH_ESP32
152
- if (!_is_rtc_configured)
153
- {
154
- configTime (0 , 0 , " time.arduino.cc" , " pool.ntp.org" , " time.nist.gov" );
155
- _is_rtc_configured = true ;
156
- }
157
- return time (NULL );
158
- #elif ARDUINO_ARCH_ESP8266
159
- unsigned long const now = millis ();
160
- bool const is_ntp_sync_timeout = (now - _last_ntp_sync_tick) > AIOT_TIMESERVICE_ESP8266_NTP_SYNC_TIMEOUT_ms;
161
- if (!_is_rtc_configured || is_ntp_sync_timeout)
162
- {
163
- _is_rtc_configured = false ;
164
- unsigned long utc = getRemoteTime ();
165
- if (EPOCH_AT_COMPILE_TIME != utc)
166
- {
167
- _rtc = utc;
168
- _last_ntp_sync_tick = now;
169
- _last_rtc_update_tick = now;
170
- _is_rtc_configured = true ;
171
- }
172
- return utc;
173
- }
174
- unsigned long const elapsed_s = (now - _last_rtc_update_tick) / 1000 ;
175
- if (elapsed_s) {
176
- _rtc += elapsed_s;
177
- _last_rtc_update_tick = now;
178
- }
179
- return _rtc;
180
- #else
181
- return getRemoteTime ();
182
- #endif
131
+
132
+ /* Read time from RTC */
133
+ unsigned long utc = getRTC ();
134
+ return isTimeValid (utc) ? utc : EPOCH_AT_COMPILE_TIME;
183
135
}
184
136
185
137
bool TimeService::sync ()
0 commit comments