《IoT物联网技术》
2018-11-16
2564浏览量
使用个人淘宝账号或手机号,开通阿里云账号,并通过__实名认证(可以用支付宝认证)__
产品官网 https://www.aliyun.com/product/iot
Nodejs安装 https://nodejs.org/en/download/
编辑器 sublimeText/nodepad++/vscode
MQTT lib https://www.npmjs.com/package/mqtt
添加产品属性定义
属性名 | 标识符 | 数据类型 | 范围 |
---|---|---|---|
温度 | temperature | float | -50~100 |
湿度 | humidity | float | 0~100 |
物模型对应属性上报topic
/sys/替换为productKey/替换为deviceName/thing/event/property/post
物模型对应的属性上报payload
{
id: 123452452,
params: {
temperature: 26.2,
humidity: 60.4
},
method: "thing.event.property.post"
}
我们以nodejs程序来模拟设备,建立连接,上报数据。
1.创建文件夹 aliyun-iot-demo-nodejs
2.进入文件夹,创建package.json文件,添加内容
3.执行npm install命令,安装sdk
4.创建thermometer.js文件,添加内容
5.执行node thermometer.js命令
{
"name": "aliyun-iot",
"dependencies": {
"mqtt": "2.18.8"
},
"author": "wongxming",
"license": "MIT"
}
在aliyun-iot-demo-nodejs文件夹下,执行命令
$ npm install
/**
"dependencies": { "mqtt": "2.18.8" }
*/
const crypto = require('crypto');
const mqtt = require('mqtt');
//设备身份三元组+区域
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`;
//建立连接
const client = mqtt.connect(url,options);
//属性上报的Topic
const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;
setInterval(function() {
//发布数据到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);
}
/*
生成基于HmacSha1的password
参考文档:https://help.aliyun.com/document_detail/73742.html?#h2-url-1
*/
function signHmacSha1(options, deviceSecret) {
let keys = Object.keys(options).sort();
// 按字典序排序
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');
}
设备配置文件
{
"productKey": "替换productKey",
"deviceName": "替换deviceName",
"deviceSecret": "替换deviceSecret",
"regionId": "cn-shanghai"
}
$ node thermometer.js
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
集结各类场景实战经验,助你开发运维畅行无忧