I am trying to use the Python Paho MQTT library in a way that I can hook into the thread executing the client, so that I can supervise this thread and take action should it hang for some reason (watchdog).
The following code works, if I maintain my own connection state in the connected variable, but if I use client.is_connected() instead, it doesn't work, because is_connected returns false, even if I can see on the network that the connection has been established.
import paho.mqtt.client as mqtt
TOPIC = 'test156751'
def on_message(client: mqtt.Client,
user_data: any,
message: str):
message = message.payload.decode()
print(f'Received message: {message}')
client = mqtt.Client()
client.on_message = on_message
client.connect_async('test.mosquitto.org', 1883, 60)
connected = False
while True:
# Add watchdog here
if connected: # client.is_connected():
client.loop_read()
client.loop_write()
client.loop_misc()
else:
print('Connecting')
client.reconnect()
print('Probably connected')
connected = True
client.subscribe(TOPIC)
client.publish(TOPIC, 'test message')
What am I doing wrong?