"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin, reset
import dht
import ujson
from umqtt.simple import MQTTClient
# --- Configuración ---
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASSWORD = ''
MQTT_SERVER = "broker.hivemq.com"
# ¡Ojo! Asegúrate de que el ClientID en la web de HiveMQ sea DIFERENTE a este
CLIENT_ID = "ESP32_Estacion_Meteorologica"
MQTT_TOPIC = "station/cuisine/meteo1" # Mantenemos tu tópico para que no tengas que cambiar la web
# --- Configuración de Umbrales (Histéresis para el Relé) ---
TEMP_ON = 30.0
TEMP_OFF = 28.0
# --- Inicialización del Sensor y el Relé ---
sensor = dht.DHT22(Pin(15))
rele = Pin(13, Pin.OUT) # El relé está en el GPIO 2 según tu circuito
rele.value(0) # Estado inicial: apagado (OFF)
# --- Conexión WiFi ---
print("Conectando al WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
print(".", end="")
time.sleep(0.1)
print(" ¡Conectado!")
# --- Conexión MQTT ---
print("Conectando al Broker MQTT...")
client = MQTTClient(CLIENT_ID, MQTT_SERVER)
client.connect()
print("¡Conectado al Broker!")
# --- Bucle Principal ---
clima_previo = ""
while True:
try:
# 1. Lectura de datos
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
# --- Lógica de Control Reactivo (Relé con Histéresis) ---
if t >= TEMP_ON and rele.value() == 0:
rele.value(1)
print(">>> ALERTA: Temperatura alta (>=30°C). Relé ENCENDIDO (ON)")
elif t <= TEMP_OFF and rele.value() == 1:
rele.value(0)
print(">>> NORMAL: Temperatura baja (<=28°C). Relé APAGADO (OFF)")
# 2. Formateo (Añadimos el estado del relé al JSON)
estado_rele = "ON" if rele.value() == 1 else "OFF"
mensaje = ujson.dumps({
"temp": t,
"hum": h,
"rele": estado_rele
})
# 3. Envío de datos
if mensaje != clima_previo:
print("¡Nuevos datos detectados!")
print("Publicando en el tópico MQTT {}: {}".format(MQTT_TOPIC, mensaje))
client.publish(MQTT_TOPIC, mensaje)
clima_previo = mensaje
else:
print("Sin cambios en los datos")
except OSError as e:
# En caso de error (WiFi perdido, sensor desconectado...)
print("Error crítico:", e)
print("Reiniciando el ESP32 en 3 segundos...")
time.sleep(3)
reset() # Reiniciamos todo para volver a intentar de forma limpia
# 4. Pausa antes de la siguiente lectura
time.sleep(3)