Processing a received message using paho mqtt in python

时间秒杀一切 提交于 2019-12-01 06:47:42

问题


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))


来源:https://stackoverflow.com/questions/42756975/processing-a-received-message-using-paho-mqtt-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!