import time
from umqtt_simple import MQTTClient
import network
import ujson
from machine import Pin, I2C
from pico_i2c_lcd import I2cLcd
# Define MQTT connection information
mqtt_server = "broker.emqx.io"
mqtt_port = 1883
mqtt_topic = "topic_face_recognition" # The MQTT topic to subscribe to
mqtt_topic_fan = "topic_temperature_fan"
# Define GPIO pins
LED_GREEN_PIN = 20
LED_BLUE_PIN = 22
LED_RED_PIN = 26
SERVO_PIN = 27
LED_PIN = LED_GREEN_PIN # Assuming LED_GREEN_PIN is used for status indication
# Initialize LEDs and Servo
led_green = Pin(LED_GREEN_PIN, Pin.OUT)
led_blue = Pin(LED_BLUE_PIN, Pin.OUT)
led_red = Pin(LED_RED_PIN, Pin.OUT)
servo = Pin(SERVO_PIN, Pin.OUT)
# Initialize LCD
i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("Wokwi-GUEST", "")
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
time.sleep(1)
print("Wi-Fi connected")
# Variables to store the latest values
latest_mode = "unknown"
def on_message(topic, msg):
global latest_mode
try:
# Convert bytes to string
topic = topic.decode()
msg = msg.decode()
# Display received message
print("Message received on topic:", topic)
print("Message:", msg)
# Control LEDs based on topic and message
if topic == mqtt_topic:
if msg == "1":
print("Face Recognized")
lcd.clear()
lcd.putstr("Face Recognized")
led_green.on()
else:
print("Nothing")
lcd.clear()
led_green.off()
except Exception as e:
print("Error parsing message:", e)
# Wi-Fi connection
connect_to_wifi()
# MQTT client setup
client = MQTTClient("raspberry-pi", mqtt_server, port=mqtt_port)
def connect_to_mqtt():
print("Connecting to MQTT...")
while client.connect() != 0:
print("MQTT connection failed. Retrying in 5 seconds...")
time.sleep(5)
print("MQTT connection successful")
client.set_callback(on_message)
connect_to_mqtt()
# Subscribe to the MQTT topic
client.subscribe(mqtt_topic)
client.subscribe(mqtt_topic_fan)
try:
while True:
# Wait for MQTT messages
client.wait_msg()
except KeyboardInterrupt:
client.disconnect()