from time import sleep
from umqttsimple import MQTTClient
import ubinascii
from machine import Pin, unique_id, reset
but = Pin(23, Pin.IN, Pin.PULL_UP)
led = Pin(21, Pin.OUT)
led.value(False)
mqtt_server = 'broker.hivemq.com'
client_id = ubinascii.hexlify(unique_id())
topic_base = 'edm'
def sub_cb(topic, message):
print("Received MQTT message: topic '{0}', value '{1}'" \
.format(topic.decode("utf-8"), message.decode("utf-8")))
if topic == b'' + topic_base + '/led':
led.value(1 if message == b'1' else 0)
def connect_and_subscribe():
mqtt_client = MQTTClient(client_id, mqtt_server)
mqtt_client.set_callback(sub_cb)
mqtt_client.connect()
topic_sub = topic_base + '/led'
mqtt_client.subscribe(topic_sub)
print('Connected to {0} MQTT broker'.format(mqtt_server))
return mqtt_client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
sleep(10)
reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
state = True
def loop():
try:
client.check_msg()
global state
if but.value() != state:
state = not state
msg = 'Button ' + ('OFF' if state else 'ON')
print(msg)
client.publish(b'' + topic_base + '/button', b'0' if state else b'1')
except OSError as e:
restart_and_reconnect()
try:
while True:
loop()
except KeyboardInterrupt:
pass