"""
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
"""
import network
import time
from machine import Pin
import dht
from umqtt.simple import MQTTClient
def sub_cb(topic, msg):
global MSG_ONOFF
MSG_ONOFF = msg
print(MSG_ONOFF)
# MQTT Server Parameters
MQTT_CLIENT_ID = "UNLAM5"
MQTT_BROKER = "io.adafruit.com"
MQTT_USER = "alexfourcade"
MQTT_PASSWORD = "04a3398e8dde464c92a852d531c1b6fe"
MQTT_TOPIC_PUB_MSG = "alexfourcade/feeds/boton"
MQTT_TOPIC_PUB_TMP = "alexfourcade/feeds/temperatura"
MQTT_TOPIC_PUB_HUM = "alexfourcade/feeds/humedad"
MQTT_TOPIC_SUB = "alexfourcade/feeds/boton"
MSG_ONOFF = b"OFF"
#crea el sensor asociado al pin 15
sensor = dht.DHT22(Pin(15))
#crea el led asociado al pin 13
led = Pin(13,Pin.OUT)
led.off() #apaga el led
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
#esperando se conecte a la wifi
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
#conectando al servidor MqTT
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_TOPIC_SUB)
print("Connected!")
print("Esperando orden de inicio de lectura sensor!")
#inicializa el boton en el dashboard en off
client.publish(MQTT_TOPIC_SUB, b"OFF")
client.wait_msg() #espera se presion on en la web para iniciar lectura
while MSG_ONOFF != b"ON":
client.wait_msg()
led.on() #enciende el led de activado
print("Sistema de lectura de sensor iniciado!")
prev_temp = ""
prev_humi = ""
while True:
sensor.measure() #captura inforación del sensor DTH22
temp = str(sensor.temperature())
# humi = str(sensor.humidity())
#muestra la temperatura si cambio el valor
# if temp != prev_temp or humi != prev_humi:
if temp != prev_temp:
prev_temp = temp
client.publish(MQTT_TOPIC_PUB_TMP, temp)
# aux = f"la temperatura es de {temp} y la humedad de {humi}"
aux = f"la temperatura es de {temp}"
print(aux)
client.publish(MQTT_TOPIC_PUB_MSG, aux)
else:
print("No change")
#chequea boton on off en cada bucle
client.check_msg()
if MSG_ONOFF == b"ON":
led.on()
else:
led.off()
time.sleep(1)