In the first part of this tutorial, I introduced the concept of topics. Every message sent to an MQTT broker must be published to a topic and clients connected to the broker decide which messages to receive subscribing to one or more topics.
Today you’ll learn the format of the topics and different ways to subscribe to them.
A topic is a string (UTF-8 format) and consists of one or more levels, separated by a forward slash.
Here are some examples of topics:
commands home/temperature garden/tomatoes/humidity
A topic must have at least one character and can contains spaces (even if it’s not recommended).
You’re not required to define/create a topic on the broker to use it: a client sending a message can specify any topics, provided it’s syntactically correct.
A client can subscribe one or more topics. The subscription can be precise, specifying the exact name of the topic to be subscribed. Alternatively, you can use two wildcards, that are special characters used to subscrive a group of topics.
The first wildcard is the + character. This subscribes to a single level of topics.
Let’s see an example: if you subscribe to the topic home/+/temperature, you subscribe to all the topics that contain an arbitrary string instead of the wildcard, for example:
Here are on the contrary some topics thare are not subscribed:
The last example explains that the + character is wildcard for a single level (it therefore does not correspond to the two levels, terrace/dx, of the example).
The multilevel wildcard character is #. This must be the last character in the topic and preceded by a forward slash, /.
For example, if you subscribe to the topic home/indoor/# you’ll get the messages of the following topics:
while you won’t get messages from the following topics:
We can verify what explained above thanks to mosquitto. After having executed the server, let’s subscribe to the topic home/+:
mosquitto_sub.exe -t home/+ -v
(we use the -v option to display, together with the message, also the topic the message was published to).
If now we send messages to different topics, we can verify which of them are received and which not:
We can do a similar test for the wildcard #: