Search code examples
pythonmqttmosquittopahodisconnection

MQTT Client keeps on diconnecting


I have multiple python files. One files has all the code related to MQTT and has some functions while the other imports the MQTT file and calls functions as an event occurs. The MQTT file only publishes messages some QoS 0 and some QoS 1 and is connected to mosquitto broker installed in the local machine. MQTT Code is as follows

import paho.mqtt.client as mqtt
from threading import current_thread
import datetime
import cv2 as cv2
import time

# Define Variables
MQTT_HOST = "127.0.0.1"
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 60


def send_something():
    try:
        mqttc.publish("topic", "hello", 1, False)  # QoS =1 Retain = False
    except Exception as e:
        print(str(e))          
def send_something_else():
    mqttc.publish("anothertopic", CombinedByteArr, 0, False) 
            
            
def on_connect(mqttc, userdata, flags, rc):    
    print("[INFO]  : MQTT : Connection returned result: " + mqtt.connack_string(rc))
    if(rc == 0):
        print("[INFO]  : MQTT : Connection Successful")
    else:
        print(rc)

def on_disconnect(mqttc, userdata, rc):
    if rc != 0:
        print(" Unexpected disconnection")
    while(True):
        try:
            print("Trying to Reconnect")
            mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
            break
        except:
            print("Error in Retrying to Connect with Broker")
            continue

# Initiate MQTT Client

ThreadID = str(current_thread().ident)
mqttc = mqtt.Client(client_id= ThreadID, clean_session=False)


mqttc.on_publish = on_publish
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_disconnect = on_disconnect

while(True):
    try:
        mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)
        print("[INFO]  : MQTT : MQTT Connect Complete")
        break
    except:
        print("ERROR Occurred")


mqttc.loop_start()  # Start A Thread

The I run multiple python files that means multiple copies of MQTT are run. In mosquitto logs it always shows Client keep on disconnecting and then reconnecting. I get these continously after some time in mosquitto logs: -

1518788230: New client connected from 127.0.0.1 as MQTT2225 (c0, k60).
1518788230: Sending CONNACK to MQTT2225 (0, 0)
1518788230: Socket error on client MQTT2225, disconnecting.

Solution

  • You need to change mqttc.loop_start() to mqttc.loop_forever() to stop the program from just from exiting after starting the background thread.

    EDIT: after thinking about this some more the problem is not the loop, it's the client id

    Assuming you always instantiate an instance of the object described in the code you've provided from the main thread then the thread id will always be the same, which means the broker will kick all but the last instance to connect.

    And since you have logic to reconnect in a tight loop as soon as you have more than one MQTT client they will always just keep kicking off each other