本次实战设备模型为项目模板中“空气盒子”,在标准功能中新增“当前温度”、“当前湿度”为设备属性,故障上报为设备事件,如下图所示:
    空气盒子 项目开发 (Javascript SDK) - 图1
    项目创建过程不再赘述。

    node.js文件如下:

    1. const aliyunIot = require('aliyun-iot-device-sdk');
    2. const device = aliyunIot.device({
    3. productKey: "xxxxxxxxx", //填写模型下测试设备三元组
    4. deviceName: "xxxxxxxxx",
    5. deviceSecret: "xxxxxxxxxxxx"
    6. });
    7. //进行与平台连接,并执行连接后的业务循环
    8. device.on('connect', () => {
    9. console.log('connect succesfully!');
    10. const interval = setInterval(() => {
    11. //生成随机温度t和湿度h,Math.random()生成0-1之间随机数
    12. const t = Math.floor((Math.random() -0.5)*5+20);
    13. const h = Math.floor((Math.random() -0.5)*10+70);
    14. console.log(`Post current temperature: ${t}`);
    15. console.log(`Post current humidity: ${h}`);
    16. device.postProps({
    17. CurrentTemperature: t,
    18. CurrentHumidity: h
    19. });
    20. // 以下代码实现事件上报
    21. // console.log('Report filterChange event');
    22. // device.postEvent('Error', {
    23. // ErrorCode: 0
    24. // });
    25. }, 5000);
    26. });
    27. device.on('error', (err) => {
    28. console.log(err);
    29. });

    文件通过require将aliyun-iot-device-sdk导入进之后,进行设备参数初始化,得到device实例对象,通过device.on()进行平台连接,在连接成功()=>{····}回调函数中进行业务逻辑处理,本demo例程使用Math.random()方法随机生成的温湿度数据,通过device.postProps()方法进行5秒钟的属性周期上报。示例代码中注释了事件上报功能,通过device.postEvent()进行事件上报。
    将设备三元组内容更换为设备模型下真实设备,在终端中执行node index.js开始运行Node.js SDK脚本程序,在终端中将会打印设备属性上报消息。
    空气盒子 项目开发 (Javascript SDK) - 图2
    至此,我们通过Node.js SDK模拟传感器数据完成了“空气盒子”的数据上报,树莓派在Node.js环境下支持调用GPIO外接各类传感器,开发者可以使用Node.js SDK读取真实传感器温湿度数据,完成数据采集上报。