Skip to content

Commit

Permalink
Resync time via NTP once a day
Browse files Browse the repository at this point in the history
Signed-off-by: John Walicki <johnwalicki@gmail.com>
  • Loading branch information
johnwalicki committed May 1, 2021
1 parent 2b513b1 commit d9c16d6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
3 changes: 2 additions & 1 deletion WatsonIoT/src/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
16 changes: 14 additions & 2 deletions WatsonIoT/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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
}


Expand Down Expand Up @@ -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);
}

Expand Down

0 comments on commit d9c16d6

Please # to comment.