陈拓 [email protected] 2019/12/14-2020/01/02
上面的内容见《树莓派连接阿里云物联网平台-属性(nodejs)》https://blog.csdn.net/chentuo2000/article/details/103705694
上面的内容见《树莓派连接阿里云物联网平台-服务(nodejs)》https://blog.csdn.net/chentuo2000/article/details/103754860
上面的内容见《树莓派连接阿里云物联网平台-订阅(nodejs)》https://blog.csdn.net/chentuo2000/article/details/103769449
先看参考文档《阿里云物联网平台基本设置》。
事件的标识符:TemperatureSensorExceptional
查看输出参数:
输出参数标识符:TemperatureExceptional
pi@raspberrypi:~/PiAliNode/alibabacloud-iot-device-sdk/examples/quickstart $ nano index.js
在setInterval函数中添加事件上报代码:
setInterval(() => {
var data = fs.readFileSync('/sys/bus/w1/devices/28-000004d627c6/w1_slave', $
var i = data.indexOf('t=');
var temp = data.substring(i+2, data.length)/1000;
const params = {
RoomTemp: temp
};
console.log(`Post properties: ${JSON.stringify(params)}`);
device.postProps(
params,
(res) => {
console.log(`postProps:`,res);
});
if (temp > 30) {
device.postEvent("TemperatureSensorExceptional", {
TemperatureExceptional: temp,
}, (res) => {
console.log(`postEvent:${res}`);
});
}
}, 30000);
const Gpio = require('/home/pi/node_modules/onoff').Gpio;
const led = new Gpio(17, 'out');
const fs = require('fs');
const iot = require('alibabacloud-iot-device-sdk');
const deviceConfig = require('./device_id_password.json');
const device = iot.device(deviceConfig);
device.on('connect', () => {
console.log('Connect successfully!');
console.log('Post properties every 30 seconds...');
device.subscribe('/a14U7TTbz9q/BedroomTemp/user/get');
setInterval(() => {
var data = fs.readFileSync('/sys/bus/w1/devices/28-000004d627c6/w1_slave', 'utf8');
var i = data.indexOf('t=');
var temp = data.substring(i+2, data.length)/1000;
const params = {
RoomTemp: temp
};
console.log(`Post properties: ${JSON.stringify(params)}`);
device.postProps(
params,
(res) => {
console.log(`postProps:`,res);
});
if (temp > 30) {
device.postEvent("TemperatureSensorExceptional", {
TemperatureExceptional: temp,
}, (res) => {
console.log(`postEvent:${res}`);
});
}
}, 30000);
device.onService('property/set', (data) => {
console.log('Received a message: ', JSON.stringify(data));
});
});
device.onService('switch', function (res,reply) {
console.log('^onService',res);
paramsStr = JSON.stringify(res.params)
var stateInfo
if (paramsStr.indexOf('on') > 0) {
led.writeSync(1)
stateInfo = {state:'led on'}
} else {
led.writeSync(0)
stateInfo = {state:'led off'}
}
reply({
"code": 200,
"data": stateInfo
});
});
device.on('message', (topic, payload) => {
console.log('topic:',topic);
if(payload){
console.log('payload',payload.toString());
}
});
device.on('error', err => {
console.error('err: ', err);
});