All Products
Search
Document Center

IoT Platform:MQTT protocol

Last Updated:May 18, 2023

Message Queuing Telemetry Transport (MQTT) is an asynchronous communication protocol 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 versions

IoT Platform supports device connections over MQTT. Supported MQTT versions include 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 valid.
  • Supports the synchronous 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.

IoT Platform supports the following new features of MQTT 5.0:

FeatureDescription
Configure the Clean Start feature and the session expiry interval.
  • 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);
Specify a message expiration interval. 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 quality of service (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);
Configure subscription parameters. 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 messages that it published.
    • false: The client receives 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 parties.
    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 Retaion 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});
Specify a retained message
// Create a message. 
String content = "Hello World";
byte[] payload = content.getBytes();
MqttMessage message = new MqttMessage(payload);
// Specify the message as the retained message. 
message.setRetained(true);

// Publishes messages to a topic. 
MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
mqttClient.publish(topic, message);
Specify a will message.
// Create a 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);
Specify the maximum length of messages on clients and servers to filter messages.
MqttConnectionOptions connOpts = new MqttConnectionOptions();
connOpts.setMaximumPacketSize(1024L);
Specify the maximum number of QoS 1 messages per second.
MqttConnectionOptions connOpts = new MqttConnectionOptions();
connOpts.setReceiveMaximum(5);
Use the UserProperty parameter to specify a list of properties. This parameter is used to transmit additional property data. Each property consists of a key and a value.
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. Each key cannot start with an underscore (_). The total length of a key and a value cannot exceed 128 characters.
Add the ResponseTopic and CorrelationData parameters to enable bidirectional communication in a mode that is similar to HTTP-based request/response.

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.
Add more response codes that can be used by devices to identify request statuses and issues.

For more information, see Troubleshooting.

Scale down message communication topics to integers to reduce the size of MQTT messages. This saves bandwidth resources. N/A
Use shared subscription.

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

  • $share: Every shared subscription topic is prefixed with $share.
  • ${ShareName}: a string that can contain only letters, digits, and underscores (_).

    ${ShareName} indicates the 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. It can contain only 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

  • Transport Layer Security (TLS)-based TCP 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.
  • IoT Internet Device ID-based TCP connection (IoT Internet Device ID is a chip-level encryption service): high security.
  • Unencrypted TCP connection: low security. The feature will be phased out soon. We recommend that you do not use the feature.

Topic specifications

For more information about the definitions and types of 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 about 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 device SDK, see Download device SDKs.

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