2017-10-19 5 views
0

"Python MQTT 제한된 시간 동안 만 연결"스레드의 아래 python 스크립트가 있습니다. 그 다음 클라이언트가 분리됩니다 10 초 이내에 어떤 메시지를 수신하지 않은 경우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 초 동안 대기합니다.

내가 지금하고있는 것은 클라이언트가 메시지를 받았을 때마다 startTime을 다시 현재 시간으로 재설정하여 클라이언트가 연결 상태를 유지하고 10 초 후에 종료되지 않도록하고 싶습니다. 그것을 달성하기 위해 어디에서 코딩을 수정해야할지 모르겠습니다.

답변

1

코드가 거의 맞으므로 을 on_message 콜백에 전역으로 표시해야합니다. 그러면 파이썬은 새로운 로컬 변수를 생성하지 않습니다.

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() 
+0

고마워, 완벽하게 작동했습니다. – Rexksvii