import socket
import network
import time
from machine import Pin
# -------------------------
# CONFIGURAR LEDS
# -------------------------
led1 = Pin(14, Pin.OUT) # LED 1
led2 = Pin(15, Pin.OUT) # LED 2
# -------------------------
# ACCESS POINT
# -------------------------
ssid = 'ESP32_RPI_PICO_AP'
password = '12345678'
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, password=password)
ap.active(True)
for i in range(10):
if ap.active():
break
time.sleep(1)
print("Conexión exitosa")
print(ap.ifconfig())
# ---------------------------------------
# CONTADOR GLOBAL
# ---------------------------------------
contador = 0
# ---------------------------------------
# GENERAR PAGINA HTML
# ---------------------------------------
def web_page(cont, l1, l2):
estado_led1 = "ENCENDIDO" if l1 else "APAGADO"
estado_led2 = "ENCENDIDO" if l2 else "APAGADO"
return f"""<!DOCTYPE html>
<html>
<head>
<title>Pico W - ESP32</title>
<meta http-equiv="refresh" content="1"> <!-- Auto refresco cada 1 segundo -->
</head>
<body>
<h1>Servidor Web con Control de LEDs</h1>
<h2>Contador: {cont}</h2>
<h3>LED en GP14 está: {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 está: {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 operativo en el puerto 80...")
while True:
try:
conn, addr = s.accept()
print("Conexión desde:", addr)
request = conn.recv(1024).decode()
print("Solicitud:", request)
# Analizar comandos
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 respuesta
html = web_page(contador, led1.value(), led2.value())
# Cabeceras HTTP
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)