-->

Processing a received message using paho mqtt in p

2020-03-25 05:55发布

问题:

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("/leds/pi")

def on_message(client, userdata, msg):
    if msg.topic == '/leds/pi':
        print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
client.loop_start()

I use this basic code to subscribe to a topic and receive a message. The on_message function gets called whenever a message is received. I need to be able to access the msg.payload outside the function and store it to a variable. The value in the variable should be updated whenever a message is received. I tried to store the msg.payload to a Global variable inside the function and access it but, that gave an error saying that the variable is not defined. Please help.

回答1:

I need to be able to access the msg.payload outside the function and store it to a variable.

You need a global variable like:

myGlobalMessagePayload = ''   #HERE!

def on_message(client, userdata, msg):
    global myGlobalMessagePayload
    if msg.topic == '/leds/pi':
        myGlobalMessagePayload  = msg.payload   #HERE!
        print(msg.topic+" "+str(msg.payload))