from machine import Pin
import dht
import uasyncio
import time
from internet import connect_wifi
import requests
import ntptime
from my_mqtt import *
from umqtt.simple import MQTTClient
#DHT22
d = dht.DHT22(Pin(12))
# Declare lights and motion sensors
motion_sensor = Pin(25, Pin.IN)
led_motion = Pin(27, Pin.OUT)
# Declare the lights
led1 = Pin(15, Pin.OUT)
led2 = Pin(2, Pin.OUT)
led1.on()
led2.on()
# Connect to wifi
connect_wifi()
# Synchronize time with internet
ntptime.settime()
# Connect to MQTT
print("Connecting to MQTT server...", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user = MQTT_USER, password = MQTT_PASSWORD)
client.connect()
print('MQTT connected')
# Set callback MQTT
def m_callback(topic, msg):
print(topic, msg)
if(msg == b'LED_ON'):
led1.on()
led2.on()
elif(msg == b'LED_OFF'):
led1.off()
led2.off()
elif(msg == b'LED1_ON'):
led1.on()
elif(msg == b'LED2_ON'):
led2.on()
elif(msg == b'LED1_OFF'):
led1.off()
elif(msg == b'LED2_OFF'):
led2.off()
client.set_callback(m_callback)
client.subscribe("Duong/IoT/ASM")
#Read data from sensor and send to ThingSpeak 60s/1lan
async def update_env_to_thingspeak():
while True:
d.measure()
t =d.temperature()
h = d.humidity()
print(t, h)
# https://api.thingspeak.com/update?api_key=JDLJ6WMVPBTQ1XWE&field1=10&field2=20
res = requests.get(f'http://api.thingspeak.com/update?api_key=JDLJ6WMVPBTQ1XWE&field1={t}&field2={h}')
del res
await uasyncio.sleep(30)
# Detect motion, turn on lights, send alerts
async def detect_motion_and_alert():
while True:
# Lấy giờ hiện tại
hour = time.localtime()[3]
hour = (hour + 7) % 24
if(hour >= 1 and hour <= 6):
v = motion_sensor.value()
if(v == 1):
led_motion.on()
else:
led_motion.off()
await uasyncio.sleep(1)
# Receive control commands from the user
async def get_command_from_user():
while True:
# Check every 0.5 seconds
client.check_msg()
await uasyncio.sleep(0.5)
loop = uasyncio.get_event_loop()
loop.create_task(update_env_to_thingspeak())
loop.create_task(detect_motion_and_alert())
loop.create_task(get_command_from_user())
loop.run_forever()