Skip to content

Instantly share code, notes, and snippets.

@mml
Created July 27, 2024 15:44
Show Gist options
  • Save mml/7a31d03cbfc16b4c947310cd3756a4b5 to your computer and use it in GitHub Desktop.
Save mml/7a31d03cbfc16b4c947310cd3756a4b5 to your computer and use it in GitHub Desktop.
Snippet from my "exit if disabled" micropython code
def main():
connect_and_subscribe()
if check_disabled():
log('Exiting because disabled.')
return
read_sensor()
finish()
def connect_and_subscribe():
"""Connect to the MQTT server and subscribe to interesting topics."""
global c
c = umqtt.simple.MQTTClient('umqtt_client', MQTT_SERVER)
log(f'Connected to {MQTT_SERVER}')
c.set_callback(receive_message)
c.connect()
c.subscribe(topic(DISABLE_TOPIC))
def receive_message(top, msg):
global disabled
log('Received "%s" "%s"' % (top.decode('utf-8'), msg.decode('utf-8')))
if top == topic(DISABLE_TOPIC) and msg != b'false':
disabled = True
def check_disabled():
"""Checks, a couple times, if we are supposed to disable ourselves."""
c.check_msg()
if disabled:
return disabled
time.sleep(1)
c.check_msg()
return disabled
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment