from machine import Pin
import wifi
import time
from umqtt.simple import MQTTClient
import dht
# asynchronous processing library
import uasyncio as asyncio
led1 = Pin(13, Pin.OUT)
led2 = Pin(12, Pin.OUT)
led3 = Pin(14, Pin.OUT)
dht22 = dht.DHT22(Pin(25, Pin.IN))
def handle_callback(topic, msg):
m = msg.decode("utf-8")
print(m)
if(m == '0'):
led1.off()
elif(m == '1'):
led1.on()
elif(m == '2'):
led2.off()
elif(m == '3'):
led2.on()
elif(m == '4'):
led3.off()
elif(m == '5'):
led3.on()
elif(m == '-1'):
led1.off()
led2.off()
led3.off()
elif(m == '100'):
led1.on()
led2.on()
led3.on()
wifi.connect_ap()
# Ket noi den broker
client_id = "ByM9HBAQLhkLNgAqDBggDiM"
user_name = "ByM9HBAQLhkLNgAqDBggDiM"
password = "WuF/KieLMYUsoyzx58S96L/U"
server = "mqtt3.thingspeak.com"
client = MQTTClient(client_id = client_id, server =server, user=user_name, password=password)
client.set_callback(handle_callback)
client.connect()
client.subscribe(b"channels/2252824/subscribe/fields/field3")
publish_topic = b"channels/2348678/publish"
# Task 1: Publish data to MQTT broker each 5s
async def task1():
while True:
print("Update temperature and humidity!")
dht22.measure()
t = dht22.temperature()
h = dht22.humidity()
payload = f"field1={t}&field2={h}&status=MQTTPUBLISH"
client.publish(publish_topic,payload.encode("utf-8"))
await asyncio.sleep_ms(5000)
# Task 2: 0.5s check if any data is sent from MQTT Broker?
async def task2():
while True:
client.check_msg()
await asyncio.sleep_ms(500)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.create_task(task1())
loop.create_task(task2())
loop.run_forever()