How to run MQTT client in background in Python?

Question:

I’m trying to connect to DroneKit-SITL and keeping an MQTT-Broker running with loop_forever(). Whenever I receive a message over MQTT, I want to send commands to the drone via the dronekit python API. At the same time, I want to send drone data to other clients over MQTT every 5 seconds.

How do I let my dronekit-sitl-class and the mqtt-broker-class interact with each other? Should each of them run in a thread or a process?

Asked By: katzenmuetze

||

Answers:

I fixed the problem by running the loop in a separate thread like this:

clientloop_thread = Thread(target=self.connect)
clientloop_thread.start()

def connect(self):
    self._client.loop_forever()
Answered By: katzenmuetze

better solution is use loop_start() and loop_stop() instead of loop_forever()

self._client.loop_start() # its start loop in new thread
Answered By: Emad Modaresi