import dht
from machine import Pin, I2C, PWM, ADC
import time
import utime
from umqtt.simple import MQTTClient
import network
import ujson
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# MQTT Server Parameters
MQTT_BROKER = "broker.emqx.io"
MQTT_CLIENT_ID = "testing101"
MQTT_PORT = 1883
MQTT_TOPIC_PUB = "sensors/kitchen/carbon-monoxide"
MQTT_TOPIC_SUB = "sensors/kitchen/switches"
MQTT_USERNAME = 'emqx'
MQTT_PASSWORD = 'public'
# Setup the sensors and peripherals
# setup gas sensor
gas_sensor_pin = 34
gas_sensor = ADC(Pin(gas_sensor_pin))
gas_sensor.atten(ADC.ATTN_11DB) # set attenuation to 11dB
fan_relay = Pin(25, Pin.OUT)
fan_relay.value(0)
servo_pin = 26
servo = PWM(Pin(servo_pin), freq=50)
i2c = I2C(scl=Pin(22), sda=Pin(21))
lcd = I2cLcd(i2c, 0x27, 2, 16)
dht_sensor = dht.DHT22(Pin(27))
button = Pin(23, Pin.IN)
pir_sensor = Pin(14, Pin.IN)
mqtt_client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT, user=MQTT_USERNAME, password=MQTT_PASSWORD)
# Connect to the Wi-Fi network
print("Connecting to WiFi...")
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 to WiFi!")
# Connect to the MQTT broker
print("Connecting to MQTT broker...")
mqtt_client.connect()
print("Connected to MQTT broker!")
def sub_cb(topic, msg):
print("Received message from topic: {}, Message: {}".format(topic.decode('utf-8'), msg.decode('utf-8')))
# Parse the JSON payload of the message
try:
payload = ujson.loads(msg)
print("Parsed message: {}".format(payload))
if 'relay_switch' in payload:
state = payload["relay_switch"]
if state == 'on':
print("Turn on the Light")
fan_relay.value(1)
else:
print("Turn off the Light")
fan_relay.value(0)
else:
print("Invalid message format. Missing 'relay_switch' key.")
except ValueError:
print("Invalid JSON payload in message")
mqtt_client.set_callback(sub_cb)
mqtt_client.subscribe(MQTT_TOPIC_SUB)
# Initialize variables
previous_weather = ""
# Main loop
while True:
# mqtt_client.wait_msg()
# read gas sensor value
gas_value = gas_sensor.read()
# Read data from the DHT22 sensor
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Move servo based on temperature or humidity value
if temperature < 25 or humidity < 70:
# High temperature or humidity, move servo to a specific angle
servo.duty(80) # Set the desired duty cycle for the servo angle
else:
# Normal temperature and humidity, move servo to a different angle
servo.duty(120) # Set the desired duty cycle for the servo angle
# Read door lock value
if button.value():
state_lock = 'off'
else:
state_lock = 'on'
# Read PIR motion sensor status
pir_status = 'Detected' if pir_sensor.value() else 'Not Detected'
# Update the LCD display
lcd.clear()
lcd.putstr("Temp: {:.1f} C".format(temperature))
lcd.move_to(0, 1)
lcd.putstr("Hum: {:.1f} %".format(humidity))
lcd.move_to(0, 2)
lcd.putstr("Gas value: " + str(gas_value))
lcd.move_to(0, 3)
lcd.putstr("PIR: {}".format(pir_status))
lcd.move_to(0, 30)
# Publish data to MQTT broker if there is a change in weather
current_weather = ujson.dumps({"temperature": temperature, "humidity": humidity, "Gas": temperature})
# if current_weather != previous_weather:
print("Weather updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC_PUB, current_weather))
mqtt_client.publish(MQTT_TOPIC_PUB, current_weather)
previous_weather = current_weather
# else:
# print("No change in weather")
time.sleep(1)