/* ESP32 - Time from NTP and change TimeZone Settings */
#include <WiFi.h>
#include <esp_wifi.h>
#include "time.h"
#include "esp_sntp.h"
#include "common.h"
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#define PRJ_NAME "NTP_Time_Change_TZ" // Project Name
#define VERSION "0.0.1" // Project version
// String Sname = String(__FILE__).substring(3, String(__FILE__).lastIndexOf('\\'));
// String SKETCH_NAME = Sname.substring(Sname.lastIndexOf('\\') + 1, Sname.length()); // Project Name
#define SKETCH_NAME String(__FILE__).substring(String(__FILE__).lastIndexOf('/') + 1, String(__FILE__).lastIndexOf('.'))
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// ======================================================================
// setTimezone
void setTimezone(const char *timezone) {
Serial.printf("- Setting Timezone to [%s] -\r\n", timezone);
setenv("TZ", timezone, 1); // Now adjust the TZ. Clock settings are adjusted to show the new local time
tzset();
}
// ======================================================================
// printLocalTime
void printLocalTime() {
if (!getLocalTime(&timeinfo)) {
Serial.println("No time available (yet)");
return;
}
// Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
Serial.println(&timeinfo, "Time is: %F - %T (UTC%z) zone: %Z");
Serial.println();
}
// ======================================================================
// Callback function (get's called when time adjusts via NTP)
void timeavailable(struct timeval *tv) {
FlagNTPstatus = sntp_get_sync_status();
if (FlagNTPstatus) {
printf("------ Got time adjustment from NTP! ------------------\n\r");
// print_NTPservers();
const char *zeroIP = "0.0.0.0";
char BufferIP[42];
for (uint8_t i = 0; i < SNTP_MAX_SERVERS; ++i) {
yield();
ip_addr_t const *ip = esp_sntp_getserver(i);
if ((ipaddr_ntoa_r(ip, BufferIP, sizeof(BufferIP)) != NULL) && (strcmp(BufferIP, zeroIP) != 0)) {
printf("Time server name : %s \r\n", esp_sntp_getservername(i));
printf("Time server ip : %s \r\n", BufferIP);
}
}
} else {
printf("------ [Error] No time available (yet) ----------------\n\r");
}
yield();
PRINT_DASHED_LINES;
}
// ======================================================================
// setup
void setup() {
Serial.begin(115200);
printf("\r\n--------------- Booting ESP ---------------------------\r\n");
printf("Arduino IDE : %d.%d.%d \r\n", ARDUINO / 10000, ARDUINO % 10000 / 100, ARDUINO % 100 / 10 ? ARDUINO % 100 : ARDUINO % 10);
// printf("Arduino IDE : %d.%d.%d \r\n", ARDUINO);
// printf("Arduino IDE : %d \r\n", ARDUINO);
printf("Compiler ver. : %s \r\n", __VERSION__); // gcc version
printf("On Board : %s \r\n", ARDUINO_BOARD);
printf("Firmware name : %s \r\n", PRJ_NAME);
printf("Sketch name : %s \r\n", __FILE__);
printf("Sketch name : %s \r\n", SKETCH_NAME);
printf("Sketch ver. : %s \r\n", VERSION);
printf("Build Date : %s \r\n", (__DATE__ ", " __TIME__)); // compilation date, time
printf("Author : Kernel Panic \r\n");
PRINT_DASHED_LINES;
// First step is to configure WiFi STA and connect in order to get the current time and date.
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password, 6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
// set notification call-back function
sntp_set_time_sync_notification_cb(timeavailable);
/**
NTP server address could be acquired via DHCP,
NOTE: This call should be made BEFORE esp32 acquires IP address via DHCP,
otherwise SNTP option 42 would be rejected by default.
NOTE: configTime() function call if made AFTER DHCP-client run
will OVERRIDE acquired NTP server address
*/
esp_sntp_servermode_dhcp(1); // (optional)
/**
This will set configured ntp servers and constant TimeZone/daylightOffset
should be OK if your time zone does not need to adjust daylightOffset twice a year,
in such a case time adjustment won't be handled automagically.
*/
configTzTime("UTC0", ntpServer1, ntpServer2);
printLocalTime();
printESPinfo();
while (!FlagNTPstatus) {
delay(250);
}
printLocalTime();
PRINT_DASHED_LINES;
}
// ======================================================================
// loop
void loop() {
vTaskDelay(10000);
count = (count + 1) % (sizeof(timeZone) / sizeof(timeZone[0]));
printf("------- New timezone: [%s] -------------\n\r", location[count]);
setTimezone(timeZone[count]);
printLocalTime();
}
// ======================================================================
// print ESP info
void printESPinfo() {
static uint32_t chipId;
for (int i = 0; i < 17; i = i + 8) {
chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
}
//ESP info url: https://github.com/espressif/arduino-esp32/blob/master/cores/esp32/Esp.h
printf("\r\n=========== i n f o r m a t i o n s ====================\r\n");
printf("\r\t--- ESP info --- \r\n");
printf("Arduino core ver. : %s \r\n", GetCoreVersion()); // 2.0.14
printf("ESP-IDF version : %s \r\n", ESP.getSdkVersion()); // v4.4.6-dirty
printf("My Board : %s \r\n", ARDUINO_BOARD);
printf("ESP32 Chip model : %s \r\n", GetChipModel());
printf("This chip has : %d cores \r\n", ESP.getChipCores());
printf("ESP Chip ID : %d \r\n", GetchipId());
printf("ESP Mac Address : %s \r\n", WiFi.macAddress().c_str()); //
printf("ESP CPU Frequency : %d MHz \r\n", ESP.getCpuFreqMHz());
printf("ESP XTAL FREQ : %d MHz \r\n", getXtalFrequencyMhz());
printf("ESP Flash chip Speed : %d MHz \r\n", ESP.getFlashChipSpeed() / 1000000UL);
printf("ESP Flash chip Size : %d MB \r\n", ESP.getFlashChipSize() / 1000000UL);
printf("ESPSPI Flash Mode : %s \r\n", FlashChipMode[ESP.getFlashChipMode()]); // SPI Flash Mode
// Ram informations
printf("\r\t--- Ram informations ---\r\n");
//printf("Total heap size : %s \r\n", formatBytes(ESP.getHeapSize()));
printf("Available Free Ram : %s \r\n", formatBytes(ESP.getFreeHeap()));
printf("Lowest free heap : %s \r\n", formatBytes(ESP.getMinFreeHeap())); //lowest level of free heap since boot
printf("Largest block heap : %s \r\n", formatBytes(ESP.getMaxAllocHeap())); //largest block of heap that can be allocated at once
printf("Available Free PsRam : %s \r\n", formatBytes(ESP.getFreePsram()));
printf("Sketch Size : %s \r\n", formatBytes(ESP.getSketchSize()));
printf("Free Sketch Space : %s \r\n", formatBytes(ESP.getFreeSketchSpace()));
/*
// File System
printf("\r\t--- File System informations ---\r\n");
printf("LittleFS Total : %s \r\n", formatBytes(LittleFS.totalBytes()));
printf("LittleFS Used : %s \r\n", formatBytes(LittleFS.usedBytes()));
printf("LittleFS Free : %s \r\n", formatBytes(LittleFS.totalBytes() - LittleFS.usedBytes()));
*/
printf("\r\t--- WiFi informations ---\r\n");
printf("Connected to SSID : %s \r\n", WiFi.SSID().c_str());
printf("WiFi Channel : %d \r\n", WiFi.channel());
printf("RSSI signal : %d dBm \r\n", WiFi.RSSI());
printf("ESP IP address : %s \r\n", WiFi.localIP().toString().c_str());
printf("Subnet Mask : %s \r\n", WiFi.subnetMask().toString().c_str());
printf("Gateway IP : %s \r\n", WiFi.gatewayIP().toString().c_str());
printf("DNS 1 : %s \r\n", WiFi.dnsIP().toString().c_str());
printf("DNS 2 : %s \r\n", WiFi.dnsIP(1).toString().c_str());
printf("\r=========== END ESP informations ========================\r\n\n");
} //== Close printInfo ===