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之后,代码被卡住了,没有其他事情发生。在这一点上,我唯一能做的就是杀死该过程。我不知道为什么代码被卡住了,我还查看了文档,仍然找不到任何东西。

我自己解决了问题。在这里发布答案,将来可能会帮助某人。

代码被卡住的原因是我相信互斥s(死锁)问题。 message_callback_add()必须在调用on_connect()之前执行。这不是很琐碎的文档。

相关内容

  • 没有找到相关文章

最新更新