在Python中使用Paho MQTT处理收到的消息 [英] Processing a received message using paho mqtt in python

查看:1934
本文介绍了在Python中使用Paho MQTT处理收到的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我使用此基本代码订阅主题并接收消息.每当收到消息时,都会调用on_message函数.我需要能够在函数外部访问msg.payload并将其存储到变量中.每当接收到消息时,变量中的值就应该更新.我试图将msg.payload存储到函数内部的Global变量中并对其进行访问,但是,这给出了一个错误,指出该变量未定义.请帮忙.

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.

推荐答案

我需要能够访问该函数之外的msg.payload,并且 将其存储到变量中.

您需要一个像这样的全局变量:

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

这篇关于在Python中使用Paho MQTT处理收到的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