Python MQTT Connect only for a limited time

1.3k views Asked by At

I have a Python script wherein I'm connected to a MQTT server. I'm expecting to get a message through the topic where I'm subscribed to, but should I not receive the message, I want to terminate the script entirely.

The script I'm working with looks as follows:

#!/usr/bin/python
import sys
import json
import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
        if msg.topic == "discovery":
                data = json.loads(msg.payload)
                serial = data['serial']
                print "test successful!"
                sys.exit(0)

def on_connect(client, userdata, flags, rc):
        client.subscribe([("discovery", 2)])

client = mqtt.Client()
try:
        client.connect('localhost', 4444)
except:
        print "ERROR: Could not connect to MQTT
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()

I have tried using a while True statement to loop and figure the time passing in between starting the script and it getting the message, but it seemed to (obviously) not escape the loop even while it gets the message through.

Is there a way that I can say how long it be connected for, and when it exceeds that time, just terminate the script entirely?

Or perhaps, is there a way (as I tried before) to make a loop but also consider the message coming through while in the loop?

Thanks for your suggestions!

1

There are 1 answers

0
hardillb On BEST ANSWER

Try something like this

It should wait for about 5 seconds for an incoming message then quit. You can adjust the wait time by changing the value waitTime just before the while loop

I have used the version of the mqtt network loop function that only runs for a short time and put it in a while loop. The loop also checks elapsed time and disconnects the client cleanly before bailing out of the loop. I also added a clean client exit for when a message is received.

#!/usr/bin/python
import sys
import json
import paho.mqtt.client as mqtt
import time

def on_message(client, userdata, msg):
        if msg.topic == "discovery":
                data = json.loads(msg.payload)
                serial = data['serial']
                print "test successful!"
                client.disconnect()
                sys.exit(0)

def on_connect(client, userdata, flags, rc):
        client.subscribe([("discovery", 2)])

client = mqtt.Client()
try:
        client.connect('localhost', 4444)
except:
        print "ERROR: Could not connect to MQTT"

client.on_connect = on_connect
client.on_message = on_message
startTime = time.time()
waitTime = 5
while True:
        client.loop()
        elapsedTime = time.time() - startTime
        if elapsedTime > waitTime:
                client.disconnect()
                break