import network
from time import sleep
from umqtt import MQTTClient
import binascii
import machine
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!")
SERVER = "broker.mqtt.cool"
CLIENT_ID = binascii.hexlify(machine.unique_id())
TOPIC = b"led_wokwi"
state = 0
button = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_DOWN)
led = machine.Pin("LED", machine.Pin.OUT)
while True:
if button.value() == 1:
led.on()
print("Button pressed - LED on")
else:
led.off()
print("Button not pressed - LED off")
sleep(0.1)
def sub_cb(topic, msg):
global state
print(msg)
print((topic, msg))
if msg == b"on":
print("LED on")
state = 1
led.on()
elif msg == b"off":
print("LED off")
state = 0
led.off()
def main(server=SERVER):
c = MQTTClient(CLIENT_ID, server)
c.set_callback(sub_cb)
c.connect()
c.subscribe(TOPIC)
print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
try:
while True:
c.wait_msg()
except Exception as e:
print("Error:", e)
finally:
c.disconnect()
main()