Filter MQTT Topics -Python Utility Function Example

One of the most common tasks when handling MQTT messages is topic filtering.

Generally you will be subscribing to a topic base using a wild card e.g

sensors/#

so you will receive all messages published with the topic base of sensors. So you will receive messages on topics like:

sensors/hall/light1
sensors/hall/light2
sensors/lounge/light1
sensors/lounge/light2

So how do you filter the messages with lounge in their topic?

Fortunately the paho python client has a utility function called topic_matches_sub that will do this.

The function takes two arguments. The first (topic1) is the subscription topic and the second argument is the message topic (topic2).

So as an example if we were to subscribe to the topic (topic1)

+/bar

would we receive a message sent to test/bar.

Now the function is method in the client package so we have

import mqtt.paho.client as mqtt
r=mqtt.topic_matches_sub("+/bar","test/bar)
print(r)

Would return true.

Examples:

In these examples topic1=subscription topic and topic2=message topic.

  1. topic1=sensors/+/+ topic2=sensors/lounge/main-plug
  2. topic1=sensors/+/+ topic2=sensors/hall/main-plug
  3. topic1=sensors/lounge/+ topic2=sensors/hall/main-plug
  4. topic1=sensors/hall/+ topic2=sensors/hall/main-plug

Answers

1.true
2.true
3.false
4.true

Try it yourself

Send an mqtt message to broker test.mosquitto.org on topic sig/tools/filter/topic/request you will get a response on sig/tools/filter/topic/response.

The message is a string as follows
topic1,topic2
e.g. sensors/+/+,sensors/lounge/main-plug

The screen shoot below shows the process using MQTT Explorer

explorer-tool-example
Related tutorials and resources:

Please rate? And use Comments to let me know more

2 comments

  1. Steve, your blogs and examples are really useful. I purchased your book on working with PAHO. A suggestion though, please make your examples cohesive. In this article you start off with “ So how do you filter the messages with lounge in their topic?”. Then you skip to +/Bar ?? Then back to lounge.

    1. Sorry Mike didn’t mean to confuse anyone I just created them as additional more realistic examples.
      Rgds
      Steve

Leave a Reply

Your email address will not be published. Required fields are marked *