1. 阿里云IoT控制台配置
1.1 开通阿里云IoT物联网套件
IoT物联网套件官网地址
1.2 创建高级版产品,选择数据透传
1.3 添加产品属性定义
1.4 自定义payload二进制格式
2.设备端代码
2.1 package.json引入sdk
2.2 应用程序代码
1.1 开通阿里云IoT物联网套件
IoT物联网套件官网地址
1.2 创建高级版产品,选择数据透传
![](https://i-blog.csdnimg.cn/blog_migrate/8a7119560587be67ef31ee275f178cd3.png)
1.3 添加产品属性定义
属性名 | 标识符 | 数据类型 |
温度 | temperature | float |
湿度 | humidity | float |
![](https://i-blog.csdnimg.cn/blog_migrate/a4ed0153d04b8a3160742d1e51cb50a5.png)
1.4 自定义payload二进制格式
1位 | 2-5位 | 6-9位 | 9-13位 |
00 | 5b0232e1 | 41200000 | 42b00000 |
command | requestId | temperature | humidity |
2.设备端代码
2.1 package.json引入sdk
- {
- "name": "aliyun-iot",
- "dependencies": {
- "aliyun-iot-mqtt": "^0.0.4"
- },
- "author": "wongxming",
- "license": "MIT"
- }
2.2 应用程序代码
- /**
- * node iot_raw_data.js
- */
- const mqtt = require('aliyun-iot-mqtt');
- const COMMAND_REPORT = 0x00;
- //设备属性
- const options = {
- productKey: "替换自己productKey",
- deviceName: "替换自己deviceName",
- deviceSecret: "替换自己deviceSecret",
- regionId: "cn-shanghai"
- };
- //建立连接
- const client = mqtt.getAliyunIotMqttClient(options);
- //属性上报的Topic
- const topic = `/sys/${options.productKey}/${options.deviceName}/thing/model/up_raw`;
- setInterval(function() {
- //发布数据到topic
- client.publish(topic, getPostData());
- }, 5 * 1000);
- function getPostData() {
- var temperature = Math.floor((Math.random() * 20) + 10)
- var humidity = Math.floor((Math.random() * 80) + 20)
- var payloadArray = [];
- /**
- * 按照自定义协议格式拼接 raw data
- * 00|5b0232e1|41200000|42b00000
- * command(1)|requestId(4)|temperature(4)|humidity(4)
- */
- //command字段
- payloadArray = payloadArray.concat(buffer_uint8(COMMAND_REPORT));
- // id
- payloadArray = payloadArray.concat(buffer_int32(parseInt(new Date().getTime() / 1000)));
- // 属性'temperature'的值
- payloadArray = payloadArray.concat(buffer_float32(temperature));
- // 属性'humidity'的值
- payloadArray = payloadArray.concat(buffer_float32(humidity));
- return new Buffer(payloadArray);
- }
- //uint8
- function buffer_uint8(value) {
- var uint8Array = new Uint8Array(1);
- var dv = new DataView(uint8Array.buffer, 0);
- dv.setUint8(0, value);
- return [].slice.call(uint8Array);
- }
- //int32
- function buffer_int32(value) {
- var uint8Array = new Uint8Array(4);
- var dv = new DataView(uint8Array.buffer, 0);
- dv.setInt32(0, value);
- return [].slice.call(uint8Array);
- }
- //float32
- function buffer_float32(value) {
- var uint8Array = new Uint8Array(4);
- var dv = new DataView(uint8Array.buffer, 0);
- dv.setFloat32(0, value);
- return [].slice.call(uint8Array);
- }
3. 云端数据解析脚本配置