#include "clock.h" #include #include "log.h" #include "wifi.h" #define CLOCK_GMT_OFFSET_SECONDS 3600 #define CLOCK_DST_OFFSET_SECONDS 3600 #define CLOCK_NTP_SERVER2_URL "de.pool.ntp.org" #define CLOCK_EPOCH_SECONDS_MIN 1735686000 time_t clockOffset = 0; time_t startupTime = 0; auto ntpSet = false; void clockLoop() { if (isClockSet()) { return; } if (!ntpSet && isWiFiConnected()) { configTime(CLOCK_GMT_OFFSET_SECONDS, CLOCK_DST_OFFSET_SECONDS, CLOCK_NTP_SERVER2_URL, WiFi.gatewayIP().toString().c_str()); ntpSet = true; } const auto now = time(nullptr); if (isCorrectTime(now)) { clockOffset = now; } else { startupTime = now - clockOffset; info("clock set after %ld seconds! So startup was at %s", clockOffset, getStartupStr()); } } bool isClockSet() { return startupTime != 0; } char *getClockStr(const time_t epoch) { auto now = epoch; if (now == 0) { now = time(nullptr); } tm t{}; localtime_r(&now, &t); static char buffer[20]; snprintf(buffer, sizeof buffer, "%04d-%02d-%02d %02d:%02d:%02d", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); return buffer; } char *getStartupStr() { return getClockStr(startupTime); } time_t getUptimeSeconds() { return time(nullptr) - startupTime; } char *getUptimeStr() { const auto totalSeconds = getUptimeSeconds(); const auto totalMinutes = totalSeconds / 60; const auto totalHours = totalMinutes / 60; const auto partSeconds = totalSeconds % 60; const auto partMinutes = totalMinutes % 60; const auto partHours = totalHours % 24; const auto partDays = totalHours / 24; static char buffer[20]; snprintf(buffer, sizeof buffer, "%dd %2dh %2dm %2ds", partDays, partHours, partMinutes, partSeconds); return buffer; } bool isCorrectTime(const time_t now) { return now < CLOCK_EPOCH_SECONDS_MIN; } time_t clockCorrect(const time_t t) { if (!isClockSet() || isCorrectTime(t)) { return t; } return t + clockOffset; } void clockCorrect(time_t *t) { if (!isClockSet() || isCorrectTime(*t)) { return; } *t += clockOffset; }