MQTT客户端继续执行diconnecting

时间:2018-02-16 13:41:11

标签: python mqtt mosquitto paho disconnection

我有多个python文件。一个文件具有与MQTT相关的所有代码并具有一些功能,而另一个文件导入MQTT文件并在事件发生时调用函数。 MQTT文件仅发布一些QoS 0和一些QoS 1的消息,并连接到安装在本地机器中的mosquitto代理。 MQTT代码如下

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

我运行多个python文件,这意味着运行多个MQTT副本。在mosquitto日志中,它始终显示客户端保持断开连接然后重新连接。我在mosquitto日志中经过一段时间后不断得到这些: -

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.

1 个答案:

答案 0 :(得分:1)

您需要将mqttc.loop_start()更改为mqttc.loop_forever(),以便在启动后台主题后停止程序退出。

编辑:在考虑了这个之后,问题不在于循环,它是客户端ID

假设您始终实例化您从主线程提供的代码中描述的对象的实例,那么线程ID将始终相同,这意味着代理将踢除除最后一个实例之外的所有连接。

而且,由于只要有多个MQTT客户端,你就有了在紧密循环中重新连接的逻辑,他们将始终只是继续相互开始

相关问题