import time
import machine
import micropython
import network
import dht
from machine import Pin,PWM
from umqtt.simple import MQTTClient
# CONECTA WIFI
ssid = 'Wokwi-GUEST'
wifipassword = ''
# SERVER MQTT
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'Lpedro'
password = 'aio_wcSJ86B67xm68v88rKZdGhlzFLl6'
# TOPICOS
client_id = 'Incendio'
topic_TMP = 'Lpedro/feeds/sensortemp'
topic_ALARMA = 'Lpedro/feeds/alarmatemp'
ALARMA_ACTIVA=False
LEDESTADO = Pin(17, Pin.OUT) #puede cambiar
sensor = dht.DHT22(Pin(14))
#acceso a internet
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, wifipassword)
print("CONECTANDO")
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("CONECTADO A WIFI!!")
print(sta_if.ifconfig())
# HAY QUE COMPLETAR
def callback_alarma(topic, msg):
global ALARMA_ACTIVA,LEDESTADO
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print("Mensaje en Tópico" +topicrec+":"+dato)
if topicrec == topic_ALARMA and "OFF" in dato:
LEDESTADO(False)
if topicrec == topic_ALARMA and "ON" in dato:
LEDESTADO(True)
try:
conexionMQTT = MQTTClient(client_id, mqtt_server,user=user,password=password,port=int(port))
conexionMQTT.set_callback(callback_alarma)
conexionMQTT.connect()
conexionMQTT.subscribe(topic_ALARMA)
print("Conectado con Broker MQTT")
except OSError as e:
print("Fallo la conexion al Broker, reiniciando...")
time.sleep(5)
machine.reset()
while True:
try:
conexionMQTT.check_msg()
time.sleep_ms(600)
except OSError as e:
print("Error ",e)
time.sleep(5)
machine.reset()
topicrec = topic.decode('utf-8')
dato = msg.decode('utf-8')
if topicrec == topic_ALARMA and "ON" in dato:
sensor.measure()
temp = sensor.temperature()
print("TEMPERATURA=" +str(temp))
conexionMQTT.publish(topic_TMP, 1)