订阅Carriots Stream

时间:2016-07-21 06:02:57

标签: python mqtt iot paho

我正在尝试使用paho mqtt客户端订阅carriots数据流。但我无法从车上读取任何数据。 这是我用来订购carriots的源代码。

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
# Client paho-mqtt CarriotsMqttServer
# sub_carriot.py

import paho.mqtt.subscribe as mqtt

class CarriotsMqttClient():
    host = 'mqtt.carriots.com'
    port = '1883'
    auth = {}
    topic = '%s/streams'
    tls = None

    def __init__(self, auth, tls=None):
        self.auth = auth
        self.topic = '%s/streams' % auth['username']
        if tls:
            self.tls = tls
            self.port = '8883'

    #Subscribe
    def subscribe(self):
        try:
            mqtt.simple(topics=self.topic, msg_count=10, hostname=self.host, port=self.port, auth=self.auth, tls=self.tls)
        except Exception, ex:
            print ex
if __name__ == '__main__':
     auth = {'username': '72cdf4ec......bbeec9d9fb4483e', 'password': ''}
     client_mqtt = CarriotsMqttClient(auth=auth) 
     client_mqtt.subscribe()

有人可以告诉我代码是否有问题,或者我错过了订阅cariots流所需的一些步骤。

我可以使用paho mqtt在carriots上成功发布,借助于carriots网站上提供的参考代码。

1 个答案:

答案 0 :(得分:0)

mqtt.simple功能阻塞,直到收到msg_count条消息,然后返回这些消息。

所以你拥有它的代码只会等到它收到10条消息然后它可能会退出而没有任何输出,因为没有任何东西可以收集函数返回的消息。

我建议您使用回调和网络循环来查看正常的订阅方法。像这样:

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
# Client paho-mqtt CarriotsMqttServer
# sub_carriot.py

import paho.mqtt.client as mqtt

class CarriotsMqttClient():
    host = 'mqtt.carriots.com'
    port = '1883'
    auth = {}
    topic = '%s/streams'
    tls = None
    client = None

    def __init__(self, auth, tls=None):
        self.auth = auth
        self.topic = '%s/streams' % auth['username']
        if tls:
            self.tls = tls
            self.port = '8883'
        self.client = mqtt.Client()
        self.client.on_message = self.onMessage
        self.client.connect(self.host, self.port)
        self.client.loop_start()

    def onMessage(self, client, userdata, msg):
        print(msg.topic+" "+str(msg.payload))

    #Subscribe
    def subscribe(self):
        try:
            self.client.subscribe(self.topic)
        except Exception, ex:
            print ex
if __name__ == '__main__':
     auth = {'username': '72cdf4ec......bbeec9d9fb4483e', 'password': ''}
     client_mqtt = CarriotsMqttClient(auth=auth) 
     client_mqtt.subscribe()