This article describes how to use the AMQP SDK for Node.js to connect a client to Alibaba Cloud IoT Platform and receive messages from IoT Platform.

Development environment

Node.js 8.0.0 or later is used in this example.

Download the SDK

We recommend that you use the rhea library. To download the library and view its instructions, visit rhea

Add the dependency

Add the following dependency to the package.json file:

"dependencies": {
    "rhea": "^1.0.12"
 }

Sample code

For more more information about the parameters in the following sample code, see Connect an AMQP client to IoT Platform.

const container = require('rhea');
const crypto = require('crypto');

// Establish a connection.
var connection = container.connect({
    'host': '${uid}.iot-amqp.${regionId}.aliyuncs.com',
    'port': 5671,
    'transport':'tls',
    'reconnect':true,
    'idle_time_out':60000,
    // Configure the userName parameter as required by Alibaba Cloud IoT Platform. iotInstanceId: Specify the instance ID if you are using a purchased instance. If you are using a public instance, enter an empty string "".
    'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=${YourAccessKeyId},iotInstanceId=${YourIotInstanceId},consumerGroupId=${YourConsumerGroupId}|', 
    // Calculate the signature and configure the password as required by Alibaba Cloud IoT Platform.
    'password': hmacSha1('${YourAccessKeySecret}', 'authId=${YourAccessKeyID}&timestamp=1573489088171'),
});

// Create a receiver link.
var receiver = connection.open_receiver();

// The callback function that is called when messages are received from IoT Platform.
container.on('message', function (context) {
    var msg = context.message;
    var messageId = msg.message_id;
    var topic = msg.application_properties.topic;
    var content = Buffer.from(msg.body.content).toString();

    // Send an ACK packet. Do not implement a time-consuming logic in the callback function.
    context.delivery.accept();
});

// Calculate the password signature.
function hmacSha1(key, context) {
    return Buffer.from(crypto.createHmac('sha1', key).update(context).digest())
        .toString('base64');
}