2017-09-20 85 views
0

我正在使用paho.mqtt.clientMQTT paho卡在致電給message_callback_add

下面是代碼的簡化版本,但它仍然顯示問題。

# -*- 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代碼被卡住,沒有其他事情發生。在這一點上,我唯一能做的就是殺死這個過程。 我不知道爲什麼代碼卡住了,我也看過文檔,但仍然找不到任何東西。

+0

我似乎能夠重現這一點,我不明白爲什麼它應該這樣。我試圖提出一個問題反對python paho代碼,如下所述:https://pypi.python.org/pypi/paho-mqtt/1.1#reporting-bugs – hardillb

回答

1

我設法自己解決了這個問題。在這裏發佈答案,這可能有助於未來的人。

代碼卡住的原因是我相信一個互斥鎖(死鎖)問題。 message_callback_add()必須在致電on_connect()之前執行。 這並不是那麼簡單的閱讀文檔。

+1

我仍然提出一個錯誤,因爲這聽起來就像你在連接之前最終「做」訂閱,這是錯誤的, – hardillb

+0

我已經報告爲一個錯誤 – theAlse