使用我的淘寶帳號或手機號,開通阿里雲帳號,並經過支付寶實名認證javascript
產品官網 www.aliyun.com/product/iothtml
Nodejs安裝 nodejs.orgjava
1)建立高級版產品node
2)功能定義,添加產品屬性npm
3)註冊設備,得到身份三元組json
咱們用nodejs程序來模擬設備,創建鏈接,上報數據。bash
建立文件夾 iot-demo 建立2個文件 package.json 和 device.jsdom
添加阿里雲IoT套件sdk依賴tcp
{
"name": "aliyun-iot-demo",
"dependencies": {
"mqtt": "2.18.8"
}
}
複製代碼
$ 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');
}
複製代碼
至此,完成了物聯網設備接入阿里雲IoT物聯網雲平臺的開發實踐