繁体   English   中英

如何从 mqtt 主题中获取通配符值?

[英]How to get wildcard value from mqtt topic?

假设我有几个设备,每个设备都有温度。 所有与设备温度相关的消息都发布在主题device/1/temerature device/2/temperaturedevice/2/temperature等上。 我使用带有回调函数的 Python paho-mqtt 处理在此主题上发布的所有消息,该函数使用通配符表达式client.message_on_callback_add("device/+/temperature", ...) 有没有办法直接获取通配符表达式的值,这里+ (我需要解析msg.topic )?

假设我有几个设备,每个设备都有温度。 所有与设备温度相关的消息都发布在主题device/1/temerature device/2/temperaturedevice/2/temperature等上。 我使用带有回调函数的 Python paho-mqtt 处理在此主题上发布的所有消息,该函数使用通配符表达式client.message_on_callback_add("device/+/temperature", ...) 有没有办法直接获取通配符表达式的值,这里+直接(我需要解析msg.topic )?

假设我有几个设备,每个设备都有温度。 所有与设备温度相关的消息都发布在主题device/1/temerature device/2/temperaturedevice/2/temperature等上。 我使用带有回调函数的 Python paho-mqtt 处理在此主题上发布的所有消息,该函数使用通配符表达式client.message_on_callback_add("device/+/temperature", ...) 有没有办法直接获取通配符表达式的值,这里+直接(我需要解析msg.topic )?

import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    client.subscribe("device/+/temperature")
    client.message_callback_add("device/+/temperature", handler("device/+/temperature"))
    
def handler(subscribed_topic):
    wildcard_expression = subscribed_topic
    def on_message(client, userdata, msg):
        print(msg.topic+" "+str(msg.payload), wildcard_expression)
    return on_message
    
client = mqtt.Client()
client.on_connect = on_connect
client.connect(<mqtt broker url>, 1883, 60)
client.loop_forever()

暂无
暂无

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

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