import socket
import network
import time
from machine import Pin
from secreto import secrets # <--- Importar credenciales
# -------------------------
# CONFIGURAR LEDS
# -------------------------
led1 = Pin(14, Pin.OUT) # LED 1
led2 = Pin(15, Pin.OUT) # LED 2
# -------------------------
# CONFIGURAR STATION
# -------------------------
ssid = secrets["ssid"]
password = secrets["password"]
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
print("Conectando a la red WiFi:", ssid)
timeout = 0
while not wlan.isconnected():
time.sleep(1)
timeout += 1
print("Intento:", timeout)
if timeout > 15:
print("No se pudo conectar a la red.")
break
print("Conexión exitosa")
print("Datos de red:", wlan.ifconfig())
# -------------------------
# CONTADOR GLOBAL
# -------------------------
contador = 0
# -------------------------
# PÁGINA HTML
# -------------------------
def web_page(cont, l1, l2):
estado_led1 = "ENCENDIDO" if l1 else "APAGADO"
estado_led2 = "ENCENDIDO" if l2 else "APAGADO"
cont2=cont/2
return f"""<!DOCTYPE html>
<html>
<head>
<title>Pico W - ESP32</title>
<meta http-equiv="refresh" content="1">
</head>
<body>
<h1>Servidor Web con Control de LEDs</h1>
<h2>Contador: {cont} {cont2}</h2>
<h3>LED en GP14: {estado_led1}</h3>
<a href="/led1_on"><button>Encender LED 14</button></a>
<a href="/led1_off"><button>Apagar LED 14</button></a>
<h3>LED en GP15: {estado_led2}</h3>
<a href="/led2_on"><button>Encender LED 15</button></a>
<a href="/led2_off"><button>Apagar LED 15</button></a>
<br><br>
<p>German Jesus Pereira Muñoz PhD.</p>
</body>
</html>
"""
# -------------------------
# SERVIDOR WEB
# -------------------------
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
print("Servidor web listo en:", wlan.ifconfig()[0])
while True:
try:
conn, addr = s.accept()
print("Conexión desde:", addr)
request = conn.recv(1024).decode()
print("Solicitud:", request)
# Comandos para LEDs
if "/led1_on" in request:
led1.value(1)
if "/led1_off" in request:
led1.value(0)
if "/led2_on" in request:
led2.value(1)
if "/led2_off" in request:
led2.value(0)
# Incrementar contador
contador += 1
# Generar HTML actualizado
html = web_page(contador, led1.value(), led2.value())
# Enviar cabeceras y contenido
conn.send("HTTP/1.1 200 OK\r\n")
conn.send("Content-Type: text/html\r\n")
conn.send("Connection: close\r\n\r\n")
conn.sendall(html)
conn.close()
except Exception as e:
print("Error:", e)