UMQTT: Achieving a robust connection
Posted: Fri Jul 22, 2016 10:31 am
In practice continuous WiFi connectivity cannot be guaranteed. The following code recovers after a WiFi outage. Note that failed publications are lost, but it would be straightforward to queue these if the application required it.
Comments, suggestions or improvements welcome.
Comments, suggestions or improvements welcome.
Code: Select all
import time
import ubinascii
from simple import MQTTClient
from machine import Pin, unique_id
SERVER = "192.168.0.23"
CLIENT_ID = ubinascii.hexlify(unique_id())
TOPIC = b"huzzah"
def main(server=SERVER):
client = MQTTClient(CLIENT_ID, server)
client.connect()
print("Connected to %s, waiting for timer" % server)
fail = False
count = 0
try:
while True:
count += 1
time.sleep_ms(5000)
if fail: # WiFi was down
try:
client.connect()
fail = False
except OSError: # WiFi is still down
print('Reconnect fail')
try:
client.publish(TOPIC, 'count {}'.format(count).encode('UTF8'))
print('Publish') # Simplistic code loses messages while WiFi is down
fail = False
except OSError:
print('Publish fail')
fail = True
finally: # if code fails or is interrupted
client.disconnect()