import network
import time
import machine
from umqtt.simple import MQTTClient
import urandom
# Configuration
SSID = "Wokwi-GUEST"
PASSWORD = ""
MQTT_SERVER = "broker.emqx.io"
MQTT_PORT = 1883
TOPIC = b"serfer"
LED_PIN = 15
# Setup LED
led = machine.Pin(LED_PIN, machine.Pin.OUT)
# Connect to WiFi
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to", SSID)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(0.5)
print(".", end="")
print("\nWiFi connected")
# MQTT callback
def callback(topic, msg):
msg_str = msg.decode()
print("Received:", msg_str)
if msg_str == "on":
led.value(1)
elif msg_str == "off":
led.value(0)
# Connect to MQTT
def mqtt_connect():
client_id = "client-{:08x}".format(urandom.getrandbits(32))
client = MQTTClient(client_id, MQTT_SERVER, port=MQTT_PORT)
client.set_callback(callback)
client.connect()
client.subscribe(TOPIC)
print("MQTT connected")
return client
# Main loop
wifi_connect()
client = mqtt_connect()
while True:
try:
client.check_msg()
except:
print("Reconnecting...")
client = mqtt_connect()
time.sleep(0.01)