import network
from utime import sleep_ms
from umqtt.simple import MQTTClient
from machine import Pin, I2C
from ucryptolib import aes # For AES encryption/decryption
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import ubinascii
# MQTT Server Parameters
MQTT_CLIENT_ID = "smartgreeter-iqbal"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = "abc"
MQTT_PASSWORD = "abc"
MOTION_TOPIC = "smartgreeter/pir"
LCD_TOPIC = "smartgreeter/lcd"
# PIR Sensor and I2C LCD Setup
PIR_PIN = 13
pir = Pin(PIR_PIN, Pin.IN)
pir_state = 0
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000) # Adjust pins for ESP32
lcd_address = 0x27
lcd = I2cLcd(i2c, lcd_address, 2, 16) # 16x2 LCD
def encrypt_data(data):
cipher = aes(AES_KEY, 2, AES_IV) # Mode 2 is CBC mode
padded_data = data + ' ' * (16 - len(data) % 16) # Pad to 16 bytes
return ubinascii.b2a_base64(cipher.encrypt(padded_data)).strip()
def decrypt_data(data):
cipher = aes(AES_KEY, 2, AES_IV)
decrypted = cipher.decrypt(ubinascii.a2b_base64(data)).strip()
return decrypted.decode()
# Initialize LCD
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Smart Greeter")
def mqtt_message(topic, msg):
print("Message received on topic:", topic.decode())
print("Encrypted message:", msg.decode())
# Decrypt message
#decrypted_msg = decrypt_data(msg.decode())
#print("Decrypted message:", decrypted_msg)
# Update LCD with the message
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Message:")
lcd.move_to(0, 1)
lcd.putstr(msg.decode())
#lcd.putstr(decrypted_message)
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="")
sleep_ms(100)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD, ssl=True)
client.set_callback(mqtt_message)
client.connect()
client.subscribe(LCD_TOPIC)
print(" Connected!")
while True:
# AES Encryption Setup
#AES_KEY = os.urandom(16) # b'1234567890123456' Must be 16, 24, or 32 bytes
#AES_IV = os.urandom(16) # b'sixteen byte key' Must be 16 bytes
AES_KEY = b'aaaaaaaaaaaaaaaa' # b'1234567890123456' Must be 16, 24, or 32 bytes
AES_IV = b'aaaaaaaaaaaaaaaa'
client.check_msg() # Check for incoming MQTT messages
# PIR Sensor Motion Detection
motion = pir.value()
if motion == 1 and pir_state == 0:
print("Motion Detected!")
encrypted_message = encrypt_data("Motion Detected")
client.publish(MOTION_TOPIC, encrypted_message)
pir_state = 1
elif motion == 0 and pir_state == 1:
pir_state = 0