Community Blog How to Connect IoT Devices to Alibaba Cloud IoT Platform

How to Connect IoT Devices to Alibaba Cloud IoT Platform

MQTT is a message protocol which support communication between IoT devices and the IoT platform, in this tutorial you will get some information on how.

MQTT (Message Queuing Telemetry Transport) is a message protocol based on the TCP/IP protocol stack and supports asynchronous communication between the parties. MQTT separates the sender from the receiver in space and time, so it can be expanded in an unreliable network environment. Although it is called Message Queuing Telemetry Transport, it does not involve message queuing. It uses the publication and subscription model.

The MQTT protocol of the Alibaba Cloud IoT Platform does not support "will" messages, and the CONNECT message content parameters are as follows:


clientId, username, and password are generated by the device trituples (productKey, deviceName, deviceSecret) in accordance with the following rules:


Example of device code (Node.js) client.js

"dependencies": { "mqtt": "2.18.8" }
const crypto = require('crypto');
const mqtt = require('mqtt');
// The trituples of the device identity + region
const deviceConfig = {
    productKey: "replace",
    deviceName: "replace",
    deviceSecret: "replace",
    regionId: "cn-shanghai"
//Generate mqtt connection parameters from the trituples
const options = initMqttOptions(deviceConfig);
const url = `tcp://${deviceConfig.productKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuncs.com:1883`;

//2. Establish the connection
const client = mqtt.connect(url, options);

client.on('packetsend', function (packet){
  console.log('send '+packet.cmd+' packet =>',packet)

client.on('packetreceive', function (packet){
  console.log('receive '+packet.cmd+' packet =>',packet)

//Initialization of mqtt connection parameters for IoT Platform
function initMqttOptions(deviceConfig) {

    const params = {
        productKey: deviceConfig.productKey,
        deviceName: deviceConfig.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2),
    // CONNECT parameter
    const options = {
        keepalive: 60, //60s
        clean: false, //cleanSession maintains a persistent session
        protocolVersion: 4 //MQTT v3.1.1
    //1. Generate clientid, username, password
    options.password = signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=3,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;

  Generate a password based on HmacSha1
  Reference documents: https://help.aliyun.com/document_detail/73742.html?#h2-url-1
function signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // Sort by lexicographical order
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
    const contentStr = list.join('');
    return crypto.createHmac('sha1', deviceSecret)

For more information about MQTT protocol, you can go to Introduction to the MQTT Protocol and Alibaba Cloud's IoT Platform.

Related Documentation

Establish MQTT connections over TCP

This topic describes how to establish MQTT connections over TCP by using two methods: direct connection and connection after HTTPS verification.

Note: When you configure MQTT CONNECT packets:

  1. Do not use the same device certificate (ProductKey, DeviceName, and DeviceSecret) for multiple physical devices for connection authentication. This is because when a new device initiates authentication to IoT Platform, a device that is already connected to IoT Platform using the same device certificate will be brought offline. Later, the device which was brought offline will try to connect again, causing the newly connected device to be brought offline instead.
  2. In MQTT connection mode, open-source SDKs automatically reconnect to IoT Platform after they are brought offline. You can check the actions of devices by viewing the device logs.

Establish MQTT connections over WebSocket

IoT Platform supports MQTT over WebSocket. You can first use the WebSocket protocol to establish a connection, and then use the MQTT protocol to communicate on the WebSocket channel.

Using WebSocket has the following advantages:

  1. Allows browser-based applications to establish persistent connections to the server.
  2. Uses port 433, which allows messages to pass through most firewalls.

Related Blog Posts

How to Install and Secure Mosquitto MQTT Messaging Broker on Ubuntu 16.04

Mosquitto is a lightweight, open source and machine-to-machine messaging protocol for communication between "Internet of Things" devices such as ESP8266, Raspberry Pi, etc. It is designed for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. It is written in C language and suitable for use on all devices from low power single board computers to full servers. It is also ideal for mobile applications because of its small size, low power usage, minimized data packets, and efficient distribution of information to one or many receivers. Mosquitto is one of the most popular MQTT brokers due to its good community support, documentation and ease of installation.

Alibaba Cloud Message Queue vs. Message Service

There are very many message queues out there, from RocketMQ, RabbitMQ, Apache Kafka, ZeroMQ, MosquitoMQ, and many more. Many Cloud providers also offer managed message queues as a service and Alibaba Cloud has two of them namely the Message Queue and the Message Service.

With those many years of development, the Message Queue had more community experience and expertise behind it, but it also comes with more legacy methods and restrictions. For example, the Message Queue can only speak over TCP or MQTT protocols. This means you'll most likely require specific extensions enabled on your server to access these protocols. It also means you will most likely require an officially supported SDK to use it. Currently, Alibaba Cloud supports Python, PHP, .NET and Java programming languages. This means that both your producers and consumers must be written in one of those languages if you want official support.

The newer Message Service product differs from the Message Queue in that it can speak HTTP. This is a crucial differentiator implying that, so long as you can send a HTTP request, your application can use the Message Service. This opens the door to almost each and every programming language out there. There are official SDKs of course, but these are mostly to add synthetic sugar to make using it easier. Another decisive differentiator is that the Message Service has the ability to push out message to consumers instead of waiting for them to pull the messages out of the queue. The consumer can be any HTTP server, a browser via websockets, a mobile phone, an email address or even another Message Queue service!

Related Products

IoT Platform

Alibaba Cloud IoT Platform provides secure and reliable communication between devices and the IoT Platform which allows you to manage a large number of devices on a single IoT Platform and supports device access worldwide, from a variety of networks and providers that are all based on different protocols.

AlibabaMQ for Apache RocketMQ

AlibabaMQ for Apache RocketMQ is a distributed message queue service that supports reliable message-based asynchronous communication among microservices, distributed systems, and serverless applications.

0 0 0
Share on

Alibaba Clouder

2,600 posts | 754 followers