import network
import time
from machine import Pin
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "600310ea-fe0c-4d75-8a20-133fba753981" #"micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "600310ea-fe0c-4d75-8a20-133fba753981/floorplan/bedroom/light"
LIGHT_RELAY_PIN = 27
BUTTON_PIN = 25
light = Pin(LIGHT_RELAY_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_DOWN)
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="")
time.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("Light ON")
light.on()
elif msg == "off":
print("Light OFF")
light.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:
light.value(not light.value())
light_status = "on" if light.value()==1 else "off"
client.publish(MQTT_TOPIC, light_status)
client.check_msg()
time.sleep(0.2)