#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
const char* ssid = "Wokwi-GUEST";
const char* pass = "";
const char* server = "http://api.weatherapi.com/v1/current.json?key=454cba2202f24b40a82235351213110&q=jakarta&aqi=no";
unsigned long waktuTerakhir = 0;
unsigned long timerDelay = 5000;
String name;
String region;
String country;
void setup() {
// ESP 32 Wifi Setup
String jsonBuffer;
Serial.begin(115200);
WiFi.begin(ssid, pass);
while(WiFi.status() != WL_CONNECTED){
delay(100);
Serial.println(".");
}
Serial.println("WiFi Connected");
Serial.println(WiFi.localIP());
}
void loop() {
// Sending POST Request every 10 minutes
if((millis() - waktuTerakhir) > timerDelay){
// Check WiFi Status
if(WiFi.status() == WL_CONNECTED){
String sensorRead = httpGETRequest(server);
Serial.println(sensorRead);
JSONVar parsedObject = JSON.parse(sensorRead);
// Checking the Type of the Object
if(JSON.typeof(parsedObject) == "undefined"){
Serial.println("Parsing input has failed!");
return;
}
// Accessing nested JSON Object
if(parsedObject.hasOwnProperty("location")){
name = String(parsedObject["location"]["name"]);
region = String(parsedObject["location"]["region"]);
country = String(parsedObject["location"]["country"]);
Serial.print("City Name : ");
Serial.println(name);
Serial.print("Region : ");
Serial.println(region);
Serial.print("Country : ");
Serial.println(country);
}
else{
Serial.println("Missing Keys.");
}
}
else {
Serial.println("WiFi has disconnected");
}
waktuTerakhir = millis();
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Domain Name
http.begin(client, serverName);
// POST Request
int httpResponseCode = http.GET();
String payload = "{}";
if(httpResponseCode > 0){
Serial.print("Response Status : ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code : ");
Serial.println(httpResponseCode);
}
// Free Resources
http.end();
return payload;
}