简体   繁体   English

如何在python中获取mqtt连接的消息数据

[英]How can I get the message data of a mqtt connection in python

I am using the mqtt lib in Python to send and receive messages via mqtt.我在 Python 中使用 mqtt 库通过 mqtt 发送和接收消息。 At first I simply used this code:起初我只是使用了这个代码:

import paho.mqtt.client as mqtt


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

def on_message(client, userdata, msg):
  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_forever()

The example code works fine.示例代码工作正常。 Now I want to actually work with the message but, I don't know how to access the message.现在我想实际处理该消息,但我不知道如何访问该消息。 Sure msg.payload is printed, but some how I can't access it from outside the function.确定msg.payload已打印,但我无法从函数外部访问它。 I tried to alternate the code a bit, but it didn't help.我试图稍微改变代码,但没有帮助。 Eg when I try to return the value msg.payload to client.on_message I only get some address I think like a huge HEX Value.例如,当我尝试将值msg.payload返回给client.on_message我只会得到一些我认为像一个巨大的十六进制值的地址。 Can anyone tell me how to read the value outside the function or how to return this value?谁能告诉我如何读取函数外的值或如何返回这个值?

Thanks!谢谢!

You can create a global variable and append your msg.payload .您可以创建一个全局变量并附加您的msg.payload After that you can use them by iterating over that list in another thread.之后,您可以通过在另一个线程中迭代该列表来使用它们。

payloads = []
def on_message(client, userdata, msg):
    payloads.append(msg.payload)
    print(msg.topic + " " + str(msg.payload))

# ...

def funct():
    print payloads

thread.start_new_thread(funct, ())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM