import network
import ujson
from machine import Pin
from neopixel import NeoPixel
from time import sleep
from umqtt.simple import MQTTClient

pixels = NeoPixel(Pin(14), 16)
pixels.fill((250,0,0))
pixels.write()
sleep(0.5)
pixels = NeoPixel(Pin(14), 16)
pixels.fill((0,0,250))
pixels.write()
sleep(0.5)

def mqtt_message(topic, msg):
    print("Mensaje Entrante", msg)
    try:
        msg = ujson.loads(msg)
        pixels.fill((msg[0],msg[1],msg[2]))
        pixels.write()
    except Exception as e:
        print("Error:",e)

print("Conectandose al WIFI", end="")
red = network.WLAN(network.STA_IF)
red.active(True)
red.connect("Wokwi-GUEST","")

while not red.isconnected():
    sleep(0.5)
    print("*", end="")

print("Conectado a MQTT...")
client = MQTTClient("wokwi", "broker.hivemq.com")
client.set_callback(mqtt_message)
client.connect()
client.subscribe("wokwi")
print("Conectado Exitosamente")

while True:
    client.wait_msg()