Open tigoe opened 9 months ago
I took the example from the WiFi libraries that Michael Margolis originally wrote, did some digging in the NTP RFC, and re-wrote it into a generic function. This should work with any of the WiFi libraries, and could also be submitted to Espressif as a pull request for the ESP32 library. I tested it there too. It requires the UDP library though:
// send an NTP request and wait for the result:
// Thanks to Michael Margolis for the original inspiration and RFC 5905 for the details.
unsigned long getTime() {
WiFiUDP Udp;
Udp.begin(localPort);
// NTP timestamp packet is 48 bytes:
const int NTP_PACKET_SIZE = 48;
// diff between NTP result and current UTC epoch is 70 years in seconds:
const unsigned long SEVENTY_YEARS = 2208988800UL;
// byte buffer for NTP packet:
byte packetBuffer[NTP_PACKET_SIZE];
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// simplest NTP request needs only the leap indicator, NTP version, and mode.
// see RFC5905: https://datatracker.ietf.org/doc/html/rfc5905
packetBuffer[0] = 0b00100011; // Leap indicator 0, version 4, mode 3
// send request to pool.ntp.org, port 123:
Udp.beginPacket("pool.ntp.org", 123);
Udp.write(packetBuffer, NTP_PACKET_SIZE);
Udp.endPacket();
// wait for return packet:
while (!Udp.parsePacket())
;
// Parse the return packet:
Udp.read(packetBuffer, NTP_PACKET_SIZE);
//the timestamp (32 bit integer) starts at byte 40
// of the received packet:
unsigned long result = 0;
for (byte b = 40; b < 44; b++) {
// shift the whole thing over 8 bits, and add the next byte:
result = (result << 8) | packetBuffer[b];
}
// subtract the time since 1900:
result = result - SEVENTY_YEARS;
return result;
}
Espressif has NTP time in the SDK.
configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org");
time_t now = time(nullptr);
while (now < SECS_YR_2000) {
delay(100);
now = time(nullptr);
}
I plan to do the getTime implementations.
created a pull request to add gettime. The user provide POSIX timezone & daylight saving information for the current location. The output can be formatted according to the strftime() Requires both the core and bridge to be updated. Also includes an example to demonstrate the usage.
regards, Paul
The getTime() function in the WiFiS2 library never gets the time via NTP.
Here's a test:
When you run this on the Uno R4 WiFi, it'll compile, but you'll get an endless stream of "NTP request attempt" messages.