Files
crosspoint-reader-mod/src/util/TimeSync.cpp

59 lines
1.2 KiB
C++
Raw Normal View History

#include "TimeSync.h"
#include <Logging.h>
#include <esp_sntp.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <cstdlib>
#include "CrossPointSettings.h"
namespace TimeSync {
void startNtpSync() {
if (esp_sntp_enabled()) {
esp_sntp_stop();
}
// Apply timezone so NTP-synced time is displayed correctly
setenv("TZ", SETTINGS.getTimezonePosixStr(), 1);
tzset();
esp_sntp_setoperatingmode(ESP_SNTP_OPMODE_POLL);
esp_sntp_setservername(0, "pool.ntp.org");
esp_sntp_init();
LOG_DBG("NTP", "SNTP service started");
}
bool waitForNtpSync(int timeoutMs) {
startNtpSync();
const int intervalMs = 100;
const int maxRetries = timeoutMs / intervalMs;
int retry = 0;
while (sntp_get_sync_status() != SNTP_SYNC_STATUS_COMPLETED && retry < maxRetries) {
vTaskDelay(intervalMs / portTICK_PERIOD_MS);
retry++;
}
if (retry < maxRetries) {
LOG_DBG("NTP", "Time synced after %d ms", retry * intervalMs);
return true;
}
LOG_DBG("NTP", "Sync timeout after %d ms", timeoutMs);
return false;
}
void stopNtpSync() {
if (esp_sntp_enabled()) {
esp_sntp_stop();
LOG_DBG("NTP", "SNTP service stopped");
}
}
} // namespace TimeSync