import machine
from machine import I2C, Pin
import network
from ds1307 import DS1307
import time
import dht
from umqtt.simple import MQTTClient
#Defino los pines del DS1307
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))
clockObject = DS1307(i2c)
MQTT_CLIENT = "Ventana"
MQTT_BROKER = "io.adafruit.com"
MQTT_USUARIO = "F4152"
MQTT_KEY = "aio_Xccr84hDLf88HKHmgQ9ef8DmtmKI"
topic_prueba = "F4152/feeds/testing"
topic_tempe = "F4152/feeds/tempe"
topic_tempemax = "F4152/feeds/tempemax"
topic_tempemin = "F4152/feeds/tempemin"
topic_hume = "F4152/feeds/hume"
topic_humemax = "F4152/feeds/humemax"
topic_humemin = "F4152/feeds/humemin"
topic_hora = "F4152/feeds/hora"
topic_horamax = "F4152/feeds/horamax"
topic_horamin = "F4152/feeds/horamin"
port=1883
#Defino los pines del DHT22
dht_pin=Pin(12)
test_pin=Pin(27, Pin.OUT)
sensor=dht.DHT22(dht_pin)
prueba=0
temp=0
tempmax=16
tempmin=8
hume=0
humemax=70
humemin=10
hora=10
horamax=12
horamin=9
# Para evitar publicar valores sin cambios
temp_prev = None
hume_prev = None
hora_prev = None
#Defino los pines del a4988
paso=Pin(2, Pin.OUT)
dire=Pin(15, Pin.OUT)
print("Conectando a 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("Conectado")
print (sta_if.ifconfig())
#Funcion para mover el motorcito
def mover_pasos(pasos,direccion):
dire.value(direccion)
for i in range (pasos):
paso.value(1)
time.sleep_ms(5)
paso.value(0)
time.sleep_ms(5)
def funcion_callback(topic, msg):
"""Interpreta los mensajes que llegan desde Adafruit.
testing -> 0 = automático | 1 = prueba | 2 = manual‑cerrar | 3 = manual‑abrir
El resto de los feeds actualiza umbrales o (en modo prueba) valores simulados."""
global prueba, temp, tempmax, tempmin, hume, humemax, humemin, hora, horamax, horamin
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print(f"Mensaje en tópico {topicrec}: {dato}")
# MODO
if topicrec == topic_prueba:
# 0‑auto | 1‑prueba | 2‑manual‑cerrar | 3‑manual‑abrir
prueba = int(dato)
return
# UMBRALES
if topicrec == topic_tempemax: tempmax = float(dato)
elif topicrec == topic_tempemin: tempmin = float(dato)
elif topicrec == topic_humemax: humemax = float(dato)
elif topicrec == topic_humemin: humemin = float(dato)
elif topicrec == topic_horamax: horamax = float(dato)
elif topicrec == topic_horamin: horamin = float(dato)
# VALORES SIMULADOS
elif prueba == 1:
if topicrec == topic_tempe: temp = float(dato)
elif topicrec == topic_hume: hume = float(dato)
elif topicrec == topic_hora: hora = float(dato)
#Estado inicial de la ventana
ventana_abierta=False
#Conexión al broker MQTT
try:
conexionMQTT = MQTTClient(MQTT_CLIENT,MQTT_BROKER,user=MQTT_USUARIO,password=MQTT_KEY,port=int(port))
conexionMQTT.set_callback(funcion_callback) #Funcion Callback para recibir del broker mensajes
conexionMQTT.connect() #Hacemos la conexión.
conexionMQTT.subscribe (topic_prueba) #Suscripcion al topico
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_tempe)
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_tempemax)
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_tempemin)
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_hume)
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_humemax)
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_humemin)
conexionMQTT.check_msg()
time.sleep_ms(500)
conexionMQTT.subscribe (topic_hora)
time.sleep_ms(500)
conexionMQTT.subscribe (topic_horamax)
time.sleep_ms(500)
conexionMQTT.subscribe (topic_horamin)
print("Conectado con Broker MQTT")
except OSError as e:
print("Fallo la conexion al Broker, reiniciando...")
time.sleep(5)
machine.reset()
#Programa principal
while True:
try:
conexionMQTT.check_msg()
if prueba == 0:
sensor.measure()
temp = sensor.temperature()
hume = sensor.humidity()
fecha = clockObject.datetime()
hora = fecha[4]
if temp_prev is None or abs(temp - temp_prev) >= 0.5:
conexionMQTT.publish(topic_tempe, str(temp))
temp_prev = temp
if hume_prev is None or abs(hume - hume_prev) >= 0.5:
conexionMQTT.publish(topic_hume, str(hume))
hume_prev = hume
if hora_prev is None or hora != hora_prev:
conexionMQTT.publish(topic_hora, str(hora))
hora_prev = hora
print("\n------------------------")
print("Hora:", hora)
print("Temperatura:", temp, "°C")
print("Humedad:", hume, "%")
print("Estado de la ventana:", "Abierta" if ventana_abierta else "Cerrada")
#Para chequear que los valores umbrales se estan modificando:
print("\n--- Valores umbrales configurados ---")
print(f" Temperatura: {tempmin} °C (min) / {tempmax} °C (max)")
print(f" Humedad: {humemin} % (min) / {humemax} % (max)")
print(f" Hora: {horamin} hs (min) / {horamax} hs (max)")
print("------------------------")
test_pin.value(prueba)
if prueba == 0:
# Validación de los umbrales
if (tempmin < tempmax) and (humemin < humemax) and (horamin < horamax):
abrir = (temp >= tempmax) or (hume >= humemax) or (hora >= horamax)
cerrar = (temp <= tempmin) or (hume <= humemin) or (hora <= horamin)
if abrir and not ventana_abierta:
print("Abriendo ventana (condición automática).")
mover_pasos(200, 1)
ventana_abierta = True
elif cerrar and ventana_abierta:
print("Cerrando ventana (condición automática).")
mover_pasos(200, 0)
ventana_abierta = False
else:
print("Umbrales inválidos: revisar configuración.")
print(f" tempmin: {tempmin}, tempmax: {tempmax}")
print(f" humemin: {humemin}, humemax: {humemax}")
print(f" horamin: {horamin}, horamax: {horamax}")
elif prueba == 2 and ventana_abierta:
print("Cierre manual solicitado.")
mover_pasos(200, 0)
ventana_abierta = False
elif prueba == 3 and not ventana_abierta:
print("Apertura manual solicitada.")
mover_pasos(200, 1)
ventana_abierta = True
time.sleep(2)
except Exception as e:
print("Error:", e)
time.sleep(2)