import network
import time
from machine import Pin, SoftI2C
from umqtt.simple import MQTTClient
from dht import DHT22
from i2c_lcd import I2cLcd
# Configuración WiFi y MQTT
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
MQTT_CLIENT_ID = "SensorTemperatura"
MQTT_SERVER = "io.adafruit.com"
MQTT_PORT = 1883
MQTT_USER = "NicolasCaram"
MQTT_PASSWORD = "aio_JgWc573pWZwfiYM4Ruh64AYOd4zL"
MQTT_TOPIC_ACT = "NicolasCaram/feeds/activacion"
MQTT_TOPIC_TEMP = "NicolasCaram/feeds/temperatura"
# Inicializar LED y sensor DHT22
led = Pin(2, Pin.OUT)
sensor = DHT22(Pin(13))
# Configuración del I2C para el LCD
I2C_ADDR = 0x27
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20)
# Conectar a WiFi
def conectar_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Conectando a WiFi...", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(1)
print("\nConectado a WiFi")
# Función de callback para manejar mensajes MQTT
def sub_cb(topic, msg):
global midiendo
print(f"Callback ejecutado: mensaje recibido en {topic.decode('utf-8')}: {msg.decode('utf-8')}")
if topic.decode('utf-8') == MQTT_TOPIC_ACT:
print(f"Mensaje en el tópico {MQTT_TOPIC_ACT}")
if msg.decode('utf-8') == "ON":
midiendo = True
led.on()
elif msg.decode('utf-8') == "OFF":
midiendo = False
led.off()
print("Medición desactivada")
# Función para reconectar a MQTT
def reconectar_mqtt(client):
try:
client.disconnect()
except Exception as e:
print(f"Error al desconectar MQTT: {e}")
while True:
try:
client.connect()
client.subscribe(MQTT_TOPIC_ACT)
return True
except Exception as e:
print(f"Fallo al reconectar MQTT: {e}")
time.sleep(5)
# Conectar a MQTT y verificar estado inicial
def conectar_mqtt():
print("Conectando a MQTT...")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, port=MQTT_PORT, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
print("Conectado a MQTT")
client.subscribe(MQTT_TOPIC_ACT)
print(f"Suscrito al tópico {MQTT_TOPIC_ACT}")
# Verificar estado inicial de activación
client.check_msg()
return client
# Función para mostrar temperatura y humedad en el LCD
def mostrar_temperatura_y_humedad():
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"Temperatura: {temp}°C, Humedad: {hum}%")
# Determinar el mensaje basado en la temperatura
if temp <= 15:
mensaje = "Hace frio! Abrigate!"
elif temp < 25:
mensaje = "Es un lindo dia!"
else:
mensaje = "Hace mucho calor!"
# Mostrar mensaje y temperatura en el LCD
lcd.clear()
lcd.putstr(mensaje)
lcd.move_to(0, 1)
lcd.putstr(f"Temp: {temp}C")
lcd.move_to(0, 2)
lcd.putstr(f"Humedad: {hum}%")
# Publicar en el tópico MQTT
client.publish(MQTT_TOPIC_TEMP, f"Temperatura: {temp}°C, Humedad: {hum}%")
print(f"Publicado temperatura...")
# Conexión y configuración inicial
conectar_wifi()
client = conectar_mqtt()
midiendo = False # Inicializar estado local de medición
# Loop principal para verificar
while True:
try:
print("Verificando mensajes MQTT...")
client.check_msg() # Verificar mensajes MQTT
if midiendo:
mostrar_temperatura_y_humedad()
time.sleep(1)
except OSError as e:
reconectar_mqtt(client)
except Exception as e:
print(f"Error inesperado: {e}")