eclipse-paho / eclipse-paho/paho.mqtt.python

on_disconnect Callback Triggered Twice When Connection is Lost

Open
#870 4 comments 1 reaction 0 assignees View on GitHub
Status: Available
Dominant language
Python
Stars
2.4k
Forks
742
Avg merge
12d 48m
Merged PRs (30d)
1

Description

When testing the example code client_session_present.py
(from [Paho MQTT Python GitHub Repository](https://github.com/eclipsepaho/paho.mqtt.python/blob/master/examples/client_session_present.py)),
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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.