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?
Poll a umqtt broker to test for connection.
-
- Posts: 2
- Joined: Mon Mar 12, 2018 9:08 pm
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Poll a umqtt broker to test for connection.
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.
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.
Index to my micropython libraries.