import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "lazaro_esp2"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
alerta_topico1 = "UMIDADE1"
alerta_topico2 = "UMIDADE2"
buzzer = Pin(5, Pin.OUT)
led = Pin(4, Pin.OUT)
def on_message(topic, msg):
print(f"Mensagem recebida: {msg.decode()} no tópico: {topic.decode()}")
if msg.decode() == "UMIDADE1 BAIXA" or msg.decode() == "UMIDADE2 BAIXA":
buzzer.value(1)
while True:
led.value(1)
time.sleep(1)
led.value(0)
time.sleep(1)
client.check_msg()
if led.value() == 0:
break
elif msg.decode() == "UMIDADE1 NORMAL" or msg.decode() == "UMIDADE2 NORMAL":
buzzer.value(0)
led.value(0)
print("Conectando ao 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.1)
print(" Conectado!")
print("Conectando ao servidor MQTT... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(on_message)
try:
client.connect()
print("Conectado!")
client.subscribe(alerta_topico1)
client.subscribe(alerta_topico2)
except Exception as e:
print("Falha ao conectar ao MQTT:", e)
sys.exit()
while True:
try:
client.check_msg()
except OSError as e:
print("Erro ao receber mensagem MQTT:", e)
client.connect()
client.subscribe(alerta_topico1)
client.subscribe(alerta_topico2)