import network
from utime import sleep
from urandom import choice
from machine import Pin
from umqtt.simple import MQTTClient
# Area and Device
AREA = "dining" #Select from: kitchen, dining, living, bedroom
DEVICE = "light" #Select from: light, fan
# MQTT Server Parameters
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "600310ea-fe0c-4d75-8a20-133fba753981/floorplan/"+AREA+"/"+DEVICE
LIGHT_RELAY_PIN = 27
BUTTON_PIN = 25
device = Pin(LIGHT_RELAY_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_DOWN)
# Simple UUID generator
def uuid():
uuid=""
for _ in range(32):
uuid += choice(["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"])
print(uuid)
return uuid
MQTT_CLIENT_ID = uuid() #"600310ea-fe0c-4d75-8a20-133fba753981"
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
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="")
sleep(0.1)
print(" Connected!")
def on_message(topic, msg):
try:
# Convert bytes to string
topic = topic.decode()
msg = msg.decode()
# Display received message
print("Message received on topic:", topic)
print("Message:", msg)
if msg == "on":
print("Device ON")
device.on()
elif msg == "off":
print("Device OFF")
device.off()
except Exception as e:
print("Error parsing message:", e)
connect_wifi()
client.set_callback(on_message)
client.connect()
client.subscribe(MQTT_TOPIC)
while True:
if button.value() == 1:
device.value(not device.value())
device_status = "on" if device.value()==1 else "off"
client.publish(MQTT_TOPIC, device_status, retain=True)
client.check_msg()
sleep(0.1)