0

I am trying to subscribe to carriots data stream using paho mqtt client. But i am not able to read any data from carriots. Here's the source code i am using to subscribe to 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()

Can anybody tell me if there is something wrong with the code or i am missing some step which is required to subscribe to cariots stream.

I was able to successfully publish on carriots using paho mqtt, with help of reference code given on carriots website.

315
  • 13
  • 5

1 Answers1

0

The mqtt.simple function blocks until msg_count messages have been received and then it returns those messages.

So the code as you have it will just sit until it has received 10 messages then it is probably going to exit without any output as there is nothing to collect the messages returned by the function.

I would suggest you look at using the normal subscription method using a callback and the network loop. Something like this:

#!/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()
hardillb
  • 54,545
  • 11
  • 67
  • 105