import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
#Parametrizar el servidor MQTT.
MQTT_CLIENT_ID = "micropython-weather-demo_cordero"
MQTT_BROKER = "10.201.144.39"
#MQTT_BROKER = "broker.hivemq.com"
MQTT_PORT = 8883 #Puerto por defecto sin SSL
MQTT_USER = ""
MQTT_PASSWORD = ""
#Configuración del sensor DHT22.
sensor = dht.DHT22(Pin(19))
# Configurar el pin GPIO 2 como salida
led = Pin(32, Pin.OUT)
# Tópicos MQTT
MQTT_TOPIC_SUB = "variables/rele"
MQTT_TOPIC_PUB = "variables/temphum"
# Conectar a la red Wi-Fi
def connect_wifi():
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(" Connected!")
# Función de callback para cuando recibimos un mensaje
def mqtt_callback(topic, msg):
#Cuando recibo datos por MQTT los recibo como bytes b'Hola'
topic_str = topic.decode('utf-8')
msg_str = msg.decode('utf-8')
print(f'Recibido mensaje en {topic_str}: {msg_str}')
if msg_str == 'on':
# Encender el LED
led.on()
if msg_str == 'off':
# Apagar el LED
led.off()
# Configuración y conexión al broker MQTT
def connect_mqtt():
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(mqtt_callback)
client.connect()
print('Conectado al broker MQTT')
return client
# Publicar un mensaje
def publish_message(client, message):
client.publish(MQTT_TOPIC_PUB, message)
# Suscribirse a un tema
def subscribe_topic(client):
client.subscribe(MQTT_TOPIC_SUB)
print(f'Suscrito al tema {MQTT_TOPIC_SUB}')
#Bucle Principal.
prev_weather = ""
try:
connect_wifi()
client = connect_mqtt()
subscribe_topic(client)
while True:
client.check_msg() # Verifica si hay mensajes sin bloquear el loop
sensor.measure()
message = ujson.dumps({
"temperatura": sensor.temperature(),
"humedad": sensor.humidity(),
})
if message != prev_weather: #Solo publica cuando el dato a cambiado
publish_message(client, message)
print(message)
prev_weather = message
time.sleep(1)
except OSError as e:
print('Error de conexión', e)