0

I have the below python script from the thread "Python MQTT Connect only for a limited time".

#!/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

the client will wait for 10 seconds, if it didn't received any message within 10 seconds then the client will be disconnect.

What I'm trying to do now is whenever the client received a message, I want to reset the startTime back to current time so that the client will be stay connected and won't be terminated after 10 seconds but I'm not sure where should I modify the coding to achieve it.

hardillb
  • 54,545
  • 11
  • 67
  • 105
Rexksvii
  • 9
  • 1
  • 4

1 Answers1

1

The code is nearly right, you just need to mark the startTime in the on_message callback as being global so python doesn't just create a new local variable.

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()
hardillb
  • 54,545
  • 11
  • 67
  • 105