UMQTT: Achieving a robust connection

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
User avatar
pythoncoder
Posts: 4014
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

UMQTT: Achieving a robust connection

Post by pythoncoder » 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.

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()
Peter Hinch

turutupa
Posts: 1
Joined: Wed Mar 04, 2020 8:48 am

Re: UMQTT: Achieving a robust connection

Post by turutupa » Wed Mar 04, 2020 8:55 am

Is there a similar approach for a robust mqtt subscription with esp8266?? So far I manage to keep subscribed to Adafruit for around 2 days and then it simply stops working.. I've been thinking about setting my esp8266 to automatically reset once per day.. that might help.

Post Reply