Search code examples
pythonmqttpaho

Combining loop_start(), loop_stop(), and loop_forever(); launching the separate application


Is it correct to use client.loop_start(), do some things, then client.loop_stop(), and finally client.loop_forever()?

Context: I have a bootloader.py on my Raspberry device. The bootloader is to be launched automatically when the device boots. The bootloaders connects to the application server (via dedicated IP and topic), checks the expected sofware installed at the device, downloads the newer software if it is not available locally, starts the wanted application, and then the bootloader should become a subscriber that listens to the "service messages" from outside. (For example: "send me your status", "check for the new software, and if there is something new, download it and reboot the device".

Current implementation: I have already implemented the loading process and launching the wanted application. The implementation uses the client.loop_start() (that is processing the communication using separathe thread). After downloading the wanted files, the bootloader calls subprocess.Popen(cmd), and becomes the proces of the launched application.

What I want: Now I want to separate the process of the launched application. The bootloader should became a client that listens forever. My idea was to client.loops_stop() after the communication with the application server was finished, launch the application, and then client.loop_forever() as the last action of the script to make it listening forever. Is such approach correct?

Is the described situation usual? Is it a well known pattern? If yes, could you point me to the related documentation? If no, can you see any flaw in the approach?


Solution

  • It's not really a pattern I've seen elsewhere, but if it meets your needs.

    The only problem would be if the time between calling loop_stop() and loop_forever() is longer than the Keep Alive period which will result in the broker disconnecting the client.

    You may also get a burst of messages when you restart the event loop.