0
0
Drone-programmingConceptBeginner · 3 min read

MQTT Topic Wildcard: What It Is and How It Works

In MQTT, a topic wildcard is a special character used to subscribe to multiple topics at once. The two main wildcards are + for a single level and # for multiple levels in a topic hierarchy.
⚙️

How It Works

MQTT topics are like addresses for messages. Sometimes, you want to listen to many addresses that share a pattern instead of one exact address. This is where topic wildcards help.

The + wildcard matches exactly one level in the topic path, like a single folder in a file path. The # wildcard matches all remaining levels, like saying "everything inside this folder and its subfolders." This lets you subscribe to many topics with one rule.

💻

Example

This example shows how to subscribe to topics using wildcards in Python with the paho-mqtt client.

python
import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    print(f"Received message on topic: {msg.topic} with payload: {msg.payload.decode()}")

client = mqtt.Client()
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)

# Subscribe to all temperature sensors in any room
client.subscribe("home/+/temperature")

# Subscribe to all messages under home/kitchen
client.subscribe("home/kitchen/#")

client.loop_start()

# The client will print messages received on matching topics
import time
time.sleep(10)  # Keep script running to receive messages
client.loop_stop()
Output
Received message on topic: home/livingroom/temperature with payload: 22.5 Received message on topic: home/kitchen/humidity with payload: 45 Received message on topic: home/kitchen/temperature with payload: 24.0
🎯

When to Use

Use MQTT topic wildcards when you want to listen to many related topics without subscribing to each one individually. For example, if you have sensors in multiple rooms, + lets you get data from all rooms for a specific sensor type.

The # wildcard is useful when you want to monitor everything under a main category, like all devices in a building or all events in a system.

This saves time and bandwidth, making your IoT system more flexible and efficient.

Key Points

  • + matches exactly one topic level.
  • # matches any number of topic levels, including zero.
  • Wildcards can only be used in subscriptions, not in publishing.
  • They help simplify listening to many topics with similar patterns.

Key Takeaways

MQTT topic wildcards let you subscribe to multiple topics with one pattern.
Use + to match a single topic level and # to match multiple levels.
Wildcards are only for subscriptions, not for sending messages.
They make managing many IoT devices easier and more efficient.