clock startupTime FIX

This commit is contained in:
Patrick Haßel 2025-01-16 11:55:00 +01:00
parent ebacfbed02
commit dd64709884
2 changed files with 44 additions and 10 deletions

View File

@ -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) {

View File

@ -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);