繁体   English   中英

如何构建Express应用以在Raspberry Pi3上运行灯条

[英]How to structure an express app to run a light strip on a Raspberry Pi3

我已经在树莓派上设置了一个节点服务器,以在Adafruit Dotstar灯条上显示一系列颜色。 该功能的工作方式如下:我向localhost:8000/fade发出HTTP请求,服务器通过运行fade.js文件进行响应,该文件是一个无限循环,通过光带上的不同颜色淡入淡出。 不幸的是,我希望能够退出此命令,并通过另一个对localhost:8000/off请求来关闭灯带。

我已经尝试过child_process包,以便运行“淡入​​淡出”代码,同时还监听新的请求。 但是,我无法终止“淡入淡出”过程。

下面发布的是我的app.js代码。 关于如何终止child_process或以其他方式重组代码以实现相同目标的任何建议? 我真的只需要能够连续运行“淡入​​淡出”代码,同时还要响应新的请求。

ps这是我的第一个JS项目,请轻松! 任何帮助表示赞赏。

app.js:

var express     = require('express'),
    app         = express();

app.get('/', function (req, res) {
  res.send('App is responding to requests');
});

app.get('/fade', function (req, res) {
  var fork = require('child_process').fork;
  child = fork('./sequences/fade.js');
});

app.get('/off', function (req, res) {
  var fork = require('child_process').fork;
  child = fork('./sequences/off.js');
});

app.listen(8000, function () {
  console.log('Example app listening on port 8000!')
})

fade.js:

console.log("running fade.js");
var dotstar     = require('dotstar'),
    SPI         = require('pi-spi'),
    sleep       = require('sleep');

spi = SPI.initialize('/dev/spidev0.0');
const ledStripLength = 30;

const ledStrip = new dotstar.Dotstar(spi, {
  length: ledStripLength
});

while(1) {
    fade(); //where fade is a long sequence of colors
};
var child; // Outer scope, available in both functions.

app.get('/fade', function (req, res) {
  var fork = require('child_process').fork;
  child = fork('./sequences/fade.js');
});

app.get('/off', function (req, res) {
  // (might be a good idea to check if child exists and is running first...)
  child.kill('SIGHUP');
});

也是http://programmergamer.blogspot.com/2013/05/clarification-on-sigint-sigterm-sigkill.html

SIGHUP:...一个进程必须显式处理此信号才能起作用。 ...

因此,如果要关闭而不在前叉侧对其进行操作,则请使用SIGINT ,或者SIGKILL以杀死该Mofo。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM