This LAN's router does not resolve external hostnames, so NTP uses hard-coded Cloudflare/Google anycast IPs instead of names. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
43 lines
1.2 KiB
C++
43 lines
1.2 KiB
C++
#include <RTClib.h>
|
|
#include <time.h>
|
|
#include <ESP8266WiFi.h>
|
|
#include "config.h"
|
|
#include "rtc_time.h"
|
|
|
|
static RTC_DS3231 rtc;
|
|
|
|
bool rtcBegin() { return rtc.begin(); }
|
|
bool rtcLostPower() { return rtc.lostPower(); }
|
|
|
|
RtcTime rtcNow() {
|
|
DateTime n = rtc.now();
|
|
return RtcTime{ n.year(), n.month(), n.day(), n.hour(), n.minute(), n.second() };
|
|
}
|
|
|
|
void rtcSet(const RtcTime& t) {
|
|
rtc.adjust(DateTime(t.year, t.month, t.day, t.hour, t.minute, t.second));
|
|
}
|
|
|
|
uint32_t rtcEpoch() {
|
|
return rtc.now().unixtime();
|
|
}
|
|
|
|
bool ntpSync(int tzOffsetMin) {
|
|
// NTP servers by IP to bypass DNS (this network doesn't resolve names reliably).
|
|
// Cloudflare (162.159.200.123) and Google (216.239.35.0/.4) are stable anycast.
|
|
configTime(tzOffsetMin * 60, 0, "162.159.200.123", "216.239.35.0", "216.239.35.4");
|
|
time_t now = time(nullptr);
|
|
int tries = 0;
|
|
while (now < 1700000000 && tries < 120) { // up to ~30 s
|
|
delay(250);
|
|
now = time(nullptr);
|
|
tries++;
|
|
}
|
|
if (now < 1700000000) return false;
|
|
struct tm* lt = localtime(&now);
|
|
rtcSet(RtcTime{ (uint16_t)(lt->tm_year + 1900), (uint8_t)(lt->tm_mon + 1),
|
|
(uint8_t)lt->tm_mday, (uint8_t)lt->tm_hour,
|
|
(uint8_t)lt->tm_min, (uint8_t)lt->tm_sec });
|
|
return true;
|
|
}
|