使用Paho Python:为什么未触发回调“ on_message”?

时间:2020-11-11 10:50:04

标签: python mqtt paho

我不明白为什么在与我订阅的主题相同的消息中正确发布消息时,为什么未触发回调“ on_message”。 这是我使用的代码:

def on_connect(client, userdata, flags, rc):
    """ Callback called when connection/reconnection is detected """
    print("Connect %s result is: %s" % (host, rc))

    # With Paho, always subscribe at on_connect (if you want to
    # subscribe) to ensure you resubscribe if connection is
    # lost.
    client.subscribe("some/message/to/publish")

    if rc == 0:
        client.connected_flag = True
        print("connected OK")
        return

    print("Failed to connect to %s, error was, rc=%s" % rc)
    # handle error here
    sys.exit(-1)


def on_message(client, userdata, msg):
    """ Callback called for every PUBLISH received """
    print("%s => %s" % (msg.topi, str(msg.payload)))


# Define clientId, host, user and password
client = mqtt.Client(client_id=client_id, clean_session=clean_session)
client.username_pw_set(user_name, password)
client.subscribe("some/message/to/publish")
client.on_connect = on_connect
client.on_message = on_message

# connect using standard unsecure MQTT with keepalive to 60
client.connect(host, port, keepalive=60)
client.connected_flag = False
while not client.connected_flag:  # wait in loop
    client.loop()
    time.sleep(1)

client.subscribe("some/message/to/publish")
# publish message (optionally configuring qos=1, qos=2 and retain=True/False)
ret = client.publish("some/message/to/publish", "{'status' : 'on'}")
client.loop()

print("Publish operation finished with ret=%s" % ret)

client.disconnect()

这是我得到的退出代码:

Connect node02.myqtthub.com result is: 0
connected OK
Publish operation finished with ret=(0, 3)

Process finished with exit code 0

1 个答案:

答案 0 :(得分:0)

调用client.loop()仅处理客户端网络事件处理器的单个迭代。

client.publish()的调用可能需要完成多个事件(取决于消息的大小和所使用的QOS),并且在代理将其发送回客户端时,将与处理消息完全分开。 对client.subscribe()的调用还将消耗至少一个事件循环调用。 因此,仅对client.loop()的调用是不够的。

除非您对自己的工作有一个很好的了解,否则您可能应该使用client.start_loop() / client.stop_loop()函数在单独的线程上运行事件处理循环。