Skip to content

Commit

Permalink
Merge pull request #626 from croggero/dev
Browse files Browse the repository at this point in the history
Fix for NTP blocking loop if connection is blocked
  • Loading branch information
matjack1 committed Apr 9, 2024
2 parents d7be1a4 + 5f54e88 commit 17e198b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
32 changes: 22 additions & 10 deletions src/helpers.esp
Expand Up @@ -19,21 +19,33 @@ void ICACHE_FLASH_ATTR parseBytes(const char *str, char sep, byte *bytes, int ma

// This is part of the latest releases of Arduino for ESP8266
// https://github.com/SensorsIot/NTP-time-for-ESP8266-and-ESP32/
bool getNTPtime(int sec)
void trySyncNTPtime(int retrySeconds)
{
uint32_t start = millis();
time_t previousEpoch = epoch;
do
// If time since last sync is less then retry than update using last clock
if (millis() - lastNTPSync < retrySeconds * 1000)
{
time(&epoch);
localtime_r(&epoch, &timeinfo);
delay(10);
} while (((millis() - start) <= (1000 * sec)) && (timeinfo.tm_year < (2016 - 1900)));
epoch = lastNTPepoch + (int)(millis() - lastNTPSync) / 1000;
return;
}

time_t previousEpoch = epoch;
time(&epoch);
lastNTPSync = millis();
localtime_r(&epoch, &timeinfo);

if (timeinfo.tm_year <= (2016 - 1900))
{
#if DEBUG
Serial.println("[DEBUG] NTP sync failed");
#endif

epoch = previousEpoch; // fallback to previous value, so that you can use the manually set time
return false; // the NTP call was not successful
return;
}

return true;
#if DEBUG
Serial.println("[DEBUG] NTP sync success");
#endif

lastNTPepoch = epoch;
}
5 changes: 4 additions & 1 deletion src/main.cpp
Expand Up @@ -95,6 +95,8 @@ uint8_t lastDoorState = 0;
uint8_t lastTamperState = 0;
unsigned long nextbeat = 0;
time_t epoch;
time_t lastNTPepoch;
unsigned long lastNTPSync = 0;
unsigned long openDoorMillis = 0;
unsigned long previousLoopMillis = 0;
unsigned long previousMillis = 0;
Expand Down Expand Up @@ -177,7 +179,8 @@ void ICACHE_RAM_ATTR loop()
deltaTime = currentMillis - previousLoopMillis;
uptimeSeconds = currentMillis / 1000;
previousLoopMillis = currentMillis;
getNTPtime(10);

trySyncNTPtime(10);

openLockButton.update();
if (config.openlockpin != 255 && openLockButton.fell())
Expand Down
2 changes: 1 addition & 1 deletion src/wifi.esp
Expand Up @@ -175,7 +175,7 @@ bool ICACHE_FLASH_ATTR connectSTA(const char *ssid, const char *password, byte b
configTime(0, 0, config.ntpServer);
// See https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv for Timezone codes for your region
setenv("TZ", config.tzInfo, 1);
getNTPtime(10);
trySyncNTPtime(10);
return true;
}
else
Expand Down

0 comments on commit 17e198b

Please sign in to comment.