Skip to content

Commit d9c16d6

Browse files
committed
Resync time via NTP once a day
Signed-off-by: John Walicki <[email protected]>
1 parent 2b513b1 commit d9c16d6

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

WatsonIoT/src/config.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@
3535
if (LOG_L2) \
3636
Serial.println(x);
3737

38-
#define CONNECTION_TO 6000 //ms
38+
#define CONNECTION_TO 6000 //ms
3939
#define RECONNECTION_TO 10000 //ms
40+
#define RESYNCTIME 86400 // Resync the ESP32 time once a day
4041

4142
#define PRODUCTION_BOARD 1

WatsonIoT/src/main.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -739,8 +739,13 @@ void NetworkEvent(WiFiEvent_t event) {
739739
}
740740

741741

742+
time_t periodic_timesync;
742743
// MQTT SSL requires a relatively accurate time between broker and client
743744
void SetTimeESP32() {
745+
time_t now = time(nullptr);
746+
Serial.print("Before time sync : ");
747+
Serial.println(ctime(&now));
748+
744749
// Set time from NTP servers
745750
configTime(TZ_OFFSET * 3600, TZ_DST * 60, "time.nist.gov", "pool.ntp.org");
746751
Serial.println("\nWaiting for time");
@@ -759,9 +764,11 @@ void SetTimeESP32() {
759764
delay(100);
760765
}
761766
delay(1000); // Wait for time to fully sync
762-
Serial.println("Time sync'd");
763-
time_t now = time(nullptr);
767+
768+
Serial.print("After time sync: ");
769+
now = time(nullptr);
764770
Serial.println(ctime(&now));
771+
periodic_timesync = now; // periodically resync the time to prevent drift
765772
}
766773

767774

@@ -1048,6 +1055,11 @@ void loop() {
10481055
if( adxstatus )
10491056
NeoPixelBreathe();
10501057

1058+
if( (time(nullptr) - periodic_timesync) > RESYNCTIME ) {
1059+
// Resync the ESP32 time once a day so that MQTT and Seismology time is accurate
1060+
SetTimeESP32();
1061+
}
1062+
10511063
delay(10);
10521064
}
10531065

0 commit comments

Comments
 (0)