Search code examples
pythonmqtt

python mqtt paho library, subscribre to multiple topics, get topic string in the callback on_subscribe() function


I am using the mqtt-paho python library. I am subscribing using a list of tuples so I can subscribe to multiple topics using a single call.

Is there a way to get the topic string so I can log it or (not yet implemented) to store it in an object with its associated request id (mid returned by the subscribe() function)?

My code:

def on_connect(self, client, userdata, flags, rc):
    if rc == 0:
        self.connected = True
        self.logger.info(f"Connected to MQTT broker with result code {str(rc)}")
        try:
            (result, mid) = self.mqttclient.subscribe([(self.__topic1, self.__qos), (self.__topic2, self.__qos)])
            if result_subscription == mqtt.MQTT_ERR_SUCCESS:
                print(result_subscription, subscription_id)
                # self.logger.info(f"Successfully subscribed to {topicname??}")                    
        except ValueError:
            self.logger.error(f"Cannot subscribe to {topicname??}")

def on_subscribe(self, client, userdata, mid, granted_qos):
    if mid is not None:
        # I would like here to log the topic subscribed if possible and why not associate in object the topic name and the sub ID (mid)
        self.logger.info(f"Client has successfully subscribed to {mytopic??}\n"
                         f"Granted_QOS {granted_qos}\n"
                         f"Userdata: {userdata}\n"
                         f"Mid: {mid}\n"
                         f"Client: {client}\n")

Any ideas? Thanks


Solution

  • No, not from the library it's self.

    But there is nothing to stop you storing the list of topics in a hashtable keyed by the mid so you can use the mid passed to the on_subscribe callback to get the topic list and match it to the list of QOS values in granted_qos