我正在使用socket.IO创建一个nodejs应用程序,用于某些家庭自动化。在app.js我从接口接收调用工作正常,我将这些调用发送到另一个文件/ raspberry pi。这也很好,对于基本的事情,如:打开/关闭,改变颜色等。我创建了这个fade()
函数,它在led颜色之间淡化,当我调用这个函数(它保持循环应该)它只循环,并停止接收其他套接字调用。
我只需要一种方法同时运行fade()
函数,或者另一种(更好?)方法。
在我的代码下面:
let Gpio = require('pigpio').Gpio;
let socket = require('socket.io-client')('http://localhost:8080');
let delay = require('delay');
let ledRed = new Gpio(27, {mode: Gpio.OUTPUT});
let ledGreen = new Gpio(17, {mode: Gpio.OUTPUT});
let ledBlue = new Gpio(22, {mode: Gpio.OUTPUT});
let fadeState = false;
socket.on('fadeClient',function(data){
if (fadeState === false){
fadeState = data;
// fade()
}
console.log("fade " + data);
fadeState = data;
console.log("data");
});
function setRGBVal(red, blue, green){
// console.log('red: ' +red);
// console.log('blue: ' +blue);
// console.log('green: ' +green);
ledRed.pwmWrite(0);
ledGreen.pwmWrite(0);
ledBlue.pwmWrite(0);
ledRed.pwmWrite(Math.round(red));
ledGreen.pwmWrite(Math.round(blue));
ledBlue.pwmWrite(Math.round(green));
}
function fade(){
console.log("inFade");
while(fadeState === true) {
console.log(fadeState)
for (i = 0; i < 255; i++) {
setRGBVal(i, 0, 0);
delay(500);
if (fadeState === true){
break;
console.log("piemel");
}
}
for (i = 0; i < 255; i++) {
setRGBVal(0, i, 0);
delay(500);
if (fadeState === true){
break;
console.log("piemel");
}
}
for (i = 0; i < 255; i++) {
setRGBVal(0, 0, i);
delay(500);
if (fadeState === true){
break;
console.log("piemel");
}
}
}
};
答案 0 :(得分:0)
Node.js是单线程的,因此如您所发现的,delay()将阻止整个应用程序。使用setTimeout()代替,就像在前端Web应用程序中一样。像这样:
fadeNext(0);
function fadeNext(i) {
setRGBVal(i, 0, 0);
if (i < 255) {
setTimeout(function() { fadeNext(i+1); }, 500);
}
}