from machine import Pin
import network
import time
from umqtt.simple import MQTTClient
import dht
# asynchronous processing library
import uasyncio as asyncio
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi GUEST','')
print('Linking...')
while not sta.isconnected():
pass
print('Link OK')
dht22 = dht.DHT22(Pin(20, Pin.IN))
def handle_callback (topic, msg):
m = msg.decode("utf 8")
print(m)
#Ket noi den broker
client_id = "GjcbOCszCystNhAsHiQCJhg"
user_name = "GjcbOCszCystNhAsHiQCJhg"
password = "vuzm8dONqSSCniK4O1iJNIo0"
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/2501169/subscribe/fields/+")
publish_topic = b"channels/2501169/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()