34 static constexpr const char *
servers[] = {
"time.google.com",
"time.nist.gov",
"pool.ntp.org"};
49 mSyncTimeCallback = callback;
63 const unsigned short localUdpPort = 1234;
64 if (!udp.begin(localUdpPort)) {
69 while (udp.parsePacket() != 0) {
73 if (!_sendNTPPacket(udp)) {
79 bool responseReceived = _waitForResponse(udp, 1500, maxRetries, 10);
80 if (!responseReceived) {
81 UNIOT_LOG_ERROR(
"No UDP response received from NTP server after %d attempts.", maxRetries);
86 time_t currentEpoch = _processNTPResponse(udp);
92 if (mSyncTimeCallback) {
93 mSyncTimeCallback(currentEpoch);
111 bool _sendNTPPacket(WiFiUDP &udp) {
113 memset(packet, 0,
sizeof(packet));
114 packet[0] = 0b11100011;
126 const unsigned short ntpUdpPort = 123;
127 udp.beginPacket(selectedServer, ntpUdpPort);
128 size_t bytesWritten = udp.write(packet,
sizeof(packet));
129 if (bytesWritten !=
sizeof(packet)) {
134 UNIOT_LOG_TRACE(
"NTP packet sent to %s:%d.", selectedServer, ntpUdpPort);
151 bool _waitForResponse(WiFiUDP &udp,
unsigned long timeout,
int maxRetries,
unsigned long retryDelay) {
152 UNIOT_LOG_TRACE(
"Waiting for NTP response with timeout %lu ms and max %d retries.", timeout, maxRetries);
153 unsigned long startTime = millis();
155 for (
int attempt = 1; attempt <= maxRetries; ++attempt) {
156 unsigned long currentTime = millis();
157 if (currentTime - startTime >= timeout) {
158 UNIOT_LOG_WARN(
"NTP response wait timed out on attempt %d.", attempt);
162 int packetSize = udp.parsePacket();
163 if (packetSize >= 48) {
184 time_t _processNTPResponse(WiFiUDP &udp) {
186 int len = udp.read(packet,
sizeof(packet));
188 UNIOT_LOG_ERROR(
"Incomplete NTP packet received. Expected 48 bytes, got %d bytes.", len);
193 unsigned long highWord = word(packet[40], packet[41]);
194 unsigned long lowWord = word(packet[42], packet[43]);
195 unsigned long secsSince1900 = (highWord << 16) | lowWord;
198 time_t currentEpoch = secsSince1900 - 2208988800UL;
void(* SyncTimeCallback)(time_t epoch)
Callback function type for time synchronization events.
Definition SimpleNTP.h:27
static constexpr const char * servers[]
Array of NTP server hostnames to try connecting to.
Definition SimpleNTP.h:34
SimpleNTP()
Default constructor.
Definition SimpleNTP.h:41
time_t getNtpTime()
Requests and retrieves current time from NTP server.
Definition SimpleNTP.h:61
void setSyncTimeCallback(SyncTimeCallback callback)
Sets the callback function for time synchronization events.
Definition SimpleNTP.h:48
#define UNIOT_LOG_TRACE(...)
Log an TRACE level message Used for general information about system operation. Only compiled if UNIO...
Definition Logger.h:314
#define UNIOT_LOG_WARN(...)
Log an WARN level message Used for warnings about potentially problematic situations....
Definition Logger.h:247
#define UNIOT_LOG_ERROR(...)
Log an ERROR level message Used for critical errors that may prevent normal operation....
Definition Logger.h:226
Contains all classes and functions related to the Uniot Core.