Search code examples
pythonglobal-variablesmqtt

Python Paho MQTT Global Variable not Storing Message


Using paho mqtt, declaring global variable in the function, but when wanted to call the variable outside the function it doesn't work. (Last line print function outside the on_message function). It has message posting every 1sec, but when executing this, no message showing.

import paho.mqtt.client as mqtt
from datetime import datetime

message = ''
def on_connect (client, userdata, flags, rc):  
    print('Connected successful with attempt: {}'.format(str(rc)))
    client.subscribe('imax123')

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

client = mqtt.Client('IMAXCLIENT') 
client.on_connect = on_connect 
client.on_message = on_message 
client.connect('mqtt.eclipseprojects.io') 
client.loop_forever()

print(message)

Solution

  • As @Brits pointed out in the comments, the code will never pass the client.loop_forever() call.

    This call will block for the life of the MQTT client.

    How you move forward will very much depend on what you need to achieve. If you just want to receive a single message then there is a helper wrapper that will do that

    import paho.mqtt.subscribe as subscribe
    
    msg = subscribe.simple("paho/test/simple", hostname="mqtt.eclipse.org")
    print("%s %s" % (msg.topic, msg.payload))
    

    If you need to do more then you probably need to look at either swapping the client.loop_forever() for client.loop_start() which will start a background thread to run the client network loop. Even with this change your code will still need a lot more work as the message global will not be updated until a message arrives which could be a long time, so trying to print it immediately will probably not give what you expect.