This article describes how to use the Advanced Message Queuing Protocol (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 for Node.js

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

Add a dependency

Add the following dependency to the package.json file:

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

Sample code

For 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');

// Creates a connection.
var connection = container.connect({
    // The endpoint. For more information, see Connect an AMQP client to IoT Platform.
    'host': '${YourHost}',
    'port': 5671,
    'transport':'tls',
    'reconnect':true,
    'idle_time_out':60000,
    // The structure of the userName parameter. For more information, see Connect an AMQP client to IoT Platform. If you use a purchased instance, you must specify an instance ID for the iotInstanceId parameter. If you use a public instance, remove ${YourIotInstanceId} from the iotInstanceId=${YourIotInstanceId} statement.
    'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=${YourAccessKeyId},iotInstanceId=${YourIotInstanceId},consumerGroupId=${YourConsumerGroupId}|', 
    // The structure of the signature and the password parameters. For more information, see Connect an AMQP client to IoT Platform.
    'password': hmacSha1('${YourAccessKeySecret}', 'authId=${YourAccessKeyId}&timestamp=1573489088171'),
});

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

    // Returns message content.
    console.log(content);

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

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