#include "NTPSynchronisation.h"
|
|
|
|
const char* ntpServer="pool.ntp.org";
|
|
const long gmtOffset_sec=3600;
|
|
const int daylightOffset_sec=3600;
|
|
struct tm timeinfo;
|
|
|
|
/**
|
|
* Try to connect to the Wi-Fi, return true if success, false otherwise.
|
|
* A check of the connection will be made every timeDelay, for delayNumber tentative.
|
|
* If delayNumber is < 0 then the function will wait in indefinitely until the connection is made.
|
|
*/
|
|
bool connectWifi(int timeDelay, int delayNumber) {
|
|
int tentative=0;
|
|
WiFi.begin(wifiSsid, wifiPassword);
|
|
while(WiFi.status()!=WL_CONNECTED && (delayNumber<0 || tentative<delayNumber)) {
|
|
delay(timeDelay);
|
|
Serial.print(".");
|
|
tentative++;
|
|
}
|
|
Serial.println(" CONNECTED");
|
|
|
|
bool connected=WiFi.status()==WL_CONNECTED;
|
|
if(!connected){
|
|
disconnectWifi();
|
|
}
|
|
return connected;
|
|
}
|
|
|
|
void disconnectWifi() {
|
|
WiFi.disconnect(true);
|
|
WiFi.mode(WIFI_OFF);
|
|
}
|
|
|
|
/**
|
|
* Try to synchronize the internal clock with an NTP server.
|
|
* Return true if success, false otherwise.
|
|
* A check of the connection will be made every timeDelay, for maxNTPTentative tentatives.
|
|
*/
|
|
bool synchroniseTimeNTP(bool connectToWifi, bool disconnectWifiAfterSync, int timeDelay, int maxNTPTentative){
|
|
if(connectToWifi){
|
|
connectWifi(500,-1);
|
|
}
|
|
|
|
int tentative=0;
|
|
while(!getLocalTime(&timeinfo) && tentative<maxNTPTentative) {
|
|
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
|
|
delay(timeDelay);
|
|
tentative++;
|
|
}
|
|
|
|
if(disconnectWifiAfterSync){
|
|
disconnectWifi();
|
|
}
|
|
|
|
return getLocalTime(&timeinfo);
|
|
}
|