from machine import Pin
import uasyncio as asyncio
import urequests as requests
from dht import DHT22
import network
import time
from umqtt.simple import MQTTClient
# ESP32
sta_if = network.WLAN(network.STA_IF)
# Declare variables
dht22 = DHT22(Pin(25))
motion_sensor = Pin(16, Pin.IN)
high_temp_alert = False
low_temp_alert = False
high_humi_alert = False
low_humi_alert = False
# Đèn
led_motion = Pin(15, Pin.OUT)
green_led = Pin(12, Pin.OUT)
blue_led = Pin(13, Pin.OUT)
# Connect to wifi
def connect_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("Internet Connected!")
# Task 1
async def get_env_dht22():
global high_temp_alert, low_temp_alert, high_humi_alert, low_humi_alert
while True:
dht22.measure()
t = dht22.temperature()
h = dht22.humidity()
print("Temperature: {}°C, Humidity: {}%".format(t, h))
client.publish('abcxyz/iot/smashfarm/env', '{{"temperature":{}, "humidity":{}}}'.format(t, h))
if t > 50 and not high_temp_alert:
client.publish('abcxyz/iot/smashfarm/alert', 'Perform watering every 10 minutes')
high_temp_alert = True
elif t < 10 and not low_temp_alert:
client.publish('abcxyz/iot/smashfarm/alert', 'Turn on Heater')
low_temp_alert = True
elif 10 <= t <= 50 and (high_temp_alert or low_temp_alert):
client.publish('abcxyz/iot/smashfarm/alert','Temperature return to normal, performance finished' if high_temp_alert else 'Temperature return to normal, turn off heater')
high_temp_alert = False
low_temp_alert = False
elif h < 30 and not low_humi_alert:
client.publish('abcxyz/iot/smashfarm/alert', 'Turn on Mist System')
low_humi_alert = True
elif h > 60 and not high_humi_alert:
client.publish('abcxyz/iot/smashfarm/alert', 'Turn on Drainage System and Ventilation Fan')
high_humi_alert = True
elif 30 <= h <= 60 and (high_humi_alert or low_humi_alert):
client.publish('abcxyz/iot/smashfarm/alert', 'Humidity return to normal, turn off ventilation fan and water out system' if high_humi_alert else 'Humidity return to normal, turn off mist system')
high_humi_alert = False
low_humi_alert = False
# https://api.thingspeak.com/update?api_key=OU9MWNTJ56A2OPS9&field1=30&field2=50
if sta_if.isconnected(): # If Connect Wifi
res = requests.get(url=f'http://api.thingspeak.com/update?api_key=OU9MWNTJ56A2OPS9&field1={t}&field2={h}')
del res
await asyncio.sleep(10)
# Task 2
async def detect_motion():
while True:
v = motion_sensor.value()
if v == 1:
# Send Alert
client.publish('abcxyz/iot/smashfarm/alert', 'Motion Detected!!')
led_motion.on()
else:
led_motion.off()
await asyncio.sleep(1)
# Task 3
async def get_message_from_user():
while True:
client.check_msg()
await asyncio.sleep(0.5)
# Wifi Connecting
connect_wifi()
# Connect MQTT Broker
MQTT_CLIENT_ID = "abcxyz-2024-512"
MQTT_BROKER = "broker.hivemq.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
#Topic
MQTT_SUB = "abcxyz/iot/smashfarm"
def get_msg(topic, msg):
print(topic, msg)
if(msg == b'LED_ON'):
green_led.on()
blue_led.on()
elif(msg == b'LED_OFF'):
green_led.off()
blue_led.off()
elif(msg == b'GREEN_ON'):
green_led.on()
elif(msg == b'BLUE_ON'):
blue_led.on()
elif(msg == b'GREEN_OFF'):
green_led.off()
elif(msg == b'BLUE_OFF'):
blue_led.off()
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
# Get access when called
client.set_callback(get_msg)
client.connect()
print("Connected!")
client.subscribe(MQTT_SUB)
# Initiate and run asynchronous tasks
loop = asyncio.get_event_loop()
loop.create_task(get_env_dht22())
loop.create_task(detect_motion())
loop.create_task(get_message_from_user())
loop.run_forever()