from machine import Pin
import time
import dht
import asyncio
import random as rd
import network
from umqtt.simple import MQTTClient
from utime import localtime, sleep
import urequests
# Khởi tạo các chân và cảm biến
living_room_led = Pin(12, Pin.OUT) # Đèn phòng khách (đèn đỏ nối với chân GPIO 12)
bedroom_led = Pin(14, Pin.OUT) # Đèn phòng ngủ (đèn xanh nối với chân GPIO 14)
motion_sensor = Pin(27, Pin.IN) # Cảm biến chuyển động
d = dht.DHT22(Pin(26)) # Cảm biến nhiệt độ và độ ẩm
# Bơm tưới cây
water_pump = Pin(2, Pin.OUT) # Bơm tưới cây nối với chân GPIO 2
# Biến lưu thời gian tưới cây
schedule_on_time_watering = None
schedule_off_time_watering = None
# Biến trạng thái để theo dõi điều khiển thủ công
manual_control_living_room = False
# Kết nối WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Kết nối tới MQTT
MQTT_CLIENT_ID = f'bkacad_{rd.randint(0, 1000000)}'
MQTT_BROKER = "broker.hivemq.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_SUB_TOPIC = "d04k14_bkacad_14210"
# Callback
def sub_cb(topic, msg):
global schedule_on_time_watering, schedule_off_time_watering, manual_control_living_room
print(f"Received message: {topic} {msg}")
msg = msg.decode('utf-8')
if msg.startswith('schedule_on_watering'):
parts = msg.split()
if len(parts) == 2:
try:
command, time_str = parts
hour, minute = map(int, time_str.split(':'))
schedule_on_time_watering = (hour, minute)
print(f'Schedule on time for watering set to {schedule_on_time_watering}')
except ValueError as e:
print(f"Error processing message: {e}")
else:
print("Invalid schedule_on_watering message format. Expected format: 'schedule_on_watering HH:MM'")
elif msg.startswith('schedule_off_watering'):
parts = msg.split()
if len(parts) == 2:
try:
command, time_str = parts
hour, minute = map(int, time_str.split(':'))
schedule_off_time_watering = (hour, minute)
print(f'Schedule off time for watering set to {schedule_off_time_watering}')
except ValueError as e:
print(f"Error processing message: {e}")
else:
print("Invalid schedule_off_watering message format. Expected format: 'schedule_off_watering HH:MM'")
elif msg == 'led_red_on':
living_room_led.on()
manual_control_living_room = True
elif msg == 'led_red_off':
living_room_led.off()
manual_control_living_room = False
elif msg == 'led_blue_on':
bedroom_led.on()
elif msg == 'led_blue_off':
bedroom_led.off()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.set_callback(sub_cb)
client.connect()
client.subscribe(MQTT_SUB_TOPIC)
print("Connected!")
# Nhiệm vụ giám sát cảm biến chuyển động
async def task1():
motion_timeout = 10 # thời gian chờ tắt đèn sau khi phát hiện chuyển động
last_motion_time = time.time()
while True:
v = motion_sensor.value()
current_time = time.time()
if v == 1:
last_motion_time = current_time
if not manual_control_living_room:
living_room_led.on()
elif current_time - last_motion_time > motion_timeout:
if not manual_control_living_room:
living_room_led.off()
await asyncio.sleep(0.5)
# Nhiệm vụ giám sát nhiệt độ và độ ẩm
async def task2():
while True:
try:
d.measure()
t = d.temperature()
h = d.humidity()
print(f"t = {t}, h = {h}")
# Đẩy dữ liệu lên ThinkSpeak
url = f"https://api.thingspeak.com/update?api_key=LS1PHFH6NBRWZNZ4&field1={t}&field2={h}"
response = urequests.get(url)
print(response.text)
response.close()
except OSError as e:
print(f"Failed to read from DHT22 sensor: {e}")
await asyncio.sleep(15)
# Lắng nghe tin nhắn từ broker
async def task3():
while True:
client.check_msg()
await asyncio.sleep(0.5)
# Hàm kiểm tra lịch tưới cây
def check_watering_schedule():
now = localtime()
current_time = (now[3], now[4])
if schedule_on_time_watering and current_time == schedule_on_time_watering:
water_pump.on()
print("Water pump turned on by schedule")
if schedule_off_time_watering and current_time == schedule_off_time_watering:
water_pump.off()
print("Water pump turned off by schedule")
# Nhiệm vụ bật/tắt bơm tưới cây theo lịch trình
async def task4():
while True:
check_watering_schedule()
await asyncio.sleep(60) # Kiểm tra lịch trình mỗi phút
# Main loop
loop = asyncio.get_event_loop()
loop.create_task(task1())
loop.create_task(task2())
loop.create_task(task3())
loop.create_task(task4())
loop.run_forever()