无法在 MQTT 客户端中调用 message.topic?

Cannot call message.topic in a MQTT client?

我有这个问题,当我调用 msg.topic 时,我的 on_message 方法将停止正常工作。我没有收到错误,但打印语句不再执行,尽管正在发送新消息。

有什么问题?

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

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

如果您想知道您的代码哪里出错了,您可以将自己的 try/expect 添加到 on_message 函数的内部以显示问题。类似于:

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)