为什么MQTT客户端无法正确重新连接?

时间:2019-08-14 11:36:33

标签: python mqtt mosquitto paho

我有一个订阅主题的MQTT客户端,并测试所有可能的情况,我关闭了代理,然后再次打开以测试MQTT提供的自动重新连接,并且在代理中,以冗长的模式我可以看到该客户端连接到代理,但是什么也没有发生,没有数据在流动。另外,我注意到,即使在关闭代理之前的第一个连接中,也不会触发回调函数on_connect。在我的发布客户端中,on_connect也有另一个奇怪的行为。它会被触发,但不会在on_connect回调函数中运行所有代码,而且我也不知道为什么。 我正在使用mosquitto作为代理。

我尝试使用qos > 0, keepalive=60, clean session = false,但这些方法都不能解决没有数据传输的问题,并且on_connect函数仍然不会触发。

订户代码如下:

import paho.mqtt.client as mqtt

broker_url = "127.0.0.1"

def on_connect(client, userdata, flags, rc):
   print("Connected With Result Code " (rc))
   client.subscribe("Magnetometer", qos=2)

def on_message_from_Magnetometer(client, userdata, message):
   print("Message Recieved from Magnetometer: "+message.payload.decode())

def on_message(client, userdata, message):
   print("Message Recieved from Others: "+message.payload.decode())

def on_log(mqttc, obj, level, string):
    print(string)

client = mqtt.Client(client_id='MagnetometerSubscriber', clean_session=False)
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_url, keepalive=60)

client.subscribe("Magnetometer", qos=2)
client.message_callback_add("Magnetometer", on_message_from_Magnetometer)


client.loop_forever()

客户端代码如下:


client=""

flushOfflineData = 0

flag_connected = 0

flag_first_connection = 1

logger=''

def on_connect(client, userdata, flags, rc):
   global flag_connected
   print "Client connected with the Broker."
   flag_connected = 1
   print flag_first_connection

   #This code below does not get executed

   if flag_first_connection == 1:
      flag_first_connection = 0
   else:
      ParseOfflineData()

def on_disconnect(client, userdata, rc):
   global flag_connected
   flag_connected = 0
   setLocalStore()
   print "Client disconnected with the Broker."


def main():

    InitializeBrokerConnection()


    ser = serial.Serial(
        port='/dev/pts/17',\
        baudrate=9600,\

        parity=serial.PARITY_NONE,\
        stopbits=serial.STOPBITS_ONE,\
        bytesize=serial.EIGHTBITS)

    print("connected to: " + ser.portstr)



    while True:

        line=ser.readline()
        if line:
            print(line)
            json_body=Parse(line)
            if flag_connected == 1:
               client.publish("Magnetometer",json_body, qos=2)
            else:
                StoreLocally()


    ser.close()


def InitializeBrokerConnection():
    global client
    broker_address="127.0.0.1" 

    client = mqtt.Client("Magnetometer")
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.connect(broker_address) 
    client.loop_start()

因此,我期望on_connect这两个函数的代码都可以运行,并且希望订户客户端在可能的情况下重新连接并开始接收数据。仅当我关闭代理并将其重新打开以测试订户是否连接并接收数据时,才会出现此问题。当我使代理程序联机并执行订户python代码时,它可以正常工作,但是当我使代理程序脱机并重新联机时,订户客户端正在运行,它将不再接收数据。

0 个答案:

没有答案