0
我从线程“Python MQTT连接只有有限的时间”下面的python脚本。Python MQTT收到消息后重置计时器
#!/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秒后不会终止,我不知道应该在哪里修改编码来实现它。
非常感谢,它工作完美! – Rexksvii