Description
When testing the example code client_session_present.py
(from Paho MQTT Python GitHub Repository),
I encountered an issue where the on_disconnect callback is triggered twice when the network connection is lost. This behavior seems unexpected, as it could cause redundancy and potentially unwanted behavior in production applications.
I modified the example minimally to include on_disconnect and on_log callbacks to monitor connection status.
import paho.mqtt.client as mqtt
def on_connect(mqttc, obj, flags, reason_code, properties):
print("Session present: " + str(flags.session_present))
print("Connection result: " + str(reason_code))
def on_disconnect(mqttc, obj, flags, reason_code, properties):
print('Disconnected')
def on_log(mqttc, obj, level, string):
print(string)
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="asdfj", clean_session=False)
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
# Uncomment to enable debug messages
# mqttc.on_log = on_log
mqttc.user_data_set(0)
mqttc.connect("mqtt.eclipseprojects.io", 1883, 10)
mqttc.loop_forever()
When I simulate a network disconnection, the following output is generated:
Session present: True
Connection result: Success
Disconnected
Disconnected
Session present: True
Connection result: Success
As shown above, Disconnected is printed twice, indicating that the on_disconnect callback is called twice.
Environment:
Paho MQTT Python Client Version: 2.1.0
Python Version: 3.10
Request:
Could you please investigate why on_disconnect is being triggered twice? Any insights or fixes would be greatly appreciated.