import machine
import time
import network
from umqtt.simple import MQTTClient
# Конфигурация MQTT
MQTT_BROKER = 'test.e-ln.ru'
MQTT_TOPIC = 'goydazov'
# Инициализация пинов для LED бар-графа
led_pins = [machine.Pin(i, machine.Pin.OUT) for i in [2,4,5,18,19,21,22,23,25,26]]
def connect_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='')
time.sleep(0.3)
print('connected')
def on_message(topic, msg):
global led_pins
# Обновить состояние LED бар-графа в соответствии с полученным сообщением
try:
value = int(msg.decode())
for i in range(len(led_pins)):
if i < value:
led_pins[i].value(1)
else:
led_pins[i].value(0)
except Exception as e:
print(f"Error in on_message: {e}")
def main():
try:
connect_wifi()
client = MQTTClient('esp32', MQTT_BROKER)
client.set_callback(on_message)
client.connect()
print('Connected to MQTT broker')
client.subscribe(MQTT_TOPIC)
print(f'Subscribed to {MQTT_TOPIC}')
except Exception as e:
print(f"Error connecting to MQTT: {e}")
return
while True:
try:
client.check_msg()
time.sleep(1)
except Exception as e:
print(f"Error in main loop: {e}")
try:
client.reconnect()
except Exception as e:
print(f"Error reconnecting: {e}")
time.sleep(10) # Ждать перед повторной попыткой
if __name__ == '__main__':
main()