收到消息后Python MQTT重置计时器

2024-04-25 07:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我从线程“python MQTT Connect only for a limited time”中得到了下面的python脚本。你知道吗

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

def on_message(client, userdata, msg):
        if msg.topic == "foo/bar":
                print ("test successful! Message = ", str(msg.payload.decode("utf-8")))
                startTime = time.time()


def on_connect(client, userdata, flags, rc):
        client.subscribe("foo/bar")
        print("Client connected")

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

client.on_connect = on_connect
client.on_message = on_message
startTime = time.time()
waitTime = 10

while True:
        client.loop()
        elapsedTime = time.time() - startTime
        print("Elapsed time: ", elapsedTime)

        if elapsedTime > waitTime:
                client.disconnect()
                break

客户端将等待10秒钟,如果在10秒钟内没有收到任何消息,则客户端将断开连接。你知道吗

我现在要做的是,每当客户端接收到消息时,我都希望将startTime重置回当前时间,这样客户端将保持连接,并且不会在10秒后终止,但我不确定应该在哪里修改编码来实现它。你知道吗


Tags: importclient客户端messagetimeondefconnect
1条回答
网友
1楼 · 发布于 2024-04-25 07:31:20

代码几乎是正确的,您只需要将startTime回调中的on_message标记为全局,这样python就不会仅仅创建一个新的局部变量。你知道吗

def on_message(client, userdata, msg):
        if msg.topic == "foo/bar":
                print ("test successful! Message = ", str(msg.payload.decode("utf-8")))
                global startTime
                startTime = time.time()

相关问题 更多 >