from wifi_lib import conecta
from umqttsimple import MQTTClient
import broker
import dht
from machine import Pin
import time
"""def controle_estufa(topic, msg):
print(f"Mensagem recebida no tópico {topic.decode()}: {msg.decode()}")
if topic.decode() == "estufa/ventilador/status":
if msg.decode() == "true":
relay.on()
print("Ventilador ligado")
elif msg.decode() == "false":
relay.off()
print("Ventilador desligado")
else:
print("Mensagem desconhecida no tópico ventilador.")"""
print("Configurando componentes...")
sensor_dht = dht.DHT22(Pin(15))
relay = Pin(23, Pin.OUT)
print("Tentando conectar ao WI-Fi...")
station = conecta("Wokwi-GUEST", "")
if station.isconnected():
print("Conectado ao Wi-Fi")
else:
print("Falha ao conectar ao Wi-Fi!")
client = MQTTClient(broker.mqtt_client_id,
broker.mqtt_server,
broker.mqtt_port,
broker.mqtt_user,
broker.mqtt_password)
try:
print("Tentando conectar ao HiveMQ...")
client.connect()
print("Conectado ao HiveMQ")
#client.set_callback(controle_estufa) # Define a função de callback
#client.subscribe("estufa/ventilador/status") # Inscreve-se no tópico do ventilador
except OSError as e:
print("Falha ao conectar ao HiveMQ:", e)
while True:
# Verifica mensagens MQTT
#client.check_msg() # Verifica se há novas mensagens recebidas
sensor_dht.measure()
temp = sensor_dht.temperature()
hum = sensor_dht.humidity()
client.publish("estufa/medida/umidade", str(hum))
client.publish("estufa/medida/temperatura", str(temp))
print(f"Temperatura: {temp}°C | Umidade: {hum}%")
time.sleep(2)
client.disconnect()
station.disconnect()