#include <WiFi.h>
// Time zone, daylight time intervals
#define MYTZ "CET-1CEST-2,M3.5.0,M10.5.0/3"
// Structure containing a calendar date and time broken down into its components.
// https://cplusplus.com/reference/ctime/tm/
// It's defined inside "time.h", automatically inclued in sketch
struct tm tInfo;
// Get update time (with timeout)
void updatetime(const uint32_t timeout) {
uint32_t start = millis();
do {
time_t now = time(nullptr);
tInfo = *localtime(&now);
delay(1);
} while (millis() - start < timeout && tInfo.tm_year <= (1970 - 1900));
}
// Print to serial updated time (system time keeping is handled from ESP32 internal RTC timer)
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html
void printTime() {
time_t now = time(nullptr);
localtime_r(&now, &tInfo);
static uint8_t old;
if (tInfo.tm_sec != old) {
old = tInfo.tm_sec;
char str[30];
strftime(str, sizeof(str), "%A %d/%m/%Y - %T", &tInfo);
Serial.println(str);
}
}
void strFromEpoch(size_t epoch, char* str, size_t len) {
time_t now = epoch;
struct tm tInfo = *localtime(&now);
//https://cplusplus.com/reference/ctime/strftime/
strftime(str, len, "%A %d/%m/%Y - %T", &tInfo);
}
void setup() {
Serial.begin(115200);
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
// Config timezone and NTP servers
configTzTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");
// At start-up it is necessary to wait a few seconds for synchronization
updatetime(5000);
uint32_t sunset = 1674493983;
uint32_t sunrise = 1674457983;
char myStr[30];
strFromEpoch(sunrise, myStr, sizeof(myStr));
Serial.print("Sunrise: ");
Serial.println(myStr);
strFromEpoch(sunset, myStr, sizeof(myStr));
Serial.print("Sunset: ");
Serial.println(myStr);
}
void loop() {
// Print updated time every seconds
printTime();
// Speed up simulation
delay(10);
}