Skip to content

Commit 9471ee0

Browse files
committed
Make use of initRTC and sync functions
1 parent 82699bb commit 9471ee0

File tree

1 file changed

+10
-58
lines changed

1 file changed

+10
-58
lines changed

src/utility/time/TimeService.cpp

Lines changed: 10 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -117,69 +117,21 @@ TimeService::TimeService()
117117
void TimeService::begin(ConnectionHandler * con_hdl)
118118
{
119119
_con_hdl = con_hdl;
120-
#ifdef ARDUINO_ARCH_SAMD
121-
rtc.begin();
122-
#endif
120+
initRTC();
123121
}
124122

125123
unsigned long TimeService::getTime()
126124
{
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();
137130
}
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;
183135
}
184136

185137
bool TimeService::sync()

0 commit comments

Comments
 (0)