#pragma once #include #include #include "html.h" #include "dht22.h" #include "ota.h" WebServer server(80); void setupServidor() { // 1. Dashboard principal con gráficos y OTA (especificando charset=utf-8) server.on("/", HTTP_GET, []() { server.send(200, "text/html; charset=utf-8", htmlDashboard); }); // 2. Endpoint JSON para actualizar los gráficos en tiempo real server.on("/datos", HTTP_GET, []() { String json = "{\"temp\":" + String(temperaturaFloat, 2) + ",\"hum\":" + String(humedadFloat, 2) + ",\"temperatura\":" + String(temperaturaFloat, 2) + ",\"humedad\":" + String(humedadFloat, 2) + "}"; server.send(200, "application/json; charset=utf-8", json); }); // 3. Endpoint de hostname server.on("/wifi-name", HTTP_GET, []() { server.send(200, "text/plain; charset=utf-8", WiFi.getHostname()); }); // 4. Reset del ESP32 server.on("/reset", HTTP_POST, []() { server.send(200, "text/plain; charset=utf-8", "Reiniciando ESP32..."); delay(500); ESP.restart(); }); // 5. Reset del portal cautivo server.on("/resetportal", HTTP_POST, []() { server.send(200, "text/plain; charset=utf-8", "Reiniciando portal..."); digitalWrite(pinDos, HIGH); mostrarOled("", "Reseteando WiFi...", "", ""); delay(500); wm.resetSettings(); ESP.restart(); }); // 6. Activar actualización remota por URL server.on("/update-url", HTTP_POST, []() { server.send(200, "text/plain; charset=utf-8", "Iniciando descarga remota..."); pinMode(pinDos, OUTPUT); digitalWrite(pinDos, HIGH); // Encender LED pin GPIO 2 al activar OTA remota pendienteActualizarURL = true; // Se procesará en loopOTA() }); // 7. Actualización OTA DIRECTA (.bin) desde el navegador server.on("/update", HTTP_POST, []() { server.sendHeader("Connection", "close"); server.send(200, "text/plain; charset=utf-8", (Update.hasError()) ? "FAIL" : "OK"); if (!Update.hasError()) { pinMode(pinDos, OUTPUT); digitalWrite(pinDos, HIGH); // Mantener LED GPIO 2 encendido delay(300); ESP.restart(); } }, []() { HTTPUpload& upload = server.upload(); if (upload.status == UPLOAD_FILE_START) { Serial.printf("Iniciando subida OTA: %s\n", upload.filename.c_str()); pinMode(pinDos, OUTPUT); digitalWrite(pinDos, HIGH); // Encender LED GPIO 2 durante OTA mostrarOled("OTA en curso...", "Subiendo .bin", "Espere...", ""); if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_WRITE) { if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { Update.printError(Serial); } } else if (upload.status == UPLOAD_FILE_END) { if (Update.end(true)) { Serial.printf("OTA finalizada correctamente: %u bytes\n", upload.totalSize); pinMode(pinDos, OUTPUT); digitalWrite(pinDos, HIGH); // Mantener LED GPIO 2 encendido mostrarOled("OTA Completa", "Reiniciando...", "", ""); } else { Update.printError(Serial); mostrarOled("Error OTA", "Fallo al grabar", "", ""); } } }); server.begin(); Serial.println("Servidor Web (Dashboard y OTA) iniciado en el puerto 80."); } void loopServidor() { server.handleClient(); }