import network
import ubinascii
import machine
from machine import Pin
import urequests as requests
import time
import random
import socket
from secreto import secrets # Credenciales WiFi
from Wifi_lib import wifi_init, get_html # Funciones auxiliares
from LibDecTarjeta import Board # Detección de placa
# ---------------- CONFIGURACIÓN INICIAL ----------------
led_state = "@@"
random_value = 0
# ---------------- DETECCIÓN DE PLACA ----------------
BOARD_TYPE = Board().type
print("Tarjeta Detectada:", BOARD_TYPE)
# ---------------- INICIALIZAR WIFI ----------------
wifi_init()
# ---------------- CONFIGURAR LED SEGÚN PLACA ----------------
try:
if BOARD_TYPE in [Board.BoardType.PICO_W, Board.BoardType.PICO_2W]:
led = Pin("LED", Pin.OUT)
elif BOARD_TYPE in [Board.BoardType.PICO, Board.BoardType.PICO_2, Board.BoardType.RP2040]:
led = Pin(25, Pin.OUT)
elif BOARD_TYPE == Board.BoardType.ESP8266:
led = Pin(2, Pin.OUT)
elif BOARD_TYPE == Board.BoardType.ESP32:
led = Pin(2, Pin.OUT)
else:
print("Placa desconocida, usando GPIO 2 por defecto.")
led = Pin(2, Pin.OUT)
except Exception as e:
print("Error al configurar el LED:", e)
led = Pin(2, Pin.OUT)
# ---------------- CONFIGURAR SERVIDOR HTTP ----------------
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('Servidor HTTP escuchando en:', addr)
# ---------------- BUCLE PRINCIPAL ----------------
while True:
try:
cl, addr = s.accept()
print('Cliente conectado desde', addr)
request = cl.recv(1024)
request = str(request)
# Procesar solicitud HTTP
led_on = request.find('led=on')
led_off = request.find('led=off')
valor = request.find('value')
print('led_on =', led_on)
print('led_off =', led_off)
print('valor =', valor)
if led_on > -1:
print('LED ENCENDIDO')
led.value(1)
led_state = "ON"
elif led_off > -1:
print('LED APAGADO')
led.value(0)
led_state = "OFF"
if valor > -1:
random_value = random.randint(0, 20)
# Responder con HTML
response = get_html('index.html')
response = response.replace('led_state', led_state)
response = response.replace('random_value', str(random_value))
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()
except OSError as e:
cl.close()
print('Conexión cerrada debido a un error:', e)Loading
pi-pico-w
pi-pico-w