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

Prerequisites

The ID of the consumer group that has subscribed to the messages of a topic is obtained.

Prepare the development environment

You can use Node.js 8.0.0 or later.

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. Download and install Node.js on the Windows or Linux operating system. In this example, Windows 10 (64-bit) is used. Download the node-v14.15.1-x64.msi installation package.
  2. Open a Command Prompt window and run the following command to view the node version:
    node --version
    If the package is decompressed, the following version number appears:
    v14.15.1
  3. Create a JavaScript file such as amqp.js on your PC to store the Node.js sample code.
    When you use the sample code, configure the parameters based on the parameter descriptions in the following table.
    const container = require('rhea');
    const crypto = require('crypto');
    
    // Create 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. 
        'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=${YourAccessKeyId},iotInstanceId=${YourIotInstanceId},consumerGroupId=${YourConsumerGroupId}|', 
        // Calculate a signature. For more information about how to configure the password parameter, see Connect an AMQP client to 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();
    
        // Return message content. 
        console.log(content);
    
        // Send an ACK packet. Do not implement 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');
    }
    Parameter Example Description
    host 198426864******.iot-amqp.cn-shanghai.aliyuncs.com The AMQP endpoint.

    For more information about the endpoints that you can specify for the ${YourHost} variable, see View the endpoint of an instance.

    username 'test |authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=LTAI4***QvKu****,iotInstanceId=,consumerGroupId=DEFAULT_GROUP|' The authentication information that is required to connect to IoT Platform. Description:
    • ${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 and click the card of the instance that you want to manage. Choose Rules Engine > Server-side Subscription > Consumer Groups. Find the consumer group that you want to manage and click View in the Actions column. The ID of each client is displayed on the Consumer Group Details page. You can use client IDs to efficiently 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 RAM user. This policy allows the RAM 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.

      Log on to the IoT Platform console. On the Overview page, view the ID of the instance.

      Notice If no Overview page or ID is generated for your instance, delete ${YourIotInstanceId}.
    • ${YourConsumerGroupId}: Replace this variable with your consumer group ID.

      To view the ID of the consumer group, perform the following steps: Log on to the IoT Platform console and click the card of the instance that you want to manange. Choose Rules Engine > Server-side Subscription > Consumer Groups. The ID is displayed on the Consumer Groups tab.

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

Sample results

  • Sample success result: Success
  • Sample failure result:

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

    Failed

References

For more information about the error codes that are related to server-side subscription, see Message-related error codes.