#include "time_util.h" #include "sensor_console.h" #include "config.h" #include // required for NTP #include "src/lib/NTPClient-master/NTPClient.h" // NTP namespace config { const char *ntp_server = NTP_SERVER; const long utc_offset_in_seconds = UTC_OFFSET_IN_SECONDS; // UTC+1 } //NOTE: ESP32 sometimes couldn't access the NTP server, and every loop would take +1000ms // ifdefs could be used to define functions specific to ESP32, e.g. with configTime namespace ntp { WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, config::ntp_server, config::utc_offset_in_seconds, 60000UL); bool connected_at_least_once = false; void setLocalTime(int32_t unix_seconds); void initialize() { timeClient.begin(); sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F("1618829570 (Sets time to the given UNIX time)")); } void update() { connected_at_least_once |= timeClient.update(); } void getLocalTime(char *timestamp) { timeClient.getFormattedDate(timestamp); } void setLocalTime(int32_t unix_seconds) { char time[23]; timeClient.getFormattedDate(time); Serial.print(F("Current time : ")); Serial.println(time); if (connected_at_least_once) { Serial.println(F("NTP update already happened. Not changing anything.")); return; } Serial.print(F("Setting UNIX time to : ")); Serial.println(unix_seconds); timeClient.setEpochTime(unix_seconds - seconds()); timeClient.getFormattedDate(time); Serial.print(F("Current time : ")); Serial.println(time); } }