NTP
NTP copied to clipboard
Clock is set to 2036-02-07 sometimes
As I found, this NTP library has the same deficiency as others if there is no (valid?) NTP server feedback. In this case ntpTime = 0, and the resulting time is 2036-02-07 ca. 7:30h. As I have no time to dig deep into the mechanism of NTP I added a simple test for 0. By this 0-validation I did not get any 2036 time so far.
Relation: https://github.com/ropg/ezTime/issues/25
I split the get and unpack into two updates. Since update() is in the loop and certainly should run much more often than 100ms, this gets the packet, then waits 100ms for a subsequent call to check and unpack the data, with no blocking. If the read is bad, updateInterval() is changed to a shorter period until a good read is performed. I'm still testing, but this seems to work well.
bool NTP::update() {
if (((millis() - lastUpdate >= interval) || lastUpdate == 0) && waiting == 0) {
udp->flush();
if (server == nullptr) udp->beginPacket(serverIP, NTP_PORT);
else udp->beginPacket(server, NTP_PORT);
udp->write(ntpRequest, NTP_PACKET_SIZE);
udp->endPacket();
waiting = millis(); // get packet, waiting to unpack
return false; // just getting packet so always return false
}
if (millis() - waiting > 100) { // see if it's there after 100ms and unpack
waiting = 0; // one try only - if it's not there after 100ms, it won't be there at all this poll
uint8_t size = udp->parsePacket();
if (size == 48) {
lastUpdate = millis() - waiting;
udp->read(ntpQuery, NTP_PACKET_SIZE);
uint32_t ntpTime = ntpQuery[40] << 24 | ntpQuery[41] << 16 | ntpQuery[42] << 8 | ntpQuery[43];
utcTime = ntpTime - SEVENTYYEARS;
interval = oInterval; // good read so set back to original interval
return true;
}
}
else interval = eInterval; // bad read so shorten interval
return false;
}
should solved with 1.7