Search code examples
pythonmqttmosquittopaho

Payload handling outside the scope of the on_message callback


I'm developing a code using the following technologies: Python, Mqtt, Mosquitto, Paho and Docker

The code works perfectly, I can connect to my pseudo broker (Mosquitto that is in Docker), send and receive my payloads. What bothers me and what I'm trying to do is to treat the payload received outside the paho callback, because the standard way of using it is:

# Function for the on_message callback
def receive_payload(client: mqtt.Client, userdata: dict[str, Any], message: mqtt.MQTTMessage) -> None:
     pass

# callback on_message
client: mqtt.Client = mqtt.Client()
client.on_message = receive_payload

I want to deal with it outside the scope of the on_message callback, as I wanted to add a return and use it in other parts and modules in my code. How can I do this without using global variables? I've searched on google and chatgpn and haven't found a definitive solution


Solution

  • You need to change your way of thinking.

    MQTT messages are delivered asynchronously, the on_message callback is only run when a message is delivered from the broker which matches a topic pattern the client is subscribed to. That means there is no where to "return" to, because there is nowhere in your code you could call a function that would ever return something. At the point you make the "call" there could have never been a message delivered or many, which do you want?

    What you want to do is to have the on_message function trigger what ever processing you want to do with the value.

    If you have a loop running that will change behaviour based on a value then you can use the on_message function to store it in a global variable.

    payload = None
    
    def on_message (client, userdata, message):
       global payload
       payload = message.payload
       ...
    
    client.on_message = on_message