Python MQTT Manual Reconnect

reconnects-iconAs 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:



Example reconnect script


Related tutorials:

Please rate? And use Comments to let me know more


  1. Hi Steve,

    Your blogs are very helpful. I am currently working with MQTT C++, and I want to know if there is something equivalent of loop_start() in C++ paho implementation.

    What I actually want is the client to block until it connects with the server, but this can not be achieved using the regular connect() system call if I start the server after the client. The client exists by throwing an exception…

    1. Sorry but haven’t used this client except with arduino and that is not the paho client.
      I Python You get the same so I always put the connect in a try block. I assume there must be an equivalent in c++

Leave a Reply

Your email address will not be published. Required fields are marked *