import machine
import time
import dht
import micropython
import network
from umqtt.simple import MQTTClient
from machine import Pin, PWM
ssid='Wokwi-GUEST'
wifipassword=''
mqtt_server='io.adafruit.com'
port=1883
user='JoelRodriguez'
password='aio_umTm94lpYJOU5aPM2KbcpxrzY2nt'
client_id='Proyecto'
topic_ALARMA='JoelRodriguez/feeds/ALARMA'
topic_tema3='JoelRodriguez/feeds/tema3'
LedRojo=Pin(18, Pin.OUT)
sta_if=network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, wifipassword)
print("Conectandose al wifi")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("Conexion realizada con exito")
print(sta_if.ifconfig())
LedRojo.value(1)
ALARMA_ACTIVA=False
def DetectaPublish(topic, msg):
global ALARMA_ACTIVA, LedRojo
codigo=msg.decode("utf-8")
topicRecibido=topic.decode('utf-8')
print("Cambio en: " + topicRecibido + ": " + codigo)
if(topicRecibido==topic_ALARMA and "ON" in codigo):
ALARMA_ACTIVA=True
LedRojo.value(0)
else:
ALARMA_ACTIVA=False
LedRojo.value(1)
try:
conexionMQTT=MQTTClient(client_id, mqtt_server, user=user, password=password, port=int(port))
conexionMQTT.set_callback(DetectaPublish)
conexionMQTT.connect()
print("Conexión establecida al Broker MQTT")
conexionMQTT.subscribe(topic_ALARMA)
conexionMQTT.subscribe(topic_tema3)
print("Suscrito a los topicos")
except OSError as e:
print("Fallo al intentar conectarse con el broker", e)
time.sleep(5)
machine.reset()
SensorTemp=dht.DHT22(Pin(12))
Alarma=PWM (Pin(5), freq=1200 ,duty_u16=32768)
Alarma.duty(0)
LedRojo=Pin(18, Pin.OUT)
print("Comenzando monitoreo de Temperatura")
while True:
SensorTemp.measure()
TempPIR=SensorTemp.temperature() #Guarda temperatura
try:
conexionMQTT.check_msg()
time.sleep_ms(500)
NuevaTemp=SensorTemp.temperature()
if ALARMA_ACTIVA:
if NuevaTemp>40:
Alarma.duty(512)
LedRojo.value(0)
if NuevaTemp!=TempPIR:
print("Temperatura modificada")
conexionMQTT.publish(topic_tema3, str(NuevaTemp))
else:
if NuevaTemp==TempPIR:
conexionMQTT.publish(topic_tema3, str(NuevaTemp))
else:
Alarma.duty(0)
TempPIR=NuevaTemp
except OSError as e:
print("Error", e)
time.sleep(5)
machine.reset()
Alarma.duty(512)
if not TempPIR:
print("Temperatura modificada")
conexionMQTT.publish(topic_tema3, str(1))
else:
if TempPIR:
conexionMQTT.publish(topic_tema3, str(0))
Alarma.duty(0)