The MQTT protocol, which stands for Message Queuing Telemetry Transport, is a lightweight messaging protocol based on the publish/subscribe model, designed for the Internet of Things. Here’s a detailed introduction:
Protocol Basics
-
Protocol Overview: MQTT was originally developed by IBM to provide a simple and efficient messaging communication method for resource-constrained devices and low-bandwidth, high-latency network environments. It operates over TCP/IP and enables message transmission by establishing a connection between clients and servers.
-
Protocol Versions: Common MQTT protocol versions include MQTT v3.1, MQTT v3.1.1, and MQTT v5.0. Among these, MQTT v3.1.1 is the most widely used version, which incorporates improvements and optimizations over v3.1 to enhance the protocol’s stability and security. MQTT v5.0 offers greater functionality and performance enhancements, introducing new features such as shared subscriptions, topic aliases, and message expiration to meet the needs of more complex IoT application scenarios.
Message Structure
-
Fixed Header: Each MQTT message begins with a fixed header, which contains information such as the message type, flags, and remaining length. The message type identifies the specific function of the message, such as CONNECT (connection request), PUBLISH (publish message), SUBSCRIBE (subscribe to topic), etc.; flags are used to set certain properties of the message, such as QoS level and whether the message is retained; the remaining length field indicates the total byte count of the variable header and payload.
-
Variable Header: The content of the variable header varies depending on the message type. For example, the variable header of a CONNECT message contains the protocol name and level; the variable header of a PUBLISH message includes the topic name and message ID. The length of the variable header is not fixed and is determined by the remaining length field in the fixed header.
-
Payload: The payload is the specific content of the message, and its format and meaning depend on the message type. For PUBLISH messages, the payload is the data to be published; for other message types, such as SUBSCRIBE messages, the payload contains information such as the list of topics to subscribe to.
Publish/Subscribe Model
-
Topic: A topic is a string used in the MQTT protocol to identify the category of messages, similar to a classification label. Publishers publish messages to specific topics, while subscribers receive corresponding messages by subscribing to topics of interest. Topics can have a hierarchical structure, using “/” as a separator, for example, “home/livingroom/temperature” represents the temperature information of a living room, allowing for easy categorization and management of messages.
-
Publisher: The publisher is the message generator, responsible for sending messages with specific topics to the MQTT server. Publishers can be various IoT devices, such as sensors and controllers, which publish relevant information as messages to the corresponding topics on the MQTT server after collecting environmental data or performing specific operations.
-
Subscriber: The subscriber is the message consumer, subscribing to topics of interest from the MQTT server, which pushes messages published to those topics to the respective subscribers. Subscribers can be other IoT devices, applications, or cloud platforms, which receive and process these messages to implement corresponding business logic, such as displaying device status or performing data analysis.
Quality of Service (QoS)
-
QoS 0: At most once delivery, where message delivery entirely depends on the underlying network conditions. The publisher is responsible for sending the message to the MQTT server without concern for whether it is correctly delivered to the subscriber. In this mode, messages may be lost, but transmission efficiency is the highest, suitable for scenarios where reliability is not critically important but real-time delivery is essential, such as real-time publishing of environmental monitoring data where occasional data loss does not significantly impact overall monitoring results.
-
QoS 1: At least once delivery, where the MQTT server ensures that messages are delivered to subscribers at least once. After sending a message, the publisher waits for a confirmation receipt from the server; if the confirmation is not received within a certain timeframe, the message is resent until confirmation is received. This mode guarantees reliable message delivery but may result in duplicate messages, suitable for scenarios where some reliability is required but duplication is tolerable, such as sending control commands for smart home devices.
-
QoS 2: Exactly once delivery, which is the highest level of message quality assurance, ensuring that messages are delivered exactly once between the publisher and subscriber, neither lost nor duplicated. Implementing QoS 2 is complex, requiring multiple message exchanges and confirmations among the publisher, server, and subscriber to ensure accurate and unique message delivery. This mode is suitable for scenarios where high reliability and accuracy are critical, such as the transmission of financial transaction data.
Retained Messages
Retained messages are an important feature of the MQTT protocol. When a publisher publishes a retained message, the MQTT server stores it and immediately sends this retained message to new subscribers who subscribe to the corresponding topic. The main purpose of retained messages is to allow new subscribers to obtain the latest state information of a topic without waiting for the publisher to publish again. For example, in a smart home system, when the status of a smart bulb changes, the bulb device can publish a state message with a retain flag to the corresponding topic, and new control terminals that subscribe to that topic can immediately receive the current status of the bulb, achieving state synchronization.
Last Will Message
The last will message is a special message mechanism provided by the MQTT protocol for clients. When a client establishes a connection with the server, it can set a last will message and topic. If the client unexpectedly disconnects, the server automatically publishes the last will message to the last will topic, notifying other relevant subscribers that the client has gone offline. Last will messages are typically used to send important status or alert information to other devices or systems in case of device failure or unexpected disconnection, allowing timely measures to be taken. For example, in a remote medical monitoring system, if a wearable device worn by a patient unexpectedly disconnects, the device can send an alert message to the monitoring center via the last will message, prompting medical staff to pay timely attention to the patient’s condition.
Security
-
Username/Password Authentication: The MQTT protocol supports a simple username and password authentication method. When a client connects to the MQTT server, it must provide the correct username and password for identity verification, and only after successful verification can it establish a connection and perform publish and subscribe operations. This authentication method is straightforward and suitable for scenarios where security requirements are not particularly high.
-
TLS/SSL Encryption: To improve communication security, the MQTT protocol can encrypt communication data based on the TLS/SSL protocol. By using TLS/SSL certificates, both clients and servers can be authenticated, and the transmitted data can be encrypted to prevent data from being stolen or tampered with during transmission. This encryption method provides high security, suitable for IoT applications in fields such as finance and healthcare where confidentiality and integrity of data are crucial.
🎉 A brand new Modbus debugging WeChat mini-program is here! Supports debugging with both Modbus TCP and Bluetooth to 485 communication forms.Convenient and efficient, helping you easily manage device debugging anytime, anywhere.Whether you are a professional engineer or a technical enthusiast, it will be your effective assistant, making Modbus debugging simpler and faster, bringing a new experience to your work and study, come and try it out! 😉