Python MQTT 连接限时

Python MQTT Connect only for a limited time

我有一个 Python 脚本,其中我连接到 MQTT 服务器。我希望通过我订阅的主题收到消息,但如果我没有收到消息,我想完全终止脚本。

我正在使用的脚本如下所示:

#!/usr/bin/python
import sys
import json
import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
        if msg.topic == "discovery":
                data = json.loads(msg.payload)
                serial = data['serial']
                print "test successful!"
                sys.exit(0)

def on_connect(client, userdata, flags, rc):
        client.subscribe([("discovery", 2)])

client = mqtt.Client()
try:
        client.connect('localhost', 4444)
except:
        print "ERROR: Could not connect to MQTT
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()

我已经尝试使用 while True 语句循环并计算启动脚本和它收到消息之间经过的时间,但它似乎(显然)没有逃脱循环,即使它通过了消息。

有没有一种方法可以说明它连接了多长时间,当超过该时间时,完全终止脚本?

或者,是否有一种方法(正如我之前尝试的那样)进行循环,同时考虑在循环中传递的消息?

感谢您的建议!

尝试这样的事情

它应该等待大约 5 秒的传入消息然后退出。您可以通过更改 while 循环

之前的值 waitTime 来调整等待时间

我用过mqtt网络循环函数只运行很短时间的版本,放在while循环里。该循环还检查经过的时间并在跳出循环之前彻底断开客户端。我还为收到消息时添加了一个干净的客户端出口。

#!/usr/bin/python
import sys
import json
import paho.mqtt.client as mqtt
import time

def on_message(client, userdata, msg):
        if msg.topic == "discovery":
                data = json.loads(msg.payload)
                serial = data['serial']
                print "test successful!"
                client.disconnect()
                sys.exit(0)

def on_connect(client, userdata, flags, rc):
        client.subscribe([("discovery", 2)])

client = mqtt.Client()
try:
        client.connect('localhost', 4444)
except:
        print "ERROR: Could not connect to MQTT"

client.on_connect = on_connect
client.on_message = on_message
startTime = time.time()
waitTime = 5
while True:
        client.loop()
        elapsedTime = time.time() - startTime
        if elapsedTime > waitTime:
                client.disconnect()
                break