As mentioned previously in understanding the loop there are some conditions when it is better to call the client loop yourself rather than using the loop_start() or loop_forever() calls.
Using these built in function calls means that you do not need to handle reconnects as they are part of the calls.
However when using the manual loop() method this you will need to handle reconnects yourself.
The code below will handle connects and reconnects.
We start with setting some starting parameters. The retry limit determines how many retry attempts it will make this is usually set to 0 which means it will try forever.
We also have a retry delay which starts at 2 seconds and is incremented after each fail and will limit at 100 seconds.
The client loop meeds to be called frequently and so it is enclosed in the while loop which is the main loop.
We use a flag that is set and reset in the on_connect and on_disconnect callbacks.
If we are connected then we can do some work. The demo script just publishes a message every 2 seconds.
We then encounter our reconnect code which starts with
if not client.connected_flag and rdelay>retry_delay:
If we are not connected and have exceeded the retry delay interval then try again to connect.
The actual connection attempt is inside a try loop as explained in understanding client connections.
If we fail to connect because the broker is not there then we fall in the exception, and then we set the retry delay.
In this case we also continue to retry
We can also fail because of a protocol error or more commonly a password error and this returns a non zero return code in the on_connect callback.
In this case we quit as there is no point in retrying. Here is the code for the on_connect callback and you can see that if the rc is not zero we quit.
The code for the main reconnect loop is shown below:
Resources:
Example reconnect script
Related tutorials:
- Paho Python MQTT Client – Understanding Callbacks
- Paho Python MQTT Client-Understanding The Loop
- Handling Multiple Client Connections-Python MQTT