//Phyton            //Реал
from machine import Pin
import network 
import ujson
from umqtt.simple import MQTTClient

# Настройка пинов для LED
led_red =    Pin(2,  Pin.OUT)  # Красный LED
led_green =  Pin(14, Pin.OUT)  # Зеленый LED
led_yellow = Pin(27, Pin.OUT)  # Жёлтый  LED

# Настройки MQTT
MQTT_CLIENT_ID = "micropython-led-controller" 
MQTT_BROKER    = "test.e-ln.ru" 
MQTT_USER      = "" 
MQTT_PASSWORD  = "" 
MQTT_TOPIC     = "led/color"

# Подключение к WiFi   
print("Connecting to WiFi", end="") 
sta_if = network.WLAN(network.STA_IF) 
sta_if.active(True) 
sta_if.connect('Wokwi-GUEST', '') 
while not sta_if.isconnected(): 
    print(".", end="") 
print(" Connected!") 

# Подключение к MQTT серверу
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD) 
client.connect() 

# Функция для обработки сообщений MQTT
def sub_callback(topic, msg):
    color_name = msg.decode('utf-8')
    print(f"Received color command: {color_name}")
    
    # Логика для управления цветами на LED баре
    led_red.off()
    led_green.off()
    led_yellow.off()
   
    if color_name == "red;" or color_name == "red":
        led_red.on()
    elif color_name == "green;" or color_name == "green":
        led_green.on()
    elif color_name == "yellow;" or color_name == "yellow":
        led_yellow.on()
    else:
        print("Unknown color command")

client.set_callback(sub_callback)
client.subscribe(MQTT_TOPIC)

while True:
    try:
        client.check_msg()  # Проверяем наличие новых сообщений
    except Exception as e:
        print('Error:', e)