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

时间:2019-01-18 20:24:13

标签: python mqtt paho

我遇到了这个问题,当我调用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()

1 个答案:

答案 0 :(得分:1)

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)