MQTT Encoding and Decoding
Jump to navigation
Jump to search
MQTT Encoding and Decoding
The MQTT protocol is very lightweight (does not use many bytes to get the message across).
Each MQTT packet consists of:
- Fixed header
- b7-4: MQTT Packet Typ, b3-0: Flags
- Remaining length - this one is a bit tricky and consumes between 1 and 4 bytes. Encoding is least significant bits first in b6-0 while b7 is a "continuation bit" ('1' meaning "another byte follows").
- Variable header (optional), depending on the package type
- Payload (optional), depending on the package type
Text is encoded in UTF-8 without a terminating "0" byte, after the number of bytes in the text encoded as two bytes, MSB first.
Type | Number | Direction | Flags | Variable Header | Payload |
---|---|---|---|---|---|
CONNECT | 1 | Device to Broker | 0 | ||
CONNACK | 2 | Broker to Device | 0 | ||
PUBLISH | 3 | Both | b3: DUP, b2-1: QoS, b0: RETAIN | ||
PUBACK | 4 | Both | 0 | ||
PUBREC | 5 | Both | 0 | ||
PUBREL | 6 | Both | 1 | ||
PUBCOMP | 7 | Both | 0 | ||
SUBSCRIBE | 8 | Device to Broker | 1 | ||
SUBACK | 9 | Broker to Device | 0 | ||
UNSUBSCRIBE | 10 | Device to Broker | 1 | ||
UNSUBACK | 11 | Broker to Device | 0 | ||
PINGREQ | 12 | Device to Broker | 0 | ||
PINGRESP | 13 | Broker to Device | 0 | ||
DISCONNECT | 14 | Device to Broker | 0 | ||