import time
import network
from machine import Pin
from umqtt.simple import MQTTClient
# WiFi setup
SSID = "Wokwi-GUEST"
PASSWORD = ""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(0.5)
print("Connected! IP:", wlan.ifconfig()[0])
# MQTT setup
MQTT_BROKER = "broker.hivemq.com"
CLIENT_ID = "esp32-wokwi-demo"
TOPIC_TEMP = b"esp32/iot/0235temp"
TOPIC_STATUS = b"esp32/iot/0235status"
TOPIC_CMD = b"esp32/iot/0235cmd"
mqtt = MQTTClient(CLIENT_ID, MQTT_BROKER)
mqtt.connect()
# LED setup
led = Pin(2, Pin.OUT)
# Callback for incoming messages
def callback(topic, msg):
print("Received:", topic.decode(), "->", msg.decode())
if msg == b"ON":
led.value(1)
elif msg == b"OFF":
led.value(0)
mqtt.set_callback(callback)
mqtt.subscribe(TOPIC_CMD)
print("Ready to receive commands...")
# Main loop
while True:
mqtt.check_msg()
# time.sleep(0.1)