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

count = 16
neopixel_ring = NeoPixel(Pin(26, Pin.OUT), count)


sta_if = None

def get_neopixel_data(topic, data_bytes):
    try:
        topic = topic.decode("utf-8")
        color = data_bytes.decode("utf-8")
        if topic == "color":
            red, green, blue = [int(part) for part in color.split("/")]
            neopixel_ring.fill((red,green,blue))
            neopixel_ring.write()
    except Exception as e:
        print(e)

def connect_to_wifi(SSID, password):
    global sta_if
    print("Connecting to WiFi", end="")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect(SSID, password)
    while not sta_if.isconnected():
        print(".", end="")
        sleep(0.1)
    print(" Connected!")


connect_to_wifi('Wokwi-GUEST', '')
print("Connecting to MQTT server... ", end="")
client = MQTTClient(
    "umqtt_client_xakep", 
    "paperno.cloud.shiftr.io", 
    user="paperno", 
    password="test"
    )
client.connect()

print("Connected!")
client.set_callback(get_neopixel_data)
client.subscribe('color')
while True:
  client.wait_msg()