#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Replace these with your WiFi network credentials.
// Replace this with the AI forecast API URL.
const char* apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=Kuwait%20City,KW&appid=da733717406567ba93a26b28b8e2fe84";
// The GPIO pin for the LED.
const int ledPin = 2;
DynamicJsonDocument doc(1024);
void setup() {
Serial.begin(115200);
// Connect to WiFi.
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Set the LED pin as an output.
pinMode(ledPin, OUTPUT);
}
void loop() {
// Get the current time from the API.
HTTPClient http;
http.begin(apiUrl);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println(payload);
// Parse the JSON response to get the sunset and sunrise times.
DeserializationError error = deserializeJson(doc, payload);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
// Get the sunset and sunrise times.
unsigned long sunset = doc["sys"]["sunset"].as<unsigned long>();
unsigned long sunrise = doc["sys"]["sunrise"].as<unsigned long>();
// Convert the UTC timestamp to a human-readable format.
int timeZoneOffset = doc["timezone"].as<int>();
unsigned long localTimeSunset = sunset + timeZoneOffset ;
unsigned long localTimeSunrise = sunrise + timeZoneOffset ;
String readableSunset = getReadableFormat(localTimeSunset, timeZoneOffset);
String readableSunrise = getReadableFormat(localTimeSunrise, timeZoneOffset);
// Print the sunset and sunrise times in a human-readable format.
Serial.println("Sunset: " + readableSunset);
Serial.println("Sunrise: " + readableSunrise);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
// Wait for 1 second before making the next API call.
delay(1000);
}
// Get the readable format of the timestamp.
String getReadableFormat(unsigned long timestamp, int timeZoneOffset) {
// Convert the timestamp to a human-readable format.
time_t localTime = timestamp + timeZoneOffset*3600 ;
// Get the local time in a human-readable format.
struct tm* tm = localtime(&localTime);
char timeBuffer[80];
strftime(timeBuffer, sizeof(timeBuffer), "%H:%M:%S", tm);
// Return the human-readable format of the timestamp.
return String(timeBuffer);
}