Python paho MQTT,client.on_publish 即使消息已发送到代理也未调用

Python paho MQTT, client.on_publish not called even though message is sent to broker

好的,这就是其中一个“我在这里缺少什么?”各种问题。

我为 client.on_publish 事件注册的回调从未被调用,即使消息已成功发布到代理(回调中没有打印日志消息,它不会在 VS Code 中的断点处停止).我特别感兴趣的消息是从 on_msg 回调中发布的,我试图在任何回调之外发布它,但它没有区别,消息由代理接收,但 on_publish回调永远不会触发。

调试时我可以看到在发布时有一个函数注册了 on_publish 回调(设置了 client._on_publish 属性)

Python 版本 3.7.4

OS Windows 10

初始化客户端的代码:

import paho.mqtt.client as mqtt

#configure mqtt client
client = mqtt.Client(config['MQTT']['client_id'])
client.on_connect = on_connect
client.on_message = on_msg
client.on_disconnect = on_disconnect
client.on_publish = on_publish

try:
    client.connect(config["MQTT"]["host"], int(config["MQTT"]["port"]))
except Exception as e:
    log.error("Failed to connect to MQTT broker", exc_info=True)

client.loop_start()

我对 on_msg 和 on_publish 的回调:

def on_msg(client, userdata, msg):
    global status_msg_id

    log.debug("on_msg")
    payload = json.loads(msg.payload)
    if payload['id'] == config["MISC"]["session_id"]:
        if payload['result'] == 0:
            log.debug("payload content=ok")
            status_msg_id = client.publish(
                topic = config["MQTT"]["pub_status"],
                payload = json.dumps({'status':'ok'}),
                qos = 2)
        else:
            log.debug("payload content=error")
            client.publish(
                topic = config["MQTT"]["pub_status"],
                payload = json.dumps({'status':'error'}),
                qos = 2)
        log.debug("msg id (mid) of status msg: {}".format(status_msg_id))

def on_publish(client, userdata, mid, granted_qos):
    log.debug("on_publish, mid {}".format(mid))
    # we never get here :(

那么,为什么 on_publish 函数没有被调用,我错过了什么?

on_publish 回调的签名错误。

来自docs

on_publish()

on_publish(client, userdata, mid)

应该是:

def on_publish(client, userdata, mid):
    log.debug("on_publish, mid {}".format(mid))