I’m having some troubles when trying to set up a reconnect on the mqtt client. So far, the relevant code after some tests is:
def breconnect_cb(client): global mqttReconnects print("[MQTT] > Reconnection failed."), print("Trying to reconnect (Attempt %d)." % mqttReconnects) mqttReconnects += 1 sleep(1000) def aconnect_cb(client): global mqttReconnects print("[MQTT] > Connection successful.") mqttReconnects = 1 # Start connection to the broker try: client.connect("192.168.0.142", 300, port = 1883, ssl_ctx = None, breconnect_cb = breconnect_cb, aconnect_cb = aconnect_cb, sock_keepalive = None) break except Exception as e: print("[MQTT] > Unable to connect. Retrying.") sleep(2000)
After this, some subscriptions and a while loop to start publishing data to the broker. The problem comes when the broker is initially connected, but later it is stopped or the internet connection is down. My next steps were:
- I set a breconnect callback with a sleep(1000) and a reconnection tries counter, to see what was happening (prior to this the VM was reseting instantly anter mqtt service shup down). I found that after 26 retries, the MQTTConnectionError was raised and the thread exited:
Thread 6 exited wi > Data error:th exc eptioMQTTConnectionError @[00D2:0038:0000:0000:0000:0000:0000:0000]n
ets Jun 8 2016 00:22:57
Checking the mqtt module I found the reconnect method: It has a reconnection_max_retry set up to 25 in a decrement loop, to raise a MQTTConnectionError exception if <0.
I tried to handle the MQTTConnectionError, trying to avoid the VM crash, but I have not been successful at all. The try-except enclosing the client.connect does not get it, and the client.loop also doesn’t.
I disabled the VM reset on unhandled exceptions. All the threads were running after the MQTTConnectionError, even the one that launches the connect and the loop (It keeps cicling in the publish loop).
I’m now stuck here. I think the solution is to catch the exception raised on the thread created by the loop, but with my current knowledge I don’t know how to do that (I’m very new in Python). After that maybe I can terminate and relaunch the MQTT thread (maybe raising an exception and relaunching it in the main?). Other solution may be just to modify the mqtt.py in any way, but I’m reluctant to do that.
Sorry in advance for my lack of skill trying to explain my problems! I will gladly answer any questions raised asap.
Thank you very much in advance!