#include <WiFi.h>
#include <HTTPClient.h>
#include "Arduino_JSON.h"
#include "ESP32Time.h"
RTC_DATA_ATTR int iBootCount = false;
ESP32Time rtc;
void setup() {
HTTPClient http;
String payload;
int httpResponseCode;
// put your setup code here, to run once:
Serial.begin(115200);
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch (wakeup_reason)
{
case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
default :
Serial.printf("Wakeup was not caused by deep sleep: %d\n", wakeup_reason);
break;
}
Serial.printf("Boot count = %d\n", iBootCount);
WiFi.begin("Wokwi-GUEST", "");
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Connected");
if (iBootCount) return;
http.begin("https://ipapi.co/ip");
httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
Serial.println(payload);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
http.begin("https://timeapi.io/api/Time/current/ip?ipAddress="+payload);
httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
Serial.println(payload);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
JSONVar myObject;
JSONVar value;
myObject = JSON.parse(payload);
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}
JSONVar keys = myObject.keys();
for (int i = 0; i < keys.length(); i++) {
value = myObject[keys[i]];
Serial.print(keys[i]);
Serial.print(" = ");
Serial.println(value);
}
Serial.println(myObject["hour"]);
Serial.println(myObject["minute"]);
Serial.println(myObject["seconds"]);
rtc.setTime(myObject["seconds"], myObject["minute"], myObject["hour"], myObject["day"], myObject["month"], myObject["year"]);
iBootCount++;
}
void loop() {
// put your main code here, to run repeatedly:
Serial.printf("%02d:%02d:%02d\n", rtc.getHour(true), rtc.getMinute(), rtc.getSecond());
delay(1000); // this speeds up the simulation
}