Skip to content

Instantly share code, notes, and snippets.

@dafvid
Created January 4, 2022 19:38
Show Gist options
  • Select an option

  • Save dafvid/bfee5110ecef7c38f1aa2bf8c293cdeb to your computer and use it in GitHub Desktop.

Select an option

Save dafvid/bfee5110ecef7c38f1aa2bf8c293cdeb to your computer and use it in GitHub Desktop.
Micropython async reconnect
import uasyncio # upip install this if not present
from umqtt.simple import MQTTClient
import webrepl
# you only need to connect once
# it's more like WiFi settings then connect
sta = network.WLAN(network.STA_IF)
sta.connect('<SSID>', '<PASSWD>')
mqtt = MQTTClient(<MQTT_SETTINGS>)
# method that checks connection and async sleeps 3 s if not connected
async def connect():
while not sta.isconnected():
await uasyncio.sleep(3)
webrepl.start() # restarts the webrepl after connection
# main loop
async def main():
print('\nStarting up...')
firstboot = True
while True:
if not sta.isconnected() or firstboot:
firstboot = False
print('Connecting...')
await connect()
print('Reconnect MQTT')
mqtt.connect()
print('listening on {0}'.format(*sta.ifconfig()))
do_whatever() # read sensors or whatever
await uasyncio.sleep(5) # async sleep for a while
uasyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment