0
0
Drone-programmingConceptBeginner · 3 min read

What is MQTT Topic: Simple Explanation and Usage

An 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.

python
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()
Output
Received message: Turn on the light on topic: home/livingroom/light
🎯

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.

Key Takeaways

MQTT topics act like addresses for messages in IoT communication.
Topics use a slash-separated hierarchy to organize messages.
Devices subscribe to topics to receive messages and publish to send them.
Using topics allows many devices to communicate without direct links.
MQTT topics make messaging simple, scalable, and efficient.