Poll a umqtt broker to test for 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
Variomatic
Posts: 2
Joined: Mon Mar 12, 2018 9:08 pm

Poll a umqtt broker to test for connection.

Post by Variomatic » Thu Mar 15, 2018 6:31 pm

I'm connecting to an MQTT broker umqtt.simple and am trying to create a loop that will catch a failed attempt to connect to the broker. Is there any way of finding out if I have a connection to the server, ideally I'd like to do something like this:

while True:
try:
mqttc.connect()
print("Connected to broker")
print("Sending data every ", INTERVAL, " second(s)")
if mqttc.is_connected == True: <-- THIS IS KINDA WHAT I NEED
break
except:
print("Failed to connect to MQTT broker...")
print("Attempting to connect again, ctl-c to exit")

Is there any way of doing something like this, or will I need to do something more elaborate?

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Poll a umqtt broker to test for connection.

Post by pythoncoder » Fri Mar 16, 2018 8:04 am

Your use of try-except in a loop already copes with the case of a failed connection, you don't need a further test in the try block. The line "THIS IS KINDA WHAT I NEED" won't be executed if the connection failed because execution will pass from mqttc.connect() to the except block.

If you're thinking about detecting a connection which is dropped some time after the initial connection you need to use exception handling again. You need to look at umqtt.robust which handles this case.
Peter Hinch
Index to my micropython libraries.

Post Reply