我正在使用onoff模块的watch方法来观察输入的状态,回调函数将被调用用于输入的任何更改(从0到1或从1到0),这就是我想要的。
问题是,当我第一次运行应用程序时,如果主打开(inputMain为1)或主关闭(inputMain为0),则回调函数不会执行,因为输入的值没有变化。因此,如果main打开,我不能调用main()函数,直到它关闭然后打开,这个问题只发生在我第一次运行应用程序时。
我如何绕过这个?有更好的接力棒处理方法吗?
var GPIO = require('onoff').Gpio,
inputMain = new GPIO(17,'in','both'),
inputGen1 = new GPIO(4,'in','both'),
inputGen2 = new GPIO(27,'in','both'),
inputGen3 = new GPIO(22,'in','both'),
outMain = new GPIO(11,'high'),
outGen1 = new GPIO(15,'high'),
outGen2P = new GPIO(18,'high'), // Generator 2 power
outGen2SM = new GPIO(23,'high'), //Generator 2 starting motor
outGen2 = new GPIO(24,'high'), // Generator 2 contactor
outGen3P = new GPIO(25,'high'),
outGen3SM = new GPIO(8,'high'),
outGen3 = new GPIO(7,'high'),
objects =[outMain,outGen1,outGen2P,outGen2SM,outGen2,outGen3P,outGen3SM,outGen3];
//检查是否有主电源,作为所有其他电源的参考
inputMain.watch(function(err,state){
if (state)
main(1);
});
//切换到主接触器
function main (arg) {
console.log('test');
if (arg == 1) {
value = [0,1,1,1,1,1,1,1];}
else {
value = [0,0,0,0,0,0,0,0];
}
out(value);
}
//根据数组的值打开所有的继电器…
function out(value) {
for ( var i = 0; i< value.length; i++) {
if (value[i] == 0 ) {
var a = objects[i];
} else {
objects[i].writeSync(value[i]);
}
}
setTimeout(function() {
a.writeSync(0);
},5000);
}
恐怕你需要调用read或readSync。
...
outGen3SM = new GPIO(8,'high'),
outGen3 = new GPIO(7,'high'),
objects =[outMain,outGen1,outGen2P,outGen2SM,outGen2,outGen3P,outGen3SM,outGen3];
//Forces the first output update
main(inputMain.readSync());