MQTT paho 卡在 message_callback_add 的呼叫中

MQTT paho stuck at call to to message_callback_add

我正在使用 paho.mqtt.client

下面是代码的简化版本,但它仍然显示了问题。

# -*- coding: utf-8 -*-

import sys
import os
import time
import logging

from time import sleep

import paho.mqtt.client as mqtt

mqtt_server_ip      = "10.42.0.1"
mqtt_server_port    = 1884

subscriptions_qos =[("doorStatus/status", 0),
                    ("doorStatus/eol",0)]

def callback_door_status(client, userdata, message):
    logging.debug("Received %s", message.payload)

def on_log(client, userdata, level, buf):
    logging.debug("%s", buf)

def on_connect(client, userdata, flags, rc):
    logging.info("Successfully connected to MQTT with result code %s", str(rc))
    print("before message_callback_add 1")
    client.message_callback_add("doorStatus", callback_door_status)
    print("after message_callback_add")

    (result, _) = client.subscribe(subscriptions_qos)
    if (result == mqtt.MQTT_ERR_SUCCESS):
        logging.info("Successfully subscribed to MQTT topics with result code %s", str(result))

def on_message(client, userdata, msg):
    logging.debug("Received: Topic: %s Body: %s", msg.topic, msg.payload)

def main():
    logger = logging.getLogger('root')
    logging.basicConfig(format='[%(asctime)s %(levelname)s: %(funcName)20s] %(message)s', level=logging.DEBUG)

    client = mqtt.Client("master")
    client.on_log = on_log
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(mqtt_server_ip, mqtt_server_port, 60)

    client.loop_forever()

if __name__ == '__main__':
    main()

这是程序的输出:

[2017-09-20 07:06:40,562 DEBUG:               on_log] Received CONNACK (0, 0)
[2017-09-20 07:06:40,562 INFO:           on_connect] Successfully connected to MQTT with result code 0
before message_callback_add 1

正如您从输出中看到的那样,与代理的连接已成功建立,但在第一次调用 message_callback_add 后代码立即卡住了,没有其他任何事情发生。此时我唯一能做的就是杀死进程。 我不知道为什么代码卡住了,我也看了文档,仍然找不到任何东西。

我自己设法解决了这个问题。在这里发布答案,这可能对以后的人有所帮助。

代码卡住的原因是我认为是互斥(死锁)问题。 message_callback_add() 必须在调用 on_connect() 之前执行。 阅读文档并非易事。