All Products
Search
Document Center

IoT Platform:MQTT protocol

最終更新日:Dec 11, 2023

Message Queuing Telemetry Transport (MQTT) is an asynchronous communication protocol that is based on the TCP/IP protocol stack. MQTT is a lightweight protocol that is used to transmit messages in the publish/subscribe model. MQTT is scalable in unreliable network environments. MQTT is suitable for scenarios in which the storage space of device hardware or network bandwidth is limited. The sender and receiver of a message that is transmitted over MQTT are not restricted by time or space. You can connect a device to IoT Platform over MQTT.

Supported version

IoT Platform supports device connections over MQTT. The following MQTT versions are supported: 5.0, 3.1.1, and 3.1. For more information, see MQTT 5.0, MQTT 3.1.1, and MQTT 3.1.

Important

Before you can connect devices to IoT Platform over MQTT 5.0, you must purchase an Enterprise Edition instance.

Differences between IoT Platform-based MQTT and standard MQTT

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

  • Supports the clean session flag.

  • Does not support will and retained messages.

  • Supports quality of service (QoS) 0 and QoS 1 messages and does not support QoS 2 messages.

  • Does not support QoS settings on subscriber clients. Only the QoS that is specified by publisher clients is supported.

  • Supports the synchronous Revert-Remote Procedure Call (RRPC) mode based on native MQTT topics. A server can call a device service and obtain a response at the same time.

Supported MQTT 5.0 features

Compared with the previous version, MQTT 5.0 provides a large number of new features to improve performance and user experience. For more information, see Appendix C. Summary of new features in MQTT 5.0 and MQTT 5.0 overview.

IoT Platform supports some new features of MQTT 5.0. The following table describes the features.

Supported feature

References

Session expiry

  • Configure the Clean Start feature and the session expiry interval when a device is connected.

    MqttConnectionOptions options = new MqttConnectionOptions();
    options.setCleanStart(true);
    options.setSessionExpiryInterval(60L);// Unit: seconds. 
    
    MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
    mqttClient.connect(options);
  • Configure the Clean Start feature and the session expiry interval when a device is disconnected.

    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

Specify a message expiration interval when a device sends messages.

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

// Create a message. 
MqttMessage message = new MqttMessage(payload);
// Specify a QoS level for messages. 
message.setQos(1);

MqttProperties mqttProperties = new MqttProperties();

// Specify a message expiration interval. 
mqttProperties.setMessageExpiryInterval(600L);

message.setProperties(mqttProperties);

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

Subscription options

Supported subscription parameters:

  • QoS: The QoS level of MQTT messages. Valid values: 0 (QoS 0 messages) and 1 (QoS 1 messages).

  • No Local: specifies whether a client receives the messages it published.

    If you use MQTT 3.1.1 and a client subscribes to a topic to which the client publishes messages, the client receives the messages. If you use MQTT 5.0, you can set this parameter to true when a client subscribes to a topic. In this case, the client does not receive the messages that it published to the topic.

    Valid values:

    • true: The client does not receive the messages that it published.

    • false: The client receives the messages that it published.

  • Retain As Publish: specifies whether to retain the RETAIN identifier of a message when the server forwards the message to a client.

    Valid values:

    • true: If the RETAIN identifier exists in a message, the identifier is retained. If the RETAIN identifier does not exist in a message, this value is invalid.

    • false: The RETAIN identifier is not retained regardless of whether the identifier exists in a message.

    Important

    The value of the Retain As Publish parameter does not affect the RETAIN identifier of retained messages.

  • Retain Handling: specifies whether the server sends a retained message to a client when a subscription is established between the server and the client.

    Valid values:

    • 0: If a subscription is established between the server and a client, the server sends a retained message.

    • 1: If a new subscription is established between the server and a client, the server sends a retained message.

    • 2: The server does not send a retained message to a client regardless of whether a subscription is established between the server and the client.

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

// Configure the QoS parameter. 
mqttSubscription.setQos(1);

// Configure the No Local parameter. 
mqttSubscription.setNoLocal(true);

// Configure the Retain As Published parameter. 
mqttSubscription.setRetainAsPublished(true);

// Configure the Retain Handling parameter. 
mqttSubscription.setRetainHandling(1);

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

Retained messages

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

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

Will messages

// 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());

// Specify the message as a will message. 
options.setWill(topic, message);

// Specify the latency for the will message. 
MqttProperties willMessageProperties = new MqttProperties();
willMessageProperties.setWillDelayInterval(60L);
options.setWillMessageProperties(willMessageProperties);

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

Feedback on connection establishment

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

User properties

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

After a device is connected to IoT Platform over MQTT 5.0, you can view the submitted UserProperty parameter in IoT Platform logs.

Important

You can add up to 20 properties. The key of a property cannot start with an underscore (_). The total length of a key and a value cannot exceed 128 characters.

Request-response pattern

For example, the requester is a device and the responder is your business server. After you use the Advanced Message Queuing Protocol (AMQP) subscription or data forwarding feature, you can parse the ResponseTopic and CorrelationData parameters from the property data in the message. Then, you can call the Pub operation to send a response to the device.

MqttProperties properties = new MqttProperties();
properties.setCorrelationData("requestId12345".getBytes());
properties.setResponseTopic("/" + productKey + "/" + deviceName + "/user/get");
Important
  • The parsed value of the CorrelationData parameter must be Base64 decoded to the byte array that is submitted by the device.

  • The value of the ResponseTopic or CorrelationData parameter cannot exceed 128 characters in length.

Enhancements in error codes

For more information, see Troubleshooting.

Topic aliases

N/A

Shared subscription

A shared subscription topic is in the $share/${ShareName}/${filter} format.

  • $share: a fixed item. The name of each shared subscription topic starts with $share.

  • ${ShareName}: a string that can contain only letters, digits, and underscores (_).

    ${ShareName} specifies a group of sessions that share the subscription. Each message that matches the shared subscription is sent to only one session.

  • ${filter}: the topic filter for non-shared subscriptions. The value can contain 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

  • Encrypted Transport Layer Security (TLS) connection: high security.

    Important
    • TLS 1.0, 1.1, 1.2, and 1.3 are supported. We recommend that you use TLS 1.2 or 1.3 for encryption. TLS 1.0 and 1.1 are earlier versions and may cause security risks.

    • Link SDK is configured with TLS 1.2 and TSL 1.3. If you use Link SDK, you do not need to configure the TLS protocol.

  • Non-encrypted Transport Layer Security (TLS) connection: low security. This feature will be phased out soon. We recommend that you do not use this feature.

    Important

    If you use a non-encrypted TLS connection, make sure that you understand data leak risks that may be caused by the connection and the corresponding consequences.

Topic specifications

For more information about how to define and classify topics, see Topics.

You can view system topics on the Device Details page of the IoT Platform console. For information about feature-specific topics, see the documentation of specific features.

Limits

After you register a device, you can use only one protocol to connect the device to IoT Platform. You cannot use multiple protocols for the same device.

Usage notes

IoT Platform provides various device SDKs. You can use the device SDKs to connect devices to IoT Platform over MQTT. For more information about how to obtain a Link SDK, see Download a Link SDK.

For more information about how to enable MQTT communication between devices and IoT Platform by using various communication protocols, see the following topics: