from machine import Pin
import wifi
import time
from umqtt.simple import MQTTClient
import dht
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()
# Connect to the broker
client_id = "HhgVNjc1EB4DKggYNTQ8IAA"
user_name = "HhgVNjc1EB4DKggYNTQ8IAA"
password = "Iqjmg9w7Wt7q/M8BAAl+JqFk"
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/2348741/subscribe/fields/field3")
publish_topic = b"channels/2348741/publish"
# Task 1: Publish data to MQTT broker every 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: Check if any data is received from MQTT Broker every 0.5s
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()