eclipse-paho / eclipse-paho/paho.mqtt.python
Client disconnect with code 16 and cannot connect again
- Dominant language
- Python
- Stars
- 2.4k
- Forks
- 742
- Avg merge
- 12d 48m
- Merged PRs (30d)
- 1
Description
I have this paho-mqtt python client (I have omitted some script logic and DB accessing for simplification):
```python
import json
import logging
import time
from paho.mqtt import client as mqtt
logging.basicConfig(level=logging.INFO)
mqtt_logger = logging.getLogger("MqttCon")
def on_connect(client, userdata, flags, rc):
mqtt_logger.info("Device connected with result code: " + str(rc))
client.subscribe("some_topic/#", qos=0)
def on_disconnect(client, userdata, rc):
mqtt_logger.info("Device disconnected with result code: " + str(rc))
def pub_values(client, base_topic, values):
msg = json.dumps(values)
target_topic = base_topic
mqtt_logger.info("Sending message to wheel...")
client.publish(target_topic, msg, qos=0)
def on_message(client, userdata, msg):
"""
Input messages format (can be one or list):
{
"tag_id": "string",
"value": "int or float",
"timestamp": "string format YYYY-MM-DDTHH:MM:SS.F"
}
"""
try:
info = json.loads(str(msg.payload.decode("utf-8")))
mqtt_logger.info(msg.topic)
pub_msg = {"tag_ids": [], "timestamp": ""}
mqtt_logger.info(f"Received message topic is {msg.topic}")
if isinstance(info, list):
# some logic
else:
# some logic, writing values to InfluxDB
pub_values(client=client, base_topic="some_topic", values=pub_msg)
except Exception as e:
mqtt_logger.error(str(e))
def on_log(client, userdata, level, buf):
mqtt_logger.info(f"SYSTEM: {buf}")
if __name__ == "__main__":
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.on_log = on_log
client.connect_async('', port=1883)
client.loop_start()
try:
while True:
time.sleep(0)
except KeyboardInterrupt:
pass
finally:
mqtt_logger.warning("Stopping client")
client.loop_stop()
client.disconnect()
```
It works good for a few hours, but at some time it have disconnection:
```
INFO:MqttCon:Received message topic is telemetry/MESPIV/batch
INFO:MqttCon:Sending message to wheel...
INFO:MqttCon:SYSTEM: Sending PUBLISH (d0, q0, r0, m4228), 'b'router/newdata'', ... (11336 bytes)
INFO:MqttCon:Sending message to wheel...
INFO:MqttCon:SYSTEM: Sending PUBLISH (d0, q0, r0, m4229), 'b'router/newdata'', ... (11336 bytes)
INFO:MqttCon:Device disconnected with result code: 16
INFO:MqttCon:Device disconnected with result code: 16
INFO:MqttCon:SYSTEM: Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b''
INFO:MqttCon:SYSTEM: Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b''
# more Sending CONNECT
```
The client disconnects with code 16 (MQTT_ERR_KEEPALIVE) and tries to connect in an infinite loop, but it fails to connect (don't recive CONNACK). How can I solve this problem? For mqtt docker container i use eclipse-mosquitto image.
My first code version worked by usial connect, but it has the same problem.
```python
if __name__ == "__main__":
# setting mqtt client
client.connect('', port=1883)
client.loop_forever()
client.disconnect()
```
**An important addition**: in the client logs there are disconnections with the code 16 with a successful reconnection, but it is impossible to reconnect from some kind.
Contributor guide
Assessment
This issue has not been assessed yet.