#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <HTTPClient.h>
// ---------- Wi-Fi (red simulada de Wokwi) ----------
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASS = "";
// ---------- Broker publico de HiveMQ ----------
// HiveMQ Cloud Serverless ya no permite clusters nuevos (fin de vida 2026-12-31)
const char* MQTT_HOST = "broker.hivemq.com";
const int MQTT_PORT = 1883;
const char* TOPIC = "casa/luz/control";
// ---------- Google Apps Script (Web App) ----------
const char* SCRIPT_URL = "https://script.google.com/macros/s/AKfycbyPsRRbGExMMZhYNh29SDxrKfVlmJaOAHnsa54Lwh4029zxi0Gv099V2UWa4lLo9CXt/exec";
const char* DEVICE_ID = "ESP32-LUZ-01";
const int LED_PIN = 2;
WiFiClient mqttNet;
PubSubClient mqtt(mqttNet);
String estadoPendiente = ""; // evento por registrar en Sheets
void conectarWiFi() {
Serial.print("Conectando a Wi-Fi");
WiFi.begin(WIFI_SSID, WIFI_PASS, 6);
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println("\nWi-Fi conectado. IP: " + WiFi.localIP().toString());
}
void alRecibir(char* topic, byte* payload, unsigned int length) {
String msg;
for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
msg.trim();
msg.toUpperCase();
Serial.println("Mensaje en " + String(topic) + ": " + msg);
if (msg == "ENCENDER") {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED -> ENCENDIDO");
estadoPendiente = "ENCENDIDO";
} else if (msg == "APAGAR") {
digitalWrite(LED_PIN, LOW);
Serial.println("LED -> APAGADO");
estadoPendiente = "APAGADO";
} else {
Serial.println("Comando no reconocido");
}
}
void conectarMQTT() {
while (!mqtt.connected()) {
Serial.print("Conectando a HiveMQ (" + String(MQTT_HOST) + ")...");
String id = "esp32-luz-" + String(esp_random(), HEX);
if (mqtt.connect(id.c_str())) {
Serial.println(" conectado");
mqtt.subscribe(TOPIC);
Serial.println("Suscrito a " + String(TOPIC));
} else {
Serial.print(" fallo, rc=");
Serial.print(mqtt.state());
Serial.println(" reintento en 3 s");
delay(3000);
}
}
}
// Fecha y hora las pone Apps Script al recibir la peticion
void registrarEnSheets(const String& estado) {
WiFiClientSecure net;
net.setInsecure();
net.setHandshakeTimeout(30); // TLS con Google es lento en la simulacion
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // Apps Script responde con 302
http.setConnectTimeout(20000); // por defecto 5 s, insuficiente en Wokwi
http.setTimeout(20000);
String url = String(SCRIPT_URL) + "?dispositivo=" + DEVICE_ID + "&estado=" + estado;
Serial.println("Enviando a Sheets... heap libre: " + String(ESP.getFreeHeap()));
// Diagnostico: probar el TLS directo para ver el error real
const char* hosts[] = {"script.google.com", "www.google.com", "httpbin.org"};
for (const char* h : hosts) {
WiFiClientSecure t;
t.setInsecure();
t.setHandshakeTimeout(30);
unsigned long t0 = millis();
bool ok = t.connect(h, 443);
char err[120] = "";
if (!ok) t.lastError(err, sizeof(err));
Serial.println(String(h) + ": " + (ok ? "OK" : String("FALLO ") + err) + " (" + String(millis() - t0) + " ms)");
t.stop();
}
http.begin(net, url);
int code = http.GET();
Serial.println("Sheets <- " + estado + " (HTTP " + String(code) + " " + http.errorToString(code) + ")");
http.end();
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW); // 1. LED apagado al iniciar
Serial.println("LED inicial APAGADO");
conectarWiFi(); // 2. Wi-Fi
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(alRecibir);
mqtt.setKeepAlive(60);
conectarMQTT(); // 3. broker y suscripcion
}
void loop() {
if (WiFi.status() != WL_CONNECTED) conectarWiFi();
if (!mqtt.connected()) conectarMQTT();
mqtt.loop(); // 7. control continuo
if (estadoPendiente != "") { // 6. registro fuera del callback MQTT
registrarEnSheets(estadoPendiente);
estadoPendiente = "";
}
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4