This topic demonstrates how to use the AMQP SDK for Node.js to connect to Alibaba Cloud IoT Platform and receive messages with server-side subscription.
Prerequisites
You have obtained a consumer group ID and subscribed to the required topic messages.
Manage AMQP consumer groups: You can use the default consumer group (DEFAULT_GROUP) in IoT Platform or create a consumer group.
Configure an AMQP server-side subscription: Subscribe to the required topic messages using a consumer group.
Set up the development environment
Node.js 8.0.0 or later is required.
Download and install the SDK
For the Node.js AMQP SDK, we recommend using the rhea library. Visit rhea to download the library and review its documentation.
This example uses the npm install rhea command to install the rhea library.
Procedure
-
On a Windows or Linux system, download and install Node.js. This topic uses a Windows 10 (64-bit) system and the node-v14.15.1-x64.msi installation package as an example.
-
After installation, open a command-line interface and run the following command to check the Node.js version.
node --versionA successful installation returns the version number:
v14.15.1 -
Create a JavaScript file, such as amqp.js, to hold the sample code.
Modify the parameters as described in the table below.
ImportantMake 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'); // Exposing your AccessKey pair can compromise your account security. // This code retrieves the AccessKey pair from environment variables for demonstration 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 documentation on how to connect an AMQP client. 'host': '${YourHost}', 'port': 5671, 'transport':'tls', 'reconnect':true, 'idle_time_out':60000, // The username format. For more information, see the documentation on how to connect an AMQP client. 'username':'${YourClientId}|authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=' + accessKey + ',iotInstanceId=${YourIotInstanceId},consumerGroupId=${YourConsumerGroupId}|', // Calculate the signature. For more information about the password format, see the documentation on how to connect an AMQP client. 'password': hmacSha1(accessSecret, 'authId='+ accessKey +'×tamp=1573489088171'), }); // Create a receiver link. var receiver = connection.open_receiver(); // The callback function for receiving messages pushed from the cloud. 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(); // Output the content. console.log(content); // Send an ACK. Do not include time-consuming operations 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 AMQP endpoint.
For the AMQP endpoint (
${YourHost}), see View and configure instance endpoints.username
'test |authMode=aksign,signMethod=hmacsha1,timestamp=1573489088171,authId=LTAI****************,iotInstanceId=iot-060a02ne,consumerGroupId=DEFAULT_GROUP|'
The authentication credentials for connecting to IoT Platform. This string contains the following parameters:
-
${YourClientId}: Replace with your client ID. You can define a custom ID up to 64 characters long. We recommend using a unique identifier, such as the UUID, MAC address, or IP address of the server that runs your AMQP client.After the AMQP client connects, you can view this parameter in the IoT Platform console. In the console for your instance, navigate to . On the tab, click View next to your consumer group. The Consumer Group Details page displays the client ID to help you distinguish between clients.
-
${YourAccessKeyId}and${YourAccessKeySecret}: Replace with your AccessKey ID and AccessKey Secret.To obtain them, log in to the IoT Platform console, move the pointer over your profile picture in the upper-right corner, and click AccessKey Management.
NoteIf you use a RAM user, you must attach the AliyunIOTFullAccess policy to the RAM user. Otherwise, the connection fails. For more information, see RAM user access.
-
${YourIotInstanceId}: Replace with your instance ID.Log in to the IoT Platform console. You can find the instance ID on the Overview tab of your instance.
ImportantIf the Overview tab is not available or your instance does not have an ID, remove the
iotInstanceId=${YourIotInstanceId}parameter from the username string. -
${YourConsumerGroupId}: Replace with your consumer group ID.To find your consumer group ID, log in to the IoT Platform console. In the console for your instance, navigate to .
password
hmacSha1('yourAccessKeySecret','authId=LTAI****************×tamp=1573489088171')
-
-
Open a command-line interface, navigate to the directory containing your amqp.js file, and run the following command to install the rhea library:
npm install rheaAfter the command completes, your project's root directory contains a
node_modulesfolder, youramqp.jsfile, and apackage-lock.jsonfile. -
In the CMD window, enter the following command to run the amqp.js code and start the AMQP client server.
node amqp.js
Example results
-
Success: On a successful connection, the client starts receiving messages and logs output similar to the following. This example shows temperature and humidity data reported by a device.
xxx>node iot_amqp.js {"deviceType":"CustomCategory","iotId":"xxx","requestId":"1613748030337","checkFailedData":{},"productKey":"xxx","gmtCreate":1613747903528, "deviceName":"xxx","items":{"Temperature":{"value":xxx,"time":1613747903526},"Humidity":{"value":23,"time":1613747903526}}} {"deviceType":"CustomCategory","iotId":"xxx","requestId":"1613729851729","checkFailedData":{},"productKey":"xxx","gmtCreate":1613729721715, "deviceName":"xxx","items":{"Temperature":{"value":17,"time":1613729721715},"Humidity":{"value":20,"time":1613729721715}}} -
Failure: If the connection fails, an error message similar to the following appears.
Use the error log to check your code and network settings. Resolve the issue and run the code again.
>node iot_amqp.js [connection-1] disconnected Error: getaddrinfo ENOTFOUND iot-xxx.b.aliyuncs.com at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26) { errno: -3008, code: 'ENOTFOUND', syscall: 'getaddrinfo', hostname: 'ixxx.iyuncs.com' }
References
For more information about error codes for server-side subscription messages, see Message-related error codes.