All Products
Search
Document Center

IoT Platform:Connect a client to IoT Platform by using the SDK for Node.js

Last Updated:Oct 22, 2023

This topic describes how to use the SDK for Node.js to connect an Advanced Message Queuing Protocol (AMQP) client to Alibaba Cloud IoT Platform and receive messages from IoT Platform by using the server-side subscription feature.

Prerequisites

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

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, visit rhea

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

Procedure

  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 installed, the following version number appears:

    v14.15.1
  3. Create a JavaScript file such as amqp.js on your computer to store the Node.js sample code.

    You can configure the parameters in the sample code based on the parameter description in the following table.

    Important

    Make sure that you specify valid parameter values. Otherwise, the AMQP client fails to connect to IoT Platform.

    const container = require('rhea');
    const crypto = require('crypto');
    
    // If you hard-code the AccessKey pair in the project code, the AccessKey pair may be disclosed if the project code is leaked. In this case, the resources within your account become insecure. The following sample code provides an example on how to obtain the AccessKey pair from environment variables. This example is for reference only.
    var accessKey = process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'];
    var accessSecret = process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'];
    
    // Create 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=' + accessKey + ',iotInstanceId=${YourIotInstanceId},consumerGroupId=${YourConsumerGroupId}|', 
        // Calculate a signature. For more information about how to construct the password, see the "Connect an AMQP client to IoT Platform" topic. 
        'password': hmacSha1(accessSecret, 'authId='+ accessKey +'&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 message. 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

    iot-cn-***.amqp.iothub.aliyuncs.com

    The endpoint that the AMQP client uses to connect to IoT Platform.

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

    username

    'test |authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=LTAI***vKu****,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 custom client ID based on your business requirements. The client ID cannot exceed 64 characters in length. We recommend that you use a unique identifier as the client ID, such as the UUID, MAC address, or IP address of the server on which the client runs.

      After the AMQP client is connected to IoT Platform and started, perform the following steps to view the details of the client: Log on to the IoT Platform console and click the card of the instance that you want to manage. In the left-side navigation pane, choose Message Forwarding > Server-side Subscription. On the Consumer Groups tab, 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 Status tab. You can use client IDs to identify clients with ease.

    • ${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 in the upper-right corner, and then click AccessKey Management to obtain the AccessKey ID and AccessKey secret.

      Note

      If you use a Resource Access Management (RAM) user, you must attach the AliyunIOTFullAccess policy to the RAM user. This policy allows the RAM user to manage IoT Platform resources. Otherwise, the connection to IoT Platform fails. For more information, see Access IoT Platform as a RAM user.

    • ${YourIotInstanceId}: Replace this variable with the ID of your instance.

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

      Important

      If the Overview tab is not displayed or your instance does not have an ID, delete the ${YourIotInstanceId} variable.

    • ${YourConsumerGroupId}: Replace this variable with the ID of your consumer group.

      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 manage. In the left-side navigation pane, choose Message Forwarding > Server-side Subscription. 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 in which the amqp.js file is stored. Then, run the npm command to download the rhea library. The following figure shows the directory structure after the library is downloaded.

    npm install rhea
    文件目录
  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

  • If information similar to the following output is displayed, the AMQP client is connected to IoT Platform and can receive messages.成功

  • If information similar to the following output is displayed, the AMQP client fails to connect to IoT Platform.

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

    失败

References

For more information about the error codes that are related to the server-side subscription feature, see the Error codes that are related to messages section of the "IoT Platform logs" topic.