I have asked here before concerning usage of the NTP time servers to acquire accurate time via the network.
I got advice and links to an NTP library to use.
But there is one thing I am not understanding how to do properly yet:
How do I read the current time as a time_t value inside the sketch at various places without actually calling the NTP server?
The NTP object should handle repeated sync to the server as needed, so as to limit network traffic.
It looks like if I use the NTP object to get the current time in my sketch it always makes a call to the server and quite often this fails and I get a time of zero.
Is there no way to read the synced time without calling out to the server?
My current project is a device that will sleep for long times, then wake up for a short while and perform a task where it needs the time. So there is an NTP request in setup() that executes once and for further use I would like to be able to call a function that gives back the current time in a time_t format without calling the NTP server at all.
Here is how the NTP object is started in loop() after checking that WiFi has been connected so there is an Internet availability:
void HandleNtpClient()
{
if (wifiFirstConnected) { //One time execution following WiFi connect
wifiFirstConnected = false;
NTP.begin ("pool.ntp.org", timeZone, true, minutesTimeZone);
NTP.setInterval (60, 86400); //Initial NTP call repeat 1 min, then 24h between calls
}
if (syncEventTriggered) {
processSyncEvent (ntpEvent);
syncEventTriggered = false;
}
}
void loop()
{
//Check if a new DHT reading is requested:
unsigned long tickcount = millis();
HandleNtpClient();
... other loop code .....
}
Then in the actual code I need to read the current time in several places, but if I use this:
t = NTP.getTime();
It looks like NTP actually calls to the server every time....
Even though NTP was successfully initialized NTP.getTime() fails often if I call it later in several places.
It seems like a function time_t CurrentTime() should exist that uses a single (NTP internal) server call plus the millis() function to calculate the current time....
And BTW:
Is there a convenient function to stuff a time_t variable content into a string (char array) in a time or date or date time format without resorting to sprintf or similar? I just want to send the time or date out in ISO format to the serial debug output. Like:
2019-02-03 08:16:01