# main.py
import network
import time
import random
import uasyncio as asyncio
from simple import MQTTClient
from led import encender_luces, apagar_luces # Asegúrate de tener este módulo
# --- Configuración Wi-Fi para Wokwi ---
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# --- Configuración MQTT ---
MQTT_BROKER = "broker.emqx.io"
MQTT_PORT = 1883
MQTT_CLIENT_ID = f"pico-luces-{random.randint(0, 1000)}"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_CONTROL_LUCES = "luces"
MQTT_TOPIC_STATUS_LUCES = "luces"
# --- Variables de estado ---
luces_encendidas = False
# --- Cliente MQTT global ---
client = None
# --- Funciones Wi-Fi (asíncronas) ---
async def conectar_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Conectando a Wi-Fi...')
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
for _ in range(20): # Esperar hasta 20 segundos por la conexión
if wlan.isconnected():
print(' Wi-Fi conectado!')
print('Configuración de red:', wlan.ifconfig())
return True
print('.', end='')
await asyncio.sleep(1)
print(' Error al conectar a Wi-Fi.')
return False
else:
print('Wi-Fi ya conectado')
print('Configuración de red:', wlan.ifconfig())
return True
# --- Funciones MQTT (asíncronas) ---
async def conectar_mqtt():
global client
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD)
client.connect()
client.set_callback(mqtt_callback)
client.subscribe(MQTT_TOPIC_CONTROL_LUCES)
print(f"Conectado a MQTT broker: {MQTT_BROKER}")
await publicar_status_luces()
return True
except Exception as e:
print(f"Error al conectar a MQTT: {e}")
return False
async def publicar_mensaje(topic, mensaje):
global client
try:
if client:
client.publish(topic, mensaje.encode('utf-8'))
print(f"Publicado en {topic}: {mensaje}")
else:
print("Error: Cliente MQTT no conectado. No se puede publicar.")
except Exception as e:
print(f"Error al publicar en MQTT: {e}")
async def publicar_status_luces():
global luces_encendidas
payload = f'{{"on": {luces_encendidas}}}'
await publicar_mensaje(MQTT_TOPIC_STATUS_LUCES, payload)
def mqtt_callback(topic, msg):
global luces_encendidas
try:
mensaje = msg.decode('utf-8')
print(f"Mensaje recibido en {topic.decode('utf-8')}: {mensaje}")
if topic == MQTT_TOPIC_CONTROL_LUCES.encode('utf-8'):
if mensaje == "on":
asyncio.create_task(encender_luces())
luces_encendidas = True
asyncio.create_task(publicar_status_luces())
elif mensaje == "off":
asyncio.create_task(apagar_luces())
luces_encendidas = False
asyncio.create_task(publicar_status_luces())
except Exception as e:
print(f"Error en la función de callback MQTT: {e}")
# --- Bucle principal asíncrono ---
async def main():
await conectar_wifi()
if client is None:
await conectar_mqtt()
try:
while True:
if client:
client.check_msg() # Mantener la conexión MQTT y procesar mensajes
await asyncio.sleep(0.1)
except KeyboardInterrupt:
print("Programa terminado.")
finally:
if client:
client.disconnect()
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as e:
print(f"Error al ejecutar el bucle de eventos: {e}")