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
so you will receive all messages published with the topic base of sensors. So you will receive messages on topics like:
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)
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.
In these examples topic1=subscription topic and topic2=message topic.
- topic1=sensors/+/+ topic2=sensors/lounge/main-plug
- topic1=sensors/+/+ topic2=sensors/hall/main-plug
- topic1=sensors/lounge/+ topic2=sensors/hall/main-plug
- topic1=sensors/hall/+ topic2=sensors/hall/main-plug
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
The screen shoot below shows the process using MQTT Explorer
Related tutorials and resources:
- Receiving Messages with the Paho MQTT Python Client
- Two Way communication Using MQTT and Python
- Handling Multiple MQTT Client Connections Using Python
- Simple Python MQTT Publish and Subscribe Example Script