MQTT Protocol: Key Features and Applications

MQTT (Message Queuing Telemetry Transport)

1. Basic Definition

MQTT is a lightweight, publish-subscribe (pub/sub) based messaging protocol designed for constrained devices and low-bandwidth, high-latency, or unreliable networks (e.g., IoT, satellite links, cellular networks). Developed by IBM in 1999 and standardized by OASIS/ISO (ISO/IEC 20922), it prioritizes minimal network overhead, low power consumption, and reliable message delivery—making it the de facto standard for IoT (Internet of Things) communication. Unlike traditional request-response protocols (e.g., HTTP), MQTT uses a broker-based pub/sub model to decouple message senders (publishers) and receivers (subscribers).

2. Core Architecture & Workflow

MQTT follows a client-broker architecture with three key roles:

2.1 Key Roles

  • Publisher: A client (e.g., sensor, smart thermostat) that sends messages to a specific “topic” (no direct connection to subscribers).
  • Subscriber: A client (e.g., mobile app, cloud server) that registers interest in one or more topics to receive relevant messages.
  • Broker: A central server that receives messages from publishers, filters them by topic, and forwards them to all subscribed clients (core responsibility: message routing and delivery).

2.2 Basic Workflow

生成失败,请重试

生成失败,请重试

豆包

你的 AI 助手,助力每日工作学习

  1. Subscribers connect to the broker and subscribe to topics (e.g., sensor/room1/temperature).
  2. Publishers connect to the broker and publish messages to the same topics.
  3. The broker matches published messages to subscribed topics and delivers messages to all relevant subscribers.
  4. Clients (publishers/subscribers) disconnect after communication (or maintain a persistent connection).

3. Core Features & Syntax

3.1 Key Features

  • Lightweight: Minimal packet size (fixed header is only 2 bytes) and low code footprint (suitable for microcontrollers like ESP8266/ESP32).
  • QoS (Quality of Service) Levels: Three levels to balance reliability and overhead:QoS LevelDescriptionUse Case0 (At Most Once)”Fire and forget”—message is delivered 0 or 1 times (no acknowledgment).Non-critical data (e.g., real-time sensor readings).1 (At Least Once)Message is delivered at least once (broker/client acknowledges receipt; retransmits if no ACK).Critical data (e.g., device command to turn on a pump).2 (Exactly Once)Message is delivered exactly once (4-way handshake to prevent duplicates).Mission-critical data (e.g., financial transactions, medical data).
  • Persistent Connections: Supports keep-alive packets to maintain connections even with intermittent network access.
  • Last Will and Testament (LWT): A pre-configured message the broker sends to a topic if a client disconnects unexpectedly (e.g., notify “device/room1/offline” if a sensor loses power).
  • Retained Messages: The broker stores the last message for a topic and delivers it to new subscribers (e.g., send the latest temperature to a new app that just subscribed).

3.2 Topic Syntax

Topics are UTF-8 strings that act as message “addresses” with hierarchical structure (separated by /):

  • Valid Examplessensor/room1/tempdevice/esp32/commandiot/factory/machine1/status
  • Wildcards: For flexible subscription:
    • +: Single-level wildcard (matches one level, e.g., sensor/+/temp matches sensor/room1/temp but not sensor/room1/floor1/temp).
    • #: Multi-level wildcard (matches all subsequent levels, must be the last character, e.g., sensor/room1/# matches sensor/room1/tempsensor/room1/humidity).

4. Typical Application Scenarios

  • IoT Device Communication: Smart home (thermostats, lights, cameras), industrial IoT (factory sensors, machinery monitoring), wearable devices (fitness trackers).
  • Remote Monitoring: Environmental monitoring (weather stations, air quality sensors) sending data to cloud servers over low-bandwidth networks.
  • Mobile/Embedded Systems: Real-time data transmission between battery-powered devices (minimal power consumption).
  • Machine-to-Machine (M2M): Communication between industrial equipment, vehicles (telematics), and backend systems.
  • Messaging for Constrained Networks: Satellite communication, rural cellular networks (low bandwidth/high latency).

5. Implementation & Tools

5.1 Popular MQTT Brokers

  • Eclipse Mosquitto: Open-source, lightweight broker (ideal for small-scale deployments).
  • EMQ X (EMQX): Scalable open-source broker for enterprise/IoT platforms.
  • AWS IoT Core/Azure IoT Hub/Google Cloud IoT: Cloud-managed MQTT brokers (no self-hosting required).

5.2 Client Libraries (Cross-Language Support)

  • Python: paho-mqtt (most widely used)
  • C/C++: Eclipse Paho C (for embedded devices)
  • JavaScript/Node.js: mqtt.js
  • Arduino/ESP32: PubSubClient

5.3 Simple Code Example (Python with Paho-MQTT)

Step 1: Install the library

bash

运行

pip install paho-mqtt

Step 2: Publisher Code (send temperature data)

python

运行

import paho.mqtt.client as mqtt
import time

# Configure broker connection
BROKER = "test.mosquitto.org"  # Public test broker
PORT = 1883
TOPIC = "sensor/room1/temperature"

# Create client instance
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)

# Connect to broker
client.connect(BROKER, PORT, 60)

# Publish messages in a loop
try:
    temp = 25.0
    while True:
        # Publish temperature (QoS 0)
        client.publish(TOPIC, payload=str(temp), qos=0)
        print(f"Published: {temp}°C to {TOPIC}")
        temp += 0.5
        time.sleep(2)
except KeyboardInterrupt:
    client.disconnect()
    print("Disconnected from broker")

Step 3: Subscriber Code (receive temperature data)

python

运行

import paho.mqtt.client as mqtt

# Configure broker/topic
BROKER = "test.mosquitto.org"
PORT = 1883
TOPIC = "sensor/room1/temperature"

# Callback for when a message is received
def on_message(client, userdata, msg):
    print(f"Received message on {msg.topic}: {msg.payload.decode()}°C")

# Create client and set callback
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_message = on_message

# Connect and subscribe
client.connect(BROKER, PORT, 60)
client.subscribe(TOPIC, qos=0)

# Keep running to receive messages
client.loop_forever()

6. Comparison with HTTP (IoT Context)

FeatureMQTTHTTP
Communication ModelPub/Sub (decoupled)Request-Response (coupled)
OverheadVery low (2-byte fixed header)High (large headers, cookies)
Connection TypePersistent (keep-alive)Stateless (per-request)
Power ConsumptionLow (ideal for batteries)High (frequent reconnections)
Use CaseReal-time IoT messagingWeb APIs, file transfers


了解 Ruigu Electronic 的更多信息

订阅后即可通过电子邮件收到最新文章。

Posted in

Leave a comment