Hello,
(This mailing list is for the mqtt protocol, for specifics implementations (like paho) you should go to there dedicated support.)
The loop_forever() method blocks the program, it is usefull when you need the program to use infinitly.
If your program is synchron, you can call repeatedly the loop() method, who loops for the amount of time defined (client.loop(0.1) blocks for 100ms)
You can also call the loop_start() (and the loop_stop()) method to start the loop in another thread, then you can control when your programm will exit.
If you still want to use the loop_forever() method, you should start a new thread for your publish function.
Here is a draft of the code i use in python :
import paho.mqtt.client as mqtt
import time
from threading import Thread
class Client(Thread):
def on_message(self, client, userdata, message):
print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos))
if message.payload == "quit":
self.stop()
def on_connect(self, client, userdata, flags, rc):
print("connected")
self.subscribe("commands")
def subscribe(self, topic):
self.client.subscribe(self.topic_prefix + topic)
def publish(self, topic, payload):
self.client.publish(self.topic_prefix + topic, payload=payload)
def __init__(self, name):
Thread.__init__(self, name=name)
self.running = False
self.client = mqtt.Client(...)
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
self.client.connect(...)
self.client.loop_start()
self.running = True
def run(self):
while self.running:
self.publish("topic", "message")
time.sleep(2)
def stop(self):
if self.running:
self.running = False
self.join()
print("Ending and cleaning up")
self.client.disconnect()
I hope it will help you,
Julien