The previous sections were all about messages and subscriptions but we haven't seen yet how published messages find their subscribers. MQTT uses a topic based routing scheme. A topic is like a label added to every published message. It allows the broker routing logic to find all matching subscribers. Topics are typically represented in plain text and look like the following examples:
hello/world/
or
device/USA/NY/NYC/Manhatten/Broadway/temperature/sensorxyz
A client that subscribes to a topic will receive future messages published to the topic as well as a matching Retained Message if one exist.
Topics use the /
character as a separator. Topic hierarchies look a little like path hierachies in a file system.
Let's assume we have multiple sensors measuring temperature and air pressure in different locations:
device/USA/NY/temperature/sensor-id-123
device/USA/NY/pressure/sensor-id-123
device/USA/NY/temperature/sensor-id-321
device/USA/NY/pressure/sensor-id-321
device/USA/CA/temperature/sensor-id-456
device/USA/CA/pressure/sensor-id-456
device/USA/CA/temperature/sensor-id-654
device/USA/CA/pressure/sensor-id-654
The topic hierarchy then looks like this:
device
USA
NY
temperature
sensor-id-123
pressure
sensor-id-321
CA
temperature
sensor-id-456
pressure
sensor-id-654
A great feature of MQTT is that subscriptions can contain wildcards. With wildcards a subscriber can receive messages from multiple devices with only one generic subscription.
device/USA/+/temperature/#
As an example, the subscription topic above instructs the broker routing engine to deliver all temperature
measurements within the USA
. This works by using the two types of wildcards defined in MQTT, +
and #
.