Python paho-mqtt delayed connection status

Question:

This code snippet:

import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('localhost')
print(client.is_connected())

while not client.is_connected():
  client.loop()
  print(client.is_connected())

print(client.is_connected())
client.disconnect()

produces:

False
False
True
True

which indicates that upon return from connect() the connection status is not yet updated. The documentation (https://pypi.org/project/paho-mqtt/#connect-reconnect-disconnect) reads The connect() function connects the client to a broker. This is a blocking function. This suggests that the status should be accurate on return from connect(). Am I missing something? Is there another way to test if client is connected?

Asked By: Paul Jurczak

||

Answers:

Connecting to a broker is a two stage process:

  • Establish a connection (TCP/TLS/Websocket etc)
  • Perform the MQTT connection handshake (CONNECT/CONNACK)

Taking a look at the source it appears that when you call client.connect('localhost') the first step (establish network connection) is completed before the function returns but the second is not (the CONNECT packet is sent but the function does not wait for the CONNACK).

The connection status (as reported by client.is_connected()) is only updated when the CONNACK packet has been processed (and this is done in the loop).

The documentation does not cover this as well as it could (and a few issues have been raised, e.g. this and this edit – I created a PR to update the docs).

Is there another way to test if client is connected?

A better approach is to use the on_connect callback (as shown in the examples). This answer provides further info.

Answered By: Brits
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.