Search code examples
pythonmqtt

How to write a function that awaits for a message from MQTT before continuing the program?


I am trying to send a message using publish.single and then receive it and act upon the data received. Hence, I can't proceed unless I receive something from the server, so is there a way to write a statement that will wait for a message from MQTT before proceeding?

Example code:

publish.single("$topic", data, ip_address)
#can't do anything here 
receive(data_from_broker) #or anythin that looks like it!
#continue with the program here 

Solution

  • The short answer is you don't.

    At least not in the way you describe. MQTT is an asynchronous protocol, there is no sense of sending a message and waiting for a response, a publishing client has no way to know if the is 0, 1 or n subscribing clients listening on the topic the message is published.

    You will need to build something called a state machine to keep track of where in the program flow you are when messages are received.

    e.g.

    1. Application published message and sets flag in the state machine to say the message was sent
    2. Remote client receives message and publishes a response
    3. New message is received by the first client, it checks the state machine to determine that the message should be treated as a response to the original message.

    To subscribe to a topic you will have to move on from using publish.single to the full MQTT client so you can setup the onMessage callback to handle the incoming messages.