HeXor
HeXor

Reputation: 1125

paho-mqtt subscribe check subscription status

I am using paho-mqtt 1.2 in python2.7 to listen to messages broadcasted by a broker, after subscribing to specific topics.

It's initialized like

import paho.mqtt.client as mqtt    #python mqtt package

# initialize MQTT client
mqttc = mqtt.Client()

# register listener functions    
mqttc.on_connect   = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message   = on_message

# connect to MQTT broker
mqttc.connect(<IP>, <PORT>, <KEEPALIVE_INTERVAL>)

# subscribe a topic to the broker
subscr = mqttc.subscribe(<TOPIC_NAME>, 0)

with the custom functions

def on_connect(client, userdata, flags, rc):
    print "connected"

def on_subscribe(client, userdata, mid, granted_qos):
    print "subscribed"

def on_message(client, userdata, msg):
    print "message received"

From the API I can read about the subscribe() function

The function returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not currently connected. mid is the message ID for the subscribe request. The mid value can be used to track the subscribe request by checking against the mid argument in the on_subscribe() callback if it is defined.

I am now trying to retrieve a status about the subscription, i.e. if I subscribed a VALID topic. In my understanding, the subscribe() function only returns an error code, if the topic has an invalid format. But I want to extract information, if I subscribed to a topic which is ACTUALLY broadcasted.

So far I get an on_subscribe() call including a subscription ID, no matter which topic (valid or invalid) I subscribe.

Upvotes: 1

Views: 5074

Answers (1)

hardillb
hardillb

Reputation: 59816

You can always subscribe to all (syntactically correct) topics, because a message may be published to it at some point in the future.

In MQTT there is no need to declare a topic before using it, a broker will allow you to subscribe to a topic that a message has never (and may be never will) had a message published to.

Topics effectively only exist at the moment a message is published to that topic.

The only way to know what topics are actually being used is to subscribe to them and see if a message turns up.

Upvotes: 2

Related Questions