from machine import Pin
# Thu vien bat dong bo
import uasyncio as asyncio
import dht
import network
from esp_internet import connect_wifi
import requests
import time
import ntptime # Network time protocol(NTP)
from umqtt.simple import MQTTClient
led_status = False
# Khai bao den (status led)
led = Pin(14, Pin.OUT)
# Chan cam bien
d = dht.DHT22(Pin(18))
# Cam bien chuyen dong
motion_sensor = Pin(5, Pin.IN)
motion_led = Pin(4, Pin.OUT)
# Khai báo 2 đèn điều khiển
led1 = Pin(32, Pin.OUT)
led2 = Pin(33, Pin.OUT)
# Tao bien luu trang thai wifi
is_connected = False
# Ket noi
# ESP
sta_if = network.WLAN(network.STA_IF)
connect_wifi(sta_if = sta_if)
ntptime.settime()
# ket noi den MQTT
def sub_cb(topic, msg): # khi co tin nhan den
if(msg==b"LED_ON"):
led1.on()
led2.on()
led_status = True
elif(msg == b"LED_OFF"):
led1.off()
led2.off()
led_status = False
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 = MQTTClient(client_id="d02k13123456", server="broker.hivemq.com", keepalive=60)
client.set_callback(sub_cb)
client.connect()
print("MQTT connected")
client.subscribe("d02k13/iot/asm")
# Task 4: nhận lệnh điều khiển từ xa
async def execute_commands_remote():
while True:
# kiem tra xem co lenh dieu khien hay ko
client.check_msg()
await asyncio.sleep(0.5)
# Task 3: phát hiện chuyển động theo khung giờ
async def detect_motion():
h = (time.localtime()[3] + 7) % 24
while True:
if(h >= 1 and h<= 17):
v = motion_sensor.value()
if(v == 1):
motion_led.on()
# Cập nhật có chuyển động lên thingspeak
res = requests.get("http://api.thingspeak.com/update?api_key=8BX23E94RN9UAPFX&field3=1")
del res # giai phong bo nho
else:
motion_led.off()
await asyncio.sleep(1)
# Task 2: lấy dữ liệu nhiệt độ, độ ẩm
async def get_env():
global is_connected
while True:
d.measure()
t = d.temperature() # nhiet do
h = d.humidity() # do am
print(t, h)
res = requests.get(f"http://api.thingspeak.com/update?api_key=8BX23E94RN9UAPFX&field1={t}&field2={h}")
del res # giai phong bo nho
await asyncio.sleep(30)
# Task 1: đèn báo hiệu kết nối thành công
async def status_led():
led_status = False
global is_connected
while True:
is_connected = sta_if.isconnected()
if(is_connected == True):
led.on()
else:
# Goi den ham -> reconnect wifi
if(led_status):
led.off()
else:
led.on()
led_status = not led_status
await asyncio.sleep(0.5)
loop = asyncio.get_event_loop()
loop.create_task(status_led())
loop.create_task(get_env())
loop.create_task(detect_motion())
loop.create_task(execute_commands_remote())
loop.run_forever()