我在线程“Python MQTT Connect仅限时间”中有以下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秒后不会终止,但我是不知道我应该在哪里修改编码来实现它。
答案 0 :(得分:1)
代码几乎是正确的,你只需要将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()