簡體   English   中英

Python 中的 MQTT on_message 超時

[英]MQTT on_message timeout in Python

因此,我正在嘗試收聽發送到某個主題的定期消息。 問題是,如果在一段時間后(比如下面的代碼中的 2 秒)沒有新消息寫入該主題,我想中斷。 有沒有辦法做到這一點,也許有內置的 MQTT function 返回某個主題的定期更新屬性? 我附上了我想要的想象(在 Python 中)

import paho.mqtt.client as mqtt

def on_message(self, mqttc, obj, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))


def listen_to_heartbeat(self):
    global status_heartbeat
    global terminate_heartbeat_listener
    status_heartbeat = 1
    terminate_heartbeat_listener = 0

    client = mqtt.Client()
    client.connect(broker, port, 3)
    client.on_message = on_message
    topic = "machine/gui/0/heartbeat"
    client.subscribe(topic, 0)

    no_message = 0
    while True:
        client.loop()
        if there is no new message on topic:
           no_message = no_message + 1
        if no_message == 5:
           print("no new message after 10s, exiting ...)
           break
        time.sleep(2)


您需要在代碼中包含 on_connect 和 on_disconnect 函數。 on_connect function 在連接到客戶端后調用,確保連接建立。 所以你可以寫 on_connect function 為

def on_connect(client, userdata, flags, rc):
    logging.info("Connected flags"+str(flags)+"result code " + str(rc)+ "client1_id")
    client.connected_flag=True

之后,您需要定義 on_disconnect function 以在沒有收到消息的情況下斷開客戶端和代理之間的連接。

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected MQTT disconnection.")

rc(返回碼)用於檢查連接是否建立。 如果 rc,=0,則表示連接不成功,然后您可以通過編寫停止循環

client.loop_stop()

但是,如果您想等到客戶端重新連接到代理,請寫

client.loop_forever()

調用這些函數的順序如下

client.connect(broker, port, 3)
topic = "machine/gui/0/heartbeat"
client.subscribe(topic, 0)
client.on_connect = on_connect
client.on_message=on_message 
client.on_disconnect = on_disconnect
client.loop_stop()

我認為那時沒有必要編寫while循環。 試試看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM