MQTT protocol specifications

更新时间:
复制 MD 格式

Message Queuing Telemetry Transport (MQTT) is an asynchronous messaging protocol built on the TCP/IP protocol stack. As a lightweight publish-subscribe protocol, it is designed for unreliable network environments and is suitable for scenarios where devices have limited hardware storage or network bandwidth. The MQTT protocol decouples message senders and receivers in time and space. IoT Platform supports device connections over MQTT.

Supported versions

IoT Platform supports standard MQTT connections, compatible with versions 5.0, 3.1.1, and 3.1. Official specifications: MQTT 5.0, MQTT 3.1.1, MQTT 3.1.

Important

To use the MQTT 5.0 protocol, you must first purchase an Enterprise instance.

Differences from standard MQTT

  • Supports MQTT messages such as PUB, SUB, PING, PONG, CONNECT, DISCONNECT, and UNSUB.

  • Supports clean sessions.

  • Does not support will messages or retained messages.

  • Supports Quality of Service (QoS) levels 0 and 1. Does not support QoS 2.

  • Does not support subscription QoS. The message QoS is determined by the sender (PUB).

  • Supports revert-RPC (RRPC) based on native MQTT topics, enabling synchronous server-to-device calls.

Supported MQTT 5.0 features

MQTT 5.0 introduces features that improve performance and usability. Appendix C. Summary of new features in MQTT v5.0 and MQTT 5.0 overview.

IoT Platform supports the following MQTT 5.0 features.

Supported features

How to use

Session expiry

  • Set Clean Start and Session Expiry Interval at connection time:

    MqttConnectionOptions options = new MqttConnectionOptions();
    options.setCleanStart(true);
    options.setSessionExpiryInterval(60L);// Unit: seconds.
    
    MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
    mqttClient.connect(options);
  • Set Session Expiry Interval at disconnect:

    MqttProperties mqttProperties = new MqttProperties();
    mqttProperties.setSessionExpiryInterval(60L);// Unit: seconds.
    
    MqttAsyncClient mqttAsyncClient = new MqttAsyncClient(host, clientId, new MemoryPersistence());
    mqttAsyncClient.disconnect(30000, null, null, MqttReturnCode.RETURN_CODE_SUCCESS, mqttProperties);

Message expiry

Set Message Expiry Interval when publishing:

IntervalString content = "Hello World";
byte[] payload = content.getBytes();

// Create a message.
MqttMessage message = new MqttMessage(payload);
// Set the QoS for the message.
message.setQos(1);

MqttProperties mqttProperties = new MqttProperties();

// Set the message time-to-live (TTL).
mqttProperties.setMessageExpiryInterval(600L);

message.setProperties(mqttProperties);

// Publish the message.
MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
mqttClient.publish(topic, message);

Subscription options

Available subscription options:

  • QoS: The MQTT message QoS level. You can set it to 0 (QoS 0 message) or 1 (QoS 1 message).

  • No Local: Specifies whether the client receives messages that it publishes.

    In MQTT 3.1.1, a client receives its own published messages on subscribed topics. In MQTT 5.0, set this option to true to prevent self-delivery.

    Values:

    • true: Does not receive.

    • false: Receives.

  • Retain As Publish: Specifies whether the server retains the RETAIN flag when it forwards a message to a client.

    Values:

    • true: If the message has a RETAIN flag, the flag is retained. If the message does not have a RETAIN flag, this option has no effect.

    • false: The RETAIN flag is not retained, regardless of whether the original message has one.

    Important

    The Retain As Publish setting does not affect the RETAIN flag in retained messages.

  • Retain Handling: Specifies whether the server sends retained messages to the client when a subscription is established.

    Values:

    • 0: The server sends retained messages as long as the client subscription is successful.

    • 1: The server sends retained messages only if the client subscription is successful and the subscription did not previously exist.

    • 2: The server does not send retained messages even if the client subscription is successful.

MqttSubscription mqttSubscription = new MqttSubscription("aaa/bbb");

