import network
import time
from machine import Pin
from umqtt.simple import MQTTClient

# Configuration réseau
ssid = 'Wokwi-GUEST'
password = ''

# Adresse du broker MQTT
mqtt_server = 'broker.emqx.io'

# Liste des pins utilisés
pins = [2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 25, 26, 27]
leds = [Pin(pin, Pin.OUT) for pin in pins]

# Fonction de connexion au WiFi
def connect_wifi():
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.isconnected():
        print('Connecting to network...')
        sta_if.active(True)
        sta_if.connect(ssid, password)
        while not sta_if.isconnected():
            pass
    print('Network connected:', sta_if.ifconfig())

# Fonction de callback pour les messages MQTT
def sub_cb(topic, msg):
    print((topic, msg))
    topic_str = topic.decode('utf-8')
    msg_str = msg.decode('utf-8')
    for i, pin in enumerate(pins):
        pin_topic = f'esp32/pin{pin}'
        if topic_str == pin_topic:
            if msg_str == 'on':
                leds[i].value(1)
            elif msg_str == 'off':
                leds[i].value(0)

# Fonction de connexion au broker MQTT
def connect_mqtt():
    client = MQTTClient('', mqtt_server)
    client.set_callback(sub_cb)
    client.connect()
    print('Connected to %s MQTT broker' % mqtt_server)
    for pin in pins:
        client.subscribe(f'esp32/pin{pin}')
    return client

# Fonction principale
def main():
    connect_wifi()
    client = connect_mqtt()
    
    try:
        while True:
            client.check_msg()
            time.sleep(0.01)
    except KeyboardInterrupt:
        print('Disconnecting from MQTT broker...')
        client.disconnect()

if __name__ == '__main__':
    main()