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

Python MQTT Reset timer after received a message

我从线程 "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 秒后终止但我不知道应该在哪里修改编码才能实现。

代码几乎是正确的,您只需要在 on_message 回调中将 startTime 标记为全局变量,这样 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()