from machine import Pin
import dht
import uasyncio
import time
import requests
import ntptime
from internet import connect_internet
from my_mqtt import *
from umqtt.simple import MQTTClient
#DHT22
d = dht.DHT22(Pin(14))
#Declare LEDs and Motion Sensor
m_sensor = Pin(34, Pin.IN)
led_m_sensor = Pin(25, Pin.OUT)
led_1 = Pin(0, Pin.OUT)
led_2 = Pin(19, Pin.OUT)
#Connect to internet
connect_internet()
#Sync 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 MQTT callback
def m_callback(topic,msg):
print(topic, msg)
if (msg == b'LED_ON'):
led_1.on()
led_2.on()
elif (msg == b'LED_OFF'):
led_1.off()
led_2.off()
elif(msg == b'LED1_ON'):
led_1.on()
elif(msg == b'LED1_OFF'):
led_1.off()
elif(msg == b'LED2_ON'):
led_2.on()
elif(msg == b'LED2_OFF'):
led_2.off()
client.set_callback(m_callback)
client.subscribe("UnizZng/control/asm")
#Detect Motion to Alarm LED
async def detect_motion():
while True:
hour = time.localtime() [3]
hour = (hour+7) % 24
if(hour >= 23 and hour <= 24):
v=m_sensor.value()
if(v == 1):
print('Detected Motion')
led_m_sensor.on()
else:
led_m_sensor.off()
await uasyncio.sleep(1)
#Read data from sensor and push to ThinkSpeak
async def update_to_thingspeak():
while True:
d.measure()
t = d.temperature()
h = d.humidity()
print(t,h)
# https://api.thingspeak.com/update?api_key=GSLDXW3JPQXXY367&field1=0
res = requests.get(f'http://api.thingspeak.com/update?api_key=GSLDXW3JPQXXY367&field1={t}&field2={h}')
del res
await uasyncio.sleep(20)
# Recieve MQTT
async def get_user_led_command():
while True:
#once per 0.5s
client.check_msg()
await uasyncio.sleep(0.5)
#Automatically do task at a set time
async def timed_auto_process():
while True:
hour = time.localtime() [3]
hour = (hour+7) % 24
minute = time.localtime() [4]
if(hour == 23 and minute == 20):
print("Doing Assigned Task")
await uasyncio.sleep(60)
# Main loop
loop = uasyncio.get_event_loop()
loop.create_task(update_to_thingspeak())
loop.create_task(detect_motion())
loop.create_task(get_user_led_command())
loop.create_task(timed_auto_process())
loop.run_forever()