#include "util.h" namespace config { const char *ntp_server = NTP_SERVER; const long utc_offset_in_seconds = UTC_OFFSET_IN_SECONDS; // UTC+1 } #if defined(ESP8266) const char *current_board = "ESP8266"; # if !defined(AMPEL_WIFI) void preinit() { // WiFi would be initialized otherwise (on ESP8266), even if unused. // see https://github.com/esp8266/Arduino/issues/2111#issuecomment-224251391 ESP8266WiFiClass::preinitWiFiOff(); } # endif #elif defined(ESP32) const char *current_board = "ESP32"; #else const char *current_board = "UNKNOWN"; #endif //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 initialize() { timeClient.begin(); } 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); } } void Ampel::showFreeSpace() { Serial.print(F("Free heap space : ")); Serial.print(ESP.getFreeHeap()); Serial.println(F(" bytes.")); Serial.print(F("Max free block size : ")); Serial.print(esp_get_max_free_block_size()); Serial.println(F(" bytes.")); Serial.print(F("Heap fragmentation : ")); Serial.print(esp_get_heap_fragmentation()); Serial.println(F(" %")); } char sensorId[10]; // e.g "ESPxxxxxx\0" char* getSensorId() { uint8_t mac[6]; WiFi.macAddress(mac); // Get last 3 bytes of ESP MAC (worldwide unique) snprintf(sensorId, sizeof(sensorId), "ESP%02x%02x%02x", mac[3], mac[4], mac[5]); return sensorId; } Ampel::Ampel() : board(current_board), sensorId(getSensorId()), max_loop_duration(0) { sensor_console::defineIntCommand("set_time", ntp::setLocalTime, F("1618829570 (Sets time to the given UNIX time)")); sensor_console::defineCommand("free", Ampel::showFreeSpace, F("(Displays available heap space)")); sensor_console::defineCommand("reset", []() { ESP.restart(); }, F("(Restarts the ESP)")); } Ampel ampel;