Nodejs device is connected to alicloud IoT platform

Keywords: Javascript Attribute JSON SDK npm

1. Preparation

1.1 register alicloud account

Use personal Taobao account or cell phone number to open the account of Ali cloud, and pass the real name authentication (can be certified by Alipay).

1.2 free IoT Suite

Product official website https://www.aliyun.com/product/iot

1.3 software environment

Nodejs installation https://nodejs.org/en/download/
Editor sublimeText/nodepad++/vscode
MQTT lib https://www.npmjs.com/package/mqtt

2. Development steps

2.1 cloud development

1) create advanced products

2) function definition, adding attributes to product model

Add product attribute definition

Attribute name identifier data type Range
temperature temperature float -50~100
humidity humidity float 0~100

Report the corresponding attribute of object model to topic

/sys / replace with productKey / replace with deviceName/thing/event/property/post

Attribute corresponding to object model reported to payload

{
    id: 123452452,
    params: {
        temperature: 26.2,
        humidity: 60.4
    },
    method: "thing.event.property.post"
}

3) device management > register devices to obtain identity triples

2.2 equipment end development

We use nodejs program to simulate the device, establish the connection and report the data.

1. Create the folder aliyun IOT demo nodejs
 2. Enter the folder, create the package.json file, and add content
 3. Execute npm install command to install sdk
 4. Create the thermometer.js file and add content
 5. Execute the node thermometer.js command

1) package.json add Alibaba cloud IoT suite sdk dependency

{
  "name": "aliyun-iot",
  "dependencies": {
    "mqtt": "2.18.8"
  },
  "author": "wongxming",
  "license": "MIT"
}

2) download and install SDK

In the aliyun IOT demo nodejs folder, execute the command

$ npm install

3) application directory structure

4) code of thermometer.js

/**
"dependencies": { "mqtt": "2.18.8" }
*/
const crypto = require('crypto');
const mqtt = require('mqtt');
//Device identity triple + region
const deviceConfig = require("./iot-device-config.json");

const options = {
    productKey: deviceConfig.productKey,
    deviceName: deviceConfig.deviceName,
    timestamp: Date.now(),
    clientId: Math.random().toString(36).substr(2)
}

options.password = signHmacSha1(options, deviceConfig.deviceSecret);
options.clientId = `${options.clientId}|securemode=3,signmethod=hmacsha1,timestamp=${options.timestamp}|`;
options.username = `${options.deviceName}&${options.productKey}`;

const url = `tcp://${deviceConfig.productKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuncs.com:1883`;
//Establish connection
const client = mqtt.connect(url,options);

//Topic reported by attribute
const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;
setInterval(function() {
    //Publish data to topic
    client.publish(topic, getPostData());
}, 5 * 1000);


function getPostData(){
    const payloadJson = {
        id: Date.now(),
        params: {
            temperature: Math.floor((Math.random() * 20) + 10),
            humidity: Math.floor((Math.random() * 40) + 60)
        },
        method: "thing.event.property.post"
    }

    console.log("===postData topic=" + topic)
    console.log(payloadJson)

    return JSON.stringify(payloadJson);
}

/*
  Generate password based on HmacSha1
  Reference document: https://help.aliyun.com/document'detail/73742.html?'h2-url-1
*/
function signHmacSha1(options, deviceSecret) {

    let keys = Object.keys(options).sort();
    // Sort by dictionary order
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${options[key]}`);
    });
    const contentStr = list.join('');
    return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');
}

Device profile

{
    "productKey": "replace productKey",
    "deviceName": "replace deviceName",
    "deviceSecret": "replace deviceSecret",
    "regionId": "cn-shanghai"
}

3. Start operation

3.1 equipment startup

$ node thermometer.js

3.2 check the operation status of the device in the cloud

Posted by paradigmapc on Sun, 08 Dec 2019 19:48:06 -0800