From d9c16d6465fa8cf7ee647e353b1d08d66dd70db3 Mon Sep 17 00:00:00 2001 From: John Walicki Date: Fri, 30 Apr 2021 21:17:03 -0400 Subject: [PATCH] Resync time via NTP once a day Signed-off-by: John Walicki --- WatsonIoT/src/config.h | 3 ++- WatsonIoT/src/main.cpp | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/WatsonIoT/src/config.h b/WatsonIoT/src/config.h index 36959b5..e7c8e03 100644 --- a/WatsonIoT/src/config.h +++ b/WatsonIoT/src/config.h @@ -35,7 +35,8 @@ if (LOG_L2) \ Serial.println(x); -#define CONNECTION_TO 6000 //ms +#define CONNECTION_TO 6000 //ms #define RECONNECTION_TO 10000 //ms +#define RESYNCTIME 86400 // Resync the ESP32 time once a day #define PRODUCTION_BOARD 1 diff --git a/WatsonIoT/src/main.cpp b/WatsonIoT/src/main.cpp index dadd8df..c275c5e 100644 --- a/WatsonIoT/src/main.cpp +++ b/WatsonIoT/src/main.cpp @@ -739,8 +739,13 @@ void NetworkEvent(WiFiEvent_t event) { } +time_t periodic_timesync; // MQTT SSL requires a relatively accurate time between broker and client void SetTimeESP32() { + time_t now = time(nullptr); + Serial.print("Before time sync : "); + Serial.println(ctime(&now)); + // Set time from NTP servers configTime(TZ_OFFSET * 3600, TZ_DST * 60, "time.nist.gov", "pool.ntp.org"); Serial.println("\nWaiting for time"); @@ -759,9 +764,11 @@ void SetTimeESP32() { delay(100); } delay(1000); // Wait for time to fully sync - Serial.println("Time sync'd"); - time_t now = time(nullptr); + + Serial.print("After time sync: "); + now = time(nullptr); Serial.println(ctime(&now)); + periodic_timesync = now; // periodically resync the time to prevent drift } @@ -1048,6 +1055,11 @@ void loop() { if( adxstatus ) NeoPixelBreathe(); + if( (time(nullptr) - periodic_timesync) > RESYNCTIME ) { + // Resync the ESP32 time once a day so that MQTT and Seismology time is accurate + SetTimeESP32(); + } + delay(10); }