Código 1: servidor con autenticación y persistencia
server.authenticate() se comprueba al inicio de cada ruta protegida. Si falla,
se responde 401 con la cabecera WWW-Authenticate, y el navegador muestra su
propio diálogo de usuario y contraseña.
El estado se guarda con Preferences solo cuando cambia, y la página consulta
/estado cada 3 segundos para reflejar cambios hechos desde otro dispositivo.
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include "secrets.h"
#define PIN_LED1 2
#define PIN_LED2 4
WebServer server(80);
Preferences prefs;
bool estado1 = false;
bool estado2 = false;
void aplicar() {
digitalWrite(PIN_LED1, estado1 ? HIGH : LOW);
digitalWrite(PIN_LED2, estado2 ? HIGH : LOW);
}
void guardar() {
prefs.putBool("led1", estado1);
prefs.putBool("led2", estado2);
}
bool autorizado() {
if (server.authenticate(WEB_USER, WEB_PASS)) return true;
server.requestAuthentication();
return false;
}
void enviarJSON() {
char json[120];
snprintf(json, sizeof(json),
"{\"led1\":%s,\"led2\":%s,\"rssi\":%d}",
estado1 ? "true" : "false",
estado2 ? "true" : "false",
WiFi.RSSI());
server.send(200, "application/json", json);
}
const char PAGINA[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="es"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Control · Torelec</title>
<style>
body{font-family:system-ui,sans-serif;background:#0f172a;color:#e2e8f0;margin:0;
display:flex;min-height:100vh;align-items:center;justify-content:center}
.panel{background:#111c33;border:1px solid #1e293b;border-radius:18px;padding:2rem;width:min(420px,92vw)}
h1{font-size:1.1rem;letter-spacing:.05em;text-transform:uppercase;color:#94a3b8;margin:0 0 1.5rem}
.fila{display:flex;align-items:center;justify-content:space-between;padding:.9rem 0;
border-bottom:1px solid #1e293b}
.fila:last-of-type{border-bottom:none}
.nombre{font-weight:600}
.estado{font-family:ui-monospace,monospace;font-size:.8rem;padding:.2rem .6rem;
border-radius:99px;background:#1e293b;color:#94a3b8}
.on{background:#065f46;color:#a7f3d0}
button{background:#0284c7;border:none;color:#fff;padding:.55rem 1rem;border-radius:8px;
cursor:pointer;font-size:.85rem;font-weight:600}
button:hover{background:#0369a1}
</style></head>
<body>
<div class="panel">
<h1>Control de canales</h1>
<div class="fila">
<span class="nombre">LED 1 · GPIO 2</span>
<span class="estado" id="e1">--</span>
<button onclick="accion(1,'toggle')">Cambiar</button>
</div>
<div class="fila">
<span class="nombre">LED 2 · GPIO 4</span>
<span class="estado" id="e2">--</span>
<button onclick="accion(2,'toggle')">Cambiar</button>
</div>
<div class="fila">
<button onclick="accion(0,'off')">Apagar todo</button>
<button onclick="accion(0,'on')">Encender todo</button>
</div>
</div>
<script>
async function refrescar(){
const r = await fetch('/estado');
const d = await r.json();
const e1=document.getElementById('e1'), e2=document.getElementById('e2');
e1.textContent = d.led1 ? 'ENCENDIDO':'APAGADO';
e2.textContent = d.led2 ? 'ENCENDIDO':'APAGADO';
e1.className = 'estado' + (d.led1 ? ' on':'');
e2.className = 'estado' + (d.led2 ? ' on':'');
}
async function accion(canal, modo){
await fetch(`/accion?canal=${canal}&modo=${modo}`);
refrescar();
}
refrescar();
setInterval(refrescar, 3000);
</script>
</body></html>
)rawliteral";
void setup() {
Serial.begin(115200);
pinMode(PIN_LED1, OUTPUT);
pinMode(PIN_LED2, OUTPUT);
prefs.begin("leds", false);
estado1 = prefs.getBool("led1", false);
estado2 = prefs.getBool("led2", false);
aplicar();
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { delay(400); Serial.print("."); }
Serial.printf("\nIP: http://%s\n", WiFi.localIP().toString().c_str());
server.on("/", []() {
if (!autorizado()) return;
server.send_P(200, "text/html; charset=utf-8", PAGINA);
});
server.on("/estado", []() {
if (!autorizado()) return;
enviarJSON();
});
server.on("/accion", []() {
if (!autorizado()) return;
int canal = server.arg("canal").toInt();
String modo = server.arg("modo");
auto nuevo = [](bool actual, const String &m) {
if (m == "on") return true;
if (m == "off") return false;
return !actual;
};
if (canal == 1) estado1 = nuevo(estado1, modo);
else if (canal == 2) estado2 = nuevo(estado2, modo);
else { estado1 = nuevo(estado1, modo); estado2 = nuevo(estado2, modo); }
aplicar();
guardar();
enviarJSON();
});
server.onNotFound([]() { server.send(404, "text/plain", "404"); });
server.begin();
}
void loop() {
server.handleClient();
}
Código 2: credenciales y contraseña del panel
Cambia la contraseña del panel antes de cargar el firmware. La autenticación básica envía
las credenciales en base64, que no es cifrado: úsala solo dentro de la red local y con una
contraseña distinta a la del WiFi.
#pragma once
#define WIFI_SSID "NOMBRE_DE_TU_RED"
#define WIFI_PASS "TU_CONTRASENA"
#define WEB_USER "admin"
#define WEB_PASS "cambia_esta_clave"