This article describes how to use Advanced Message Queuing Protocol (AMQP) SDK for Node.js to connect a client with IoT Platform and receive messages from IoT Platform.

Development environment

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

Download and install the SDK

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

In this example, run the npm install rhea command to download the rhea library.

Sample code

  1. Create a JavaScript file such as amqp.js on your PC to store the Node.js sample code.
    When you use the sample code, specify the parameters based on the parameter descriptions in the following table.
    const container = require('rhea');
    const crypto = require('crypto');
    
    // Creates a connection. 
    var connection = container.connect({
        // The endpoint. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
        'host': '${YourHost}',
        'port': 5671,
        'transport':'tls',
        'reconnect':true,
        'idle_time_out':60000,
        // The structure of the userName parameter. For more information, see the "Connect an AMQP client to IoT Platform" topic. 
        'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=${YourAccessKeyId},iotInstanceId=${YourIotInstanceId},consumerGroupId=${YourConsumerGroupId}|', 
        // Calculates a signature. For more information about how to specify the password parameter, see the "Connect an AMQP client to IoT Platform" topic. 
        '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');
    }
    Parameter Example Descripition
    host 233***.iot-amqp.cn-shanghai.aliyuncs.com The AMQP endpoint.

    ${YourHost} format: ${uid}.iot-amqp.${YourRegionId}.aliyuncs.com.

    • ${uid}: Replace this variable with the ID of your Alibaba Cloud account. You can log on to the IoT Platform console, and move the pointer over the profile picture to view the account ID.
    • ${YourRegionId}: Replace this variable with the ID of the region where your IoT Platform device resides. For more information about region IDs, see Regions and zones.
    username 'test |authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=LTAI4GFGQvKuqHJhFajiW5j3,iotInstanceId=,consumerGroupId=DEFAULT_GROUP|' The authentication information that is required to connect with IoT Platform. The field value varies based on the following operation types:
    • ${YourClientId}: Replace this variable with your client ID. You can specify a client ID as needed. The client ID cannot exceed 64 characters in length. We recommend that you use a unique identifier, such as the UUID, MAC address, or IP address of the client.

      Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups, and click View next to the required consumer group. The Consumer Group Details page shows this parameter. This parameter allows you to identify clients.

    • ${YourAccessKeyId} and ${YourAccessKeySecret}: Replace the variables with your AccessKey ID and AccessKey secret.

      Log on to the IoT Platform console, move the pointer over the profile picture, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.

      Note If you use a RAM user, you must attach the AliyunIOTFullAccess permission policy to the user. This policy allows the user to manage IoT Platform resources. Otherwise, the connection with IoT Platform fails. For more information about how to authorize a RAM user, see RAM user access.
    • ${YourIotInstanceId}: Replace this variable with your instance ID. If you use a public instance, delete ${YourIotInstanceId}.
    • ${YourConsumerGroupId}: Replace this variable with your consumer group ID.

      Log on to the IoT Platform console. Choose Rules > Server-side Subscription > Consumer Groups and view the ID of the required consumer group.

    password hmacSha1('iMS8ZhCDd***', 'authId=LTAI4GFGQ***&timestamp=1573489088171')
  2. Open Command Prompt and run the cd command to go to the amqp.js file. Then, run the npm command to download the rhea library. The following figure shows the downloaded file.
    npm install rhea
    Directory
  3. Run the following command in Command Prompt to run the amqp.js file. This way, the AMQP client is started.
    node amqp.js

Sample results

  • Sample success result: After you run the code, the following log data may be returned. The data indicates that the AMQP client is connected to IoT Platform and can receive messages.Success
  • Sample failure result:

    You can check the code or network environment based on logs, solve the problem, and then run the code again.

    Failure