What is MQTT Topic: Simple Explanation and Usage
MQTT topic is a simple string that acts like a label or address for messages in the MQTT messaging system. It helps devices know where to send or receive messages by subscribing or publishing to these topics.How It Works
Think of an MQTT topic like a mailbox address in a neighborhood. When a device wants to send a message, it puts it in the mailbox labeled with a specific topic. Other devices that care about that topic check that mailbox to get the message.
Topics are organized in a hierarchy using slashes, like home/kitchen/temperature. This helps devices subscribe to specific areas or groups of messages, just like choosing which mailboxes to check.
This system allows many devices to communicate efficiently without knowing each other's details, making MQTT great for IoT where devices need simple, fast messaging.
Example
This example shows a simple MQTT publisher sending a message to a topic and a subscriber receiving it.
import paho.mqtt.client as mqtt # Define the topic topic = "home/livingroom/light" # Callback when a message is received def on_message(client, userdata, message): print(f"Received message: {message.payload.decode()} on topic: {message.topic}") # Create subscriber client subscriber = mqtt.Client("subscriber") subscriber.on_message = on_message subscriber.connect("test.mosquitto.org", 1883) subscriber.subscribe(topic) subscriber.loop_start() # Create publisher client publisher = mqtt.Client("publisher") publisher.connect("test.mosquitto.org", 1883) # Publish a message publisher.publish(topic, "Turn on the light") # Wait to receive message import time time.sleep(2) subscriber.loop_stop()
When to Use
Use MQTT topics when you want devices to communicate by sending messages without direct connections. This is common in smart homes, industrial sensors, and remote monitoring.
For example, a temperature sensor can publish readings to home/kitchen/temperature, and a display device subscribes to that topic to show the current temperature. This keeps communication simple and scalable.
Key Points
- MQTT topics are strings that label messages for routing.
- They use a hierarchy separated by slashes for organization.
- Devices publish to or subscribe from topics to communicate.
- Topics enable flexible, decoupled messaging in IoT systems.