MQTT Packet Decoder
Decode raw MQTT control packet bytes and inspect packet type, fixed-header flags, Remaining Length, QoS, DUP, RETAIN, topic name, packet identifier, payload and common CONNECT, PUBLISH and subscription fields.
—
—
—
—
What Is an MQTT Control Packet?
MQTT communication is carried in control packets. Every packet begins with a fixed header containing a four-bit packet type, four flag bits and a variable-byte Remaining Length field.
Depending on the packet type, a variable header and payload can follow the fixed header.
MQTT Fixed Header
First Byte:
Bits 7:4
Control Packet Type
Bits 3:0
Packet-specific flags
Following Bytes:
Remaining LengthMQTT Control Packet Types
| Value | Packet | Purpose |
|---|---|---|
| 1 | CONNECT | Client connection request |
| 2 | CONNACK | Connection acknowledgement |
| 3 | PUBLISH | Publish application message |
| 4 | PUBACK | QoS 1 publish acknowledgement |
| 5 | PUBREC | QoS 2 publish received |
| 6 | PUBREL | QoS 2 publish release |
| 7 | PUBCOMP | QoS 2 publish complete |
| 8 | SUBSCRIBE | Subscribe to topic filters |
| 9 | SUBACK | Subscribe acknowledgement |
| 10 | UNSUBSCRIBE | Remove subscriptions |
| 11 | UNSUBACK | Unsubscribe acknowledgement |
| 12 | PINGREQ | Keep-alive request |
| 13 | PINGRESP | Keep-alive response |
| 14 | DISCONNECT | Disconnect notification |
MQTT Remaining Length
Remaining Length uses a variable-byte encoding. Each byte contributes seven data bits, and bit 7 indicates whether another length byte follows.
Example:
0x7F
= 127 bytes
0x80 0x01
= (0 & 127)
+ (1 × 128)
= 128 bytesMQTT PUBLISH Packet
A PUBLISH packet carries an application message. Its fixed-header flags include DUP, QoS and RETAIN.
PUBLISH First Byte:
Bit 3:
DUP
Bits 2:1:
QoS
Bit 0:
RETAINThe variable header begins with a UTF-8 Topic Name. A Packet Identifier follows the topic when QoS is greater than zero.
MQTT Topic Name Encoding
MQTT UTF-8 strings are preceded by a two-byte big-endian length field.
00 04 74 65 73 74
00 04:
Length = 4
74 65 73 74:
"test"MQTT CONNECT Packet
CONNECT is the first packet sent by an MQTT client after the network connection has been established. Its variable header includes protocol name, protocol level, connect flags and keep-alive value.
The payload can contain Client Identifier, Will Topic, Will Payload, User Name and Password depending on the Connect Flags.
MQTT CONNECT Flags
| Bit | Meaning |
|---|---|
| 7 | User Name Flag |
| 6 | Password Flag |
| 5 | Will Retain |
| 4:3 | Will QoS |
| 2 | Will Flag |
| 1 | Clean Session in MQTT 3.1.1 |
| 0 | Reserved |
MQTT SUBSCRIBE Packet
SUBSCRIBE contains a Packet Identifier followed by one or more topic-filter entries. In MQTT 3.1.1 each entry contains a UTF-8 topic filter and a requested QoS byte.
MQTT QoS Levels
| QoS | Meaning |
|---|---|
| 0 | At most once |
| 1 | At least once |
| 2 | Exactly once |