// Set the QoS subscription option.
mqttSubscription.setQos(1);

// Set the No Local subscription option.
mqttSubscription.setNoLocal(true);

// Set the Retain As Published subscription option.
mqttSubscription.setRetainAsPublished(true);

// Set the Retain Handling subscription option.
mqttSubscription.setRetainHandling(1);

MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
mqttClient.subscribe(new MqttSubscription[]{mqttSubscription});

Retained message

// Create a retained message.
String content = "Hello World";
byte[] payload = content.getBytes();
MqttMessage message = new MqttMessage(payload);
// Set the message as a retained message.
message.setRetained(true);

// Publish the message.
MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
mqttClient.publish(topic, message);

Will message

// Create a will message.
String content = "Will Message";
byte[] payload = content.getBytes();
MqttMessage message = new MqttMessage(payload);

MqttConnectionOptions options = new MqttConnectionOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.getBytes());

// Set the will message.
options.setWill(topic, message);

// Set the will delay.
MqttProperties willMessageProperties = new MqttProperties();
willMessageProperties.setWillDelayInterval(60L);
options.setWillMessageProperties(willMessageProperties);

// Establish a connection.
MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
mqttClient.connect(options);

Connection negotiation

MqttConnectionOptions connOpts = new MqttConnectionOptions();
connOpts.setMaximumPacketSize(1024L);

User property

MqttProperties properties = new MqttProperties();
List<UserProperty> userPropertys = new ArrayList<>();
userPropertys.add(new UserProperty("key1","value1"));
properties.setUserProperties(userPropertys);

After a device connects over MQTT 5.0, reported UserProperty data is visible in IoT Platform logs.

Important

Maximum 20 properties. Keys cannot start with underscore (_). Combined key-value length cannot exceed 128 characters.

Request-response pattern

If the requester is a device and the receiver is your business server, parse ResponseTopic and CorrelationData from the message properties after AMQP subscription or rule forwarding. Then call the Pub API operation to respond to the device.

MqttProperties properties = new MqttProperties();
properties.setCorrelationData("requestId12345".getBytes());
properties.setResponseTopic("/" + productKey + "/" + deviceName + "/user/get");
Important
  • Base64-decode the parsed CorrelationData to restore the original byte array.

  • ResponseTopic and CorrelationData each have a maximum length of 128 characters.

Enhanced error codes

Troubleshoot errors.

Topic alias

Not applicable.

Shared subscriptions

Shared subscription topic format: $share/${ShareName}/${filter}.

  • $share: A static field. The topic for a shared subscription must start with $share.

  • ${ShareName}: A string that contains only letters, digits, and underscores (_).

    Sessions with the same ${ShareName} share one subscription. Each matching message is delivered to only one session.

  • ${filter}: The topic filter in a non-shared subscription. It supports letters, digits, and underscores (_).

Example:

MqttConnectionOptions options = new MqttConnectionOptions();
options.setUserName(username);
options.setPassword(password);

MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
mqttClient.connect(options);

mqttClient.subscribe("$share/testGroup/user/post", 1);

Security levels

  • TLS direct connection mode (encrypted channel): Provides a high level of security.

    Important
    • IoT Platform supports TLS 1.0, 1.1, 1.2, and 1.3. Use TLS 1.2 or 1.3 — older versions have known security vulnerabilities.

    • The device-side Link SDK uses TLS 1.2 and 1.3 by default.

  • TCP direct connection mode (unencrypted): This feature will be discontinued soon. Do not use.

    Important

    You bear all data breach risks from using TCP direct connection mode.

Topic specifications

For topic definitions and classification, see What is a topic?.

You can view default communication topics on the product page of a device in the console. Feature-specific topics are described in the documentation for each feature.

Limits

Each registered device identity supports only one communication protocol at a time.

Usage notes

IoT Platform provides device-side SDKs for MQTT connections. Connect a device using a device-side SDK.

Connection methods: