import network
import time
import ujson
from machine import Pin, PWM
from led import *
from ventilador import *
from mqtthandler import *
from alarma import *

# Configuración WiFi
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# Configuración del dispositivo
DEVICE_ID = "ESP_32"

# Configuración MQTT
MQTT_BROKER = "29a24c5ee207444292a28a415803a32e.s1.eu.hivemq.cloud"
MQTT_USER = "domotica"
MQTT_PASSWORD = "Dom_esp32"
MQTT_SSL_PARAMS = {'server_hostname': MQTT_BROKER}

# Crear el objeto MQTTHandler
mqtt_handler = MQTTHandler(DEVICE_ID, MQTT_BROKER, MQTT_USER, MQTT_PASSWORD, ssl=True, ssl_params=MQTT_SSL_PARAMS)

# Inicializar LEDs
LUZ_1 = LED(13)
LUZ_2 = LED(12)
LUZ_3 = LED(14)

LUZ_1.off()
LUZ_2.off()
LUZ_3.off()

#inicializar ventilador
vent = Ventilador(27, freq=1)
vent.off()

#Inicializar Alarma
alarma = Alarma(25, 26, 18, mqtt_handler=mqtt_handler)

# Callback para manejar mensajes MQTT
def did_receive_callback(topic, message):
    print(f"Data Received! Topic: {topic}, Message: {message.decode()}")
    topic = topic.decode()
    message = message.decode()
    # Controlar LEDs y ventilador por tópico
    if topic.endswith("control"):
        if message == "lamp/1/on":
            LUZ_1.on()
        elif message == "lamp/1/off":
            LUZ_1.off()
        elif message == "lamp/2/on":
            LUZ_2.on()
        elif message == "lamp/2/off":
            LUZ_2.off()
        elif message == "lamp/3/on":
            LUZ_3.on()
        elif message == "lamp/3/off":
            LUZ_3.off()
        elif message == "lamp/on":
            LUZ_1.on()
            LUZ_2.on()
            LUZ_3.on()
        elif message == "lamp/off":
            LUZ_1.off()
            LUZ_2.off()
            LUZ_3.off()
        elif message == "vent/on":
            vent.on()
        elif message == "vent/off":
            vent.off()
        elif message == "alarm/on":
            alarma.encender()
        elif message == "alarm/off":
            alarma.apagar()
    # Controlar brillo de los LEDs
    elif topic.endswith("LED1"):
        LUZ_1.brillo(float(message))
    elif topic.endswith("LED2"):
        LUZ_2.brillo(float(message))
    elif topic.endswith("LED3"):
        LUZ_3.brillo(float(message))

    #Controlar la velocidad del ventilador
    elif topic.endswith("VENT"):
        vent.speed(float(message))

# Conectar a WiFi
def connect_wifi(ssid, password):
    wifi_client = network.WLAN(network.STA_IF)
    wifi_client.active(True)
    print("Connecting device to WiFi...")
    wifi_client.connect(ssid, password)
    while not wifi_client.isconnected():
        print("Connecting...")
        time.sleep(0.5)
    print("WiFi Connected!")
    print(wifi_client.ifconfig())

# Conectar a WiFi
connect_wifi(WIFI_SSID, WIFI_PASSWORD)

# Conectar a MQTT
mqtt_handler.connect(did_receive_callback)

# Suscribir a los tópicos necesarios
mqtt_handler.subscribe(f'dom/{DEVICE_ID}/control')
mqtt_handler.subscribe(f'dom/brillo/{DEVICE_ID}/LED1')
mqtt_handler.subscribe(f'dom/brillo/{DEVICE_ID}/LED2')
mqtt_handler.subscribe(f'dom/brillo/{DEVICE_ID}/LED3')
mqtt_handler.subscribe(f'dom/speed/{DEVICE_ID}/VENT')

# Publicar 

# Bucle principal
while True:
    try:
        mqtt_handler.check_messages()
        time.sleep(0.5)
    except KeyboardInterrupt:
        print("System interrupted!")
        break

    alarma.verificar_alarma()
    time.sleep(0.5)  # Espera medio segundo antes de verificar de nuevo