import network
import time
import ubinascii
from machine import Pin, PWM, unique_id
from my_mqtt import MQTTClient
import os
# Initial startup message for terminal verification
print("=== Starting Smart Home MicroPython Script ===")
# ==================== PINS SETUP ====================
# Servo motor configuration on GP15 (50Hz PWM frequency)
servo = PWM(Pin(15))
servo.freq(50)
# LED Pin outputs matching Wokwi board pinout (GP1, GP2, GP3)
led_area1 = Pin(1, Pin.OUT)
led_area2 = Pin(2, Pin.OUT)
led_area3 = Pin(3, Pin.OUT)
def set_servo_angle(angle):
"""Calculates PWM duty cycle to rotate servo motor to target angle."""
duty = int(1000 + (angle / 180.0) * 8000)
servo.duty_u16(duty)
def close_door():
"""Sets servo position to 0 degrees (Door Closed)."""
set_servo_angle(0)
def open_door():
"""Sets servo position to 90 degrees (Door Open)."""
set_servo_angle(90)
# Initialize hardware state: Door closed & all area lights OFF
close_door()
led_area1.value(0)
led_area2.value(0)
led_area3.value(0)
# ==================== WIFI SETUP ====================
# Wokwi virtual Wi-Fi access point credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
def connect_wifi():
"""Connects Raspberry Pi Pico W to simulated Wi-Fi access point."""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to Wi-Fi...", end="")
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print("\nWi-Fi Connected!")
print("IP Address:", wlan.ifconfig()[0])
# ==================== MQTT CONFIG ====================
# NOTE: Switched from HiveMQ Cloud to HiveMQ Public Broker (port 1883)
# because Wokwi environment lacks 'ussl' library support for encrypted connections.
MQTT_BROKER = "broker.emqx.io"
MQTT_PORT = 1883
MQTT_TOPIC = "voice_assistant/commands"
# Callback function triggered when an MQTT message arrives
def on_message(topic, msg):
try:
command = msg.decode("utf-8").strip().lower()
print(f"\n[WOKWI RECEIVED]: '{command}'")
# Command: Enter home -> Unlock door & turn ON all lights
if "enter home" in command or command == "home":
print("--> Action: Door OPEN & All Lights ON")
open_door()
led_area1.value(1)
led_area2.value(1)
led_area3.value(1)
# Command: Turn ON specific lighting areas
elif "area 1" in command or "area one" in command or command == "one":
print("--> Action: Area 1 Light ON")
led_area1.value(1)
elif "area 2" in command or "area two" in command or command == "two":
print("--> Action: Area 2 Light ON")
led_area2.value(1)
elif "area 3" in command or "area three" in command or command == "three":
print("--> Action: Area 3 Light ON")
led_area3.value(1)
# Command: Turn ON all lights without moving door
elif "lights on" in command or command == "lights":
print("--> Action: All Lights ON")
led_area1.value(1)
led_area2.value(1)
led_area3.value(1)
# Command: Leaving home -> Open door temporarily & turn OFF all lights
elif "getting out" in command or "out" in command or "leaving" in command:
print("--> Action: Door OPEN & All Lights OFF")
open_door()
led_area1.value(0)
led_area2.value(0)
led_area3.value(0)
# Command: Close / Lock door
elif "close" in command or "lock" in command:
print("--> Action: Door CLOSED")
close_door()
except Exception as e:
print("Error processing message:", e)
# ==================== MAIN EXECUTION ====================
def main():
connect_wifi()
# 1. اسم بسيط وقصير جداً لـ HiveMQ
import random
client_id = f"pico_{random.randint(100, 999)}"
print(f"\nConnecting to MQTT Broker using ID: {client_id}...")
try:
client = MQTTClient(
client_id=client_id,
server=MQTT_BROKER,
port=MQTT_PORT,
keepalive=60
)
client.set_callback(on_message)
client.connect()
print("Successfully Connected to EMQX Broker!")
client.subscribe(MQTT_TOPIC)
print(f"Subscribed to Topic: {MQTT_TOPIC}")
print("Waiting for Voice Commands from Python Server...\n")
except Exception as e:
print("MQTT Connection Failed Error:", e)
return
last_ping = time.time()
while True:
try:
client.check_msg()
if time.time() - last_ping > 20:
client.ping()
last_ping = time.time()
time.sleep(0.1)
except Exception:
pass
main()Loading
pi-pico-w
pi-pico-w