Reputation: 8165
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?
Upvotes: 2
Views: 2277
Reputation: 18290
Connecting to a broker is a two stage process:
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.
Upvotes: 3