diff --git a/src/patrix/clock.cpp b/src/patrix/clock.cpp index 9941ee5..9ba3cd6 100644 --- a/src/patrix/clock.cpp +++ b/src/patrix/clock.cpp @@ -22,16 +22,16 @@ void clockLoop() { } if (!ntpSet && isWiFiConnected()) { - configTime(CLOCK_GMT_OFFSET_SECONDS, CLOCK_DST_OFFSET_SECONDS, WiFi.gatewayIP().toString().c_str(), CLOCK_NTP_SERVER2_URL); + 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, getClockStr()); + info("clock set after %ld seconds! So startup was at %s", clockOffset, getStartupStr()); + } else { + clockOffset = now; } } @@ -39,18 +39,46 @@ bool isClockSet() { return startupTime != 0; } -char buffer[20]; -char *getClockStr() { - const auto now = time(nullptr); - tm t{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; + return now >= CLOCK_EPOCH_SECONDS_MIN; } time_t clockCorrect(const time_t t) { diff --git a/src/patrix/clock.h b/src/patrix/clock.h index f3d992a..06ed605 100644 --- a/src/patrix/clock.h +++ b/src/patrix/clock.h @@ -7,7 +7,13 @@ void clockLoop(); bool isClockSet(); -char * getClockStr(); +char *getClockStr(time_t epoch = 0); + +char *getStartupStr(); + +time_t getUptimeSeconds(); + +char *getUptimeStr(); bool isCorrectTime(time_t now);