AceTimeClock  1.3.0
Clock classes for Arduino that can synchronize from an NTP server or an RTC chip
EspSntpClock.cpp
1 #include <Arduino.h>
2 #include "EspSntpClock.h"
3 
4 #if defined(ESP8266) || defined(ESP32) || defined(EPOXY_CORE_ESP8266)
5 
6 namespace ace_time {
7 namespace clock {
8 
9 // Value of time_t for 2000-01-01 00:00:00, used to detect invalid SNTP
10 // responses.
11 static const time_t EPOCH_2000_01_01 = 946684800;
12 
13 const char EspSntpClock::kDefaultNtpServer[] = "pool.ntp.org";
14 
15 bool EspSntpClock::setup(const char* ntpServer, uint32_t timeoutMillis) {
16  Serial.print(F("Configuring SNTP"));
17 
18  // Use UTC timezone with no STD offset and no DST offset.
19  configTime(0 /*timezone*/, 0 /*dst_sec*/, ntpServer);
20 
21  // Wait until SNTP stabilizes by ignoring values before year 2000.
22  uint32_t startMillis = millis();
23  while (true) {
24  Serial.print('.'); // each '.' represents an attempt
25  time_t now = time(nullptr);
26  if (now >= EPOCH_2000_01_01) {
27  Serial.println(F(" Done."));
28  return true;
29  }
30 
31  uint32_t elapsedMillis = millis() - startMillis;
32  if (elapsedMillis >= timeoutMillis) {
33  Serial.println(F(" Failed!"));
34  return false;
35  }
36 
37  delay(500);
38  }
39 }
40 
41 }
42 }
43 
44 #endif
bool setup(const char *ntpServer=kDefaultNtpServer, uint32_t timeoutMillis=kDefaultTimeoutMillis)
Setup the SNTP client.
static const char kDefaultNtpServer[]
Default NTP server, "pool.ntp.org".
Definition: EspSntpClock.h:28