/* ESP32 HTTP IoT Server Example for Wokwi.com
https://wokwi.com/projects/320964045035274834
To test, you need the Wokwi IoT Gateway, as explained here:
https://docs.wokwi.com/guides/esp32-wifi#the-private-gateway
Then start the simulation, and open http://localhost:9080
in another browser tab.
Note that the IoT Gateway requires a Wokwi Club subscription.
To purchase a Wokwi Club subscription, go to https://wokwi.com/club
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define LED_PIN 26 // Pin para el LED
const char* serverAddress = "https://esp32-5d7f8d64c991.herokuapp.com/iot/1";
bool ledState = false;
void toggleLed() {
// Cambia el estado del LED
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
}
void sendHttpRequest() {
HTTPClient http;
http.begin(serverAddress);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println("Response: " + payload);
// Parsear la respuesta JSON
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
// Obtener el valor desde el JSON
int value = doc[0]["valor"];
// Encender o apagar el LED según el valor recibido
digitalWrite(LED_PIN, value == 0);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
void setup(void) {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
}
Serial.println("Connected to WiFi");
// Obtener y establecer el estado inicial del LED al inicio
sendHttpRequest();
}
void loop(void) {
// Puedes realizar otras tareas en el bucle principal si es necesario
// Obtener y actualizar el estado del LED cada 5 segundos (o según sea necesario)
delay(5000);
sendHttpRequest();
}