MQTT Client keeps on diconnecting

Abdullah Shafiq

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.
hardillb

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From

MQTT existing client

From Java

How to print all topics in HiveMQ Client? (MQTT)

From Java

How to get the name of a client in HiveMQ Client (MQTT)?

From Dev

MQTT broker and client on the same RPI

From Dev

MQTT: How many times per minute MQTT client polls the server?

From Dev

JavaScript client for MQTT not using WebSockets

From Dev

Paho mqtt client not working properly

From Dev

MQTT publish subscribe in the same client

From Dev

MQTT Client testing with junit

From Dev

Problems using paho mqtt client with python 3.7

From Dev

Cannot call message.topic in a MQTT client?

From Dev

ImportError: No module named mqtt.client Error [paho-mqtt]

From Dev

flask-mqtt: Mqtt Client disconnects immediately after connect

From Dev

MQTT C++ client

From Dev

MQTT Android client not connecting to broker

From Dev

mqtt client in html page

From Dev

Installing MQTT client for windows 8.1

From Dev

Client potentially overloading mqtt broker

From Dev

Load balancing MQTT Client

From Dev

MQTT know if a client is subscribed

From Dev

MQTT Android Mosquitto client

From Dev

Artemis broker Intercept mqtt client connection

From Dev

MQTT broker communication to MQTT Client

From Dev

How to receive multiple messages in HiveMQ Client? (MQTT)

From Dev

Error wss://mqtt.eclipse.org when create mqtt client

From Dev

Create a client by using Scapy on MQTT

From Dev

Mosquitto MQTT broker with TLS - client connection errors

From Dev

HiveMQ MQTT client: subscribe to multiple topics

From Dev

mqtt client not connecting to mqtt broker through ip address