import network
import ujson
from umqtt.simple import MQTTClient
from machine import Pin
from utime import sleep
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "acaoresposta"
led = Pin(15, Pin.OUT)
ledverde = Pin(14, Pin.OUT)
ledverm = Pin(12, Pin.OUT)
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="")
sleep(0.1)
print(" Connected!")
def mqtt_callback(topic, msg):
print(msg)
mensagem_decodificada = msg.decode('utf-8')
inicio_mudanca = mensagem_decodificada.find("Mudanca Percentual:") + 19
fim_mudanca = mensagem_decodificada.find("%", inicio_mudanca)
mudanca_percentual_str = mensagem_decodificada[inicio_mudanca:fim_mudanca].strip()
try:
mudanca_percentual = float(mudanca_percentual_str)
ledverde.off()
ledverm.off()
if mudanca_percentual > 0:
ledverde.on()
elif mudanca_percentual < 0:
ledverm.on()
except ValueError:
print("Erro ao converter a mudança percentual para float.")
led.on()
sleep(0.5)
led.off()
sleep(0.5)
led.on()
sleep(0.5)
led.off()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
print("Connected!")
client.subscribe(MQTT_TOPIC)
print("Connected and subscribed to {}".format(MQTT_TOPIC))
while True:
client.check_msg()
sleep(1)