Nodejs設備接入阿里雲IoT物聯網平臺

1. 準備工做

1.1 註冊阿里雲帳號

使用我的淘寶帳號或手機號,開通阿里雲帳號,並經過支付寶實名認證javascript

1.2 免費開通IoT物聯網套件

產品官網 www.aliyun.com/product/iothtml

image.png | left | 528x331

1.3 軟件環境

Nodejs安裝 nodejs.orgjava

2. 開發步驟

2.1 IoT雲端開發

1)建立高級版產品node

image.png | left | 635x325

2)功能定義,添加產品屬性npm

image.png | left | 636x281

3)註冊設備,得到身份三元組json

image.png | left | 633x313

2.2 設備端開發

咱們用nodejs程序來模擬設備,創建鏈接,上報數據。bash

1)建立設備端項目

建立文件夾 iot-demo 建立2個文件 package.json 和 device.jsdom

2)package.json文件

添加阿里雲IoT套件sdk依賴tcp

{
    "name": "aliyun-iot-demo",
    "dependencies": {
        "mqtt": "2.18.8"
    }
}
複製代碼

3)npm下載安裝IoT套件SDK

$ npm install
複製代碼

4)device.js 應用程序代碼post

/** "dependencies": { "mqtt": "2.18.8" } */
const crypto = require('crypto');
const mqtt = require('mqtt');
//設備身份三元組+區域
const deviceConfig = {
    productKey: "替換",
    deviceName: "替換",
    deviceSecret: "替換",
    regionId: "cn-shanghai"
};
//根據三元組生成mqtt鏈接參數
const options = initMqttOptions(deviceConfig);
const url = `tcp://${deviceConfig.productKey}.iot-as-mqtt.${deviceConfig.regionId}.aliyuncs.com:1883`;

//2.創建鏈接
const client = mqtt.connect(url, options);

//3.屬性數據上報
const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;
setInterval(function() {
    //發佈數據到topic
    client.publish(topic, getPostData());
}, 5 * 1000);

//4.訂閱主題,接收指令
const subTopic = `/${deviceConfig.productKey}/${deviceConfig.deviceName}/control`;
client.subscribe(subTopic)
client.on('message', function(topic, message) {
    console.log("topic " + topic)
    console.log("message " + message)
})

//IoT平臺mqtt鏈接參數初始化
function initMqttOptions(deviceConfig) {

    const params = {
        productKey: deviceConfig.productKey,
        deviceName: deviceConfig.deviceName,
        timestamp: Date.now(),
        clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT參數
    const options = {
        keepalive: 60, //60s
        clean: false, //cleanSession保持持久會話
        protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成clientId,username,password
    options.password = signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=3,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;
}

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

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

    return JSON.stringify(payloadJson);
}

/* 生成基於HmacSha1的password 參考文檔:https://help.aliyun.com/document_detail/73742.html?#h2-url-1 */
function signHmacSha1(params, deviceSecret) {

    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
        list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');
}
複製代碼

3.設備運行

3.1 設備啓動

image.png | left | 453x108

3.2 IoT控制檯查看設備運行狀態

image.png | left | 571.4285714285714x400

至此,完成了物聯網設備接入阿里雲IoT物聯網雲平臺的開發實踐

更多IoT物聯網技術,敬請關注公共帳號

iot-tech-weixin.png | center | 225x224
相關文章
相關標籤/搜索