After you complete the configuration in the IoT Platform console, you can begin device-side development. This topic describes how to use a Node.js script to simulate device behavior, establish an MQTT connection, and report data.
Procedure
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.
Open a Command Prompt window and run the following command to view the node version:
node --versionIf the package is installed, the following version number appears:
v14.15.1Create a JavaScript file, such as `iot_device.js`, on your local computer to store the Node.js sample code.
The following sample code is provided:
// Import the dependent MQTT library, or implement it yourself. const mqtt = require('aliyun-iot-mqtt'); // Device identity. var options = { productKey: "Your ProductKey", deviceName: "Your DeviceName", deviceSecret: "Your DeviceSecret", host: "iot-cn-***.mqtt.iothub.aliyuncs.com" }; // 1. Establish a connection. const client = mqtt.getAliyunIotMqttClient(options); // 2. The device receives instruction data from the cloud. client.on('message', function(topic, message) { console.log("topic " + topic) console.log("message " + message) }) // 3. Simulate reporting data from the device (raw message). setInterval(function() { client.publish(`/${options.productKey}/${options.deviceName}/user/data`, getPostData(),{qos:1}); }, 1000); // Simulate the original message format of the device. function getPostData() { let payload = { temperature:Math.floor((Math.random() * 20) + 10) }; console.log("payload=[ " + payload+" ]") return JSON.stringify(payload); }Configure the device connection parameters.
Parameter
Example
Description
productKey
a16c*****
The device certificate information that you saved after you added the device.
You can find this on the Device Details page in the IoT Platform console.
deviceName
device1
deviceSecret
b2e6e4f102458d84***
host
iot-cn-***.mqtt.iothub.aliyuncs.com
The domain name for MQTT device connection. For more information, see View and configure instance endpoints.
Open a Command Prompt window. Run the
cdcommand to navigate to the directory that contains the iot_device.js file. In that directory, run thenpmcommand to download the MQTT library for the Alibaba Cloud IoT Platform. The downloaded MQTT library files are shown in the following figure.npm install aliyun-iot-mqtt -S