首页 > 解决方案 > 不能在 MQTT 客户端中调用 message.topic?

问题描述

我有这个问题,on_message当我调用msg.topic. 我没有收到错误,但打印语句不再执行,尽管正在发送新消息。

问题是什么?

import paho.mqtt.client as client

hostname = 'iot.eclipse.org'
topic = 'Mein/Topic'

def on_message(client, userdata, msg):
    msg = msg.payload.decode()
    print("topic:", msg.topic)
    print("Received Message:      {}".format(msg))

def on_connect(client, userdata, flags, rc):
    print("Connection returned result: " + str(rc) +
          "\n")
    if rc == 0:
        print("Listening now.\n")
    client.subscribe(topic)

client = client.Client()
client.on_message = on_message
client.on_connect = on_connect
client.connect(hostname)
client.loop_forever()

标签: pythonmqttpaho

解决方案


paho 客户端有一个内置的 try/expect 块,用于包装调用on_message以防止行为不良的回调使网络线程崩溃。

如果你想知道你的代码在哪里失败,你可以在on_message函数内部添加你自己的 try/expect 来显示问题。就像是:

def on_message(client, userdata, msg):
    try:
        msg = msg.payload.decode()
        print("topic:", msg.topic)
        print("Received Message:      {}".format(msg))
    expect Exception, e:
        print(e)

推荐阅读