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

# Настройки MQTT
MQTT_CLIENT_ID = "esp-neopixel"
MQTT_BROKER = "test.e-ln.ru"
MQTT_PORT = 1883
MQTT_TOPIC_SUB = "led_ring"  # Обычная строка для топика

# Настройки NeoPixel
NUM_PIXELS = 16  
DATA_PIN = 2     
np = neopixel.NeoPixel(Pin(DATA_PIN), NUM_PIXELS)

# Подключение к Wi-Fi
def connect_wifi(ssid, password):
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect(ssid, password)
    while not sta_if.isconnected():
        time.sleep(0.1)
    print("Connected to Wi-Fi:", sta_if.ifconfig())

# Управление светодиодами
def set_leds(color, count):
    rgb = {
        "red": (255, 0, 0),
        "green": (0, 255, 0),
        "blue": (0, 0, 255)
    }
    led_color = rgb.get(color.lower(), (0, 0, 0))
    for i in range(NUM_PIXELS):
        np[i] = led_color if i < count else (0, 0, 0)
    np.write()

# Обработчик сообщений MQTT
def sub_cb(topic, msg):
    print(f"Received message: {msg} on topic: {topic.decode()}")
    try:
        data = ujson.loads(msg)
        color = data.get("color", "off")
        count = data.get("count", 1)
        if 1 <= count <= NUM_PIXELS:
            set_leds(color, count)
        else:
            print("Invalid count value")
    except Exception as e:
        print("Error handling message:", e)

# Подключение к MQTT
def connect_mqtt():
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, MQTT_PORT)
    client.set_callback(sub_cb)
    try:
        client.connect()
        client.subscribe(MQTT_TOPIC_SUB.encode())  # Преобразуем топик в байты
        print("Connected to MQTT and subscribed to topic:", MQTT_TOPIC_SUB)
    except Exception as e:
        print("MQTT connection error:", e)
        time.sleep(1)
    return client

try:
    connect_wifi('Wokwi-GUEST', '')
    client = connect_mqtt()
    while True:
        try:
            client.check_msg()
        except Exception as e:
            print("Error checking messages:", e)
            time.sleep(1)
            client = connect_mqtt()  # Переподключение при ошибке
except Exception as e:
    print("General error:", e)
finally:
    client.disconnect()
    print("Disconnected from MQTT broker.")