-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdaemon.js
83 lines (72 loc) · 2.03 KB
/
daemon.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const { spawn } = require('cross-spawn');
const Gpio = require('onoff').Gpio;
const reset = new Gpio(2, 'in', 'rising', { debounceTimeout: 10, activeLow: true });
const power = new Gpio(3, 'in', 'both', { debounceTimeout: 100, activeLow: true });
const light = new Gpio(4, 'out');
let child;
const STATE = {
OFF: 0,
BOOT: 1,
RUNNING: 2
}
const spawnOpts = { stdio: ['inherit', 'inherit', 'inherit'], cwd: __dirname };
let currentState = STATE.OFF;
const spawnMain = (code) => {
if (power.readSync()) {
if (code) {
console.error('Child process exited with error code', code);
currentState = STATE.ERROR;
} else {
console.log('Child process exited cleanly. Launching new process.')
child = spawn('node', ['index.js'], spawnOpts);
child.on('exit', spawnMain);
}
} else {
powerOff();
}
}
const powerOff = () => {
if (currentState !== STATE.OFF) {
console.log('Powering off');
currentState = STATE.OFF;
}
}
setInterval(() => {
if (currentState === STATE.ERROR) {
light.writeSync(light.readSync() ^ 1);
}
}, 500);
power.watch((err, value) => {
console.log('Detected power', value);
light.writeSync(value);
switch (currentState) {
case STATE.OFF:
if (value) {
currentState = STATE.BOOT;
child = spawn('node', ['boot.js'], spawnOpts);
child.on('exit', code => {
currentState = STATE.RUNNING;
spawnMain(code);
});
}
break;
case STATE.BOOT:
break;
case STATE.ERROR:
if (!value) {
powerOff();
}
case STATE.RUNNING:
if (!value) {
child.kill();
powerOff();
}
}
});
reset.watch(() => {
console.log('Detected reset');
if (currentState === STATE.RUNNING) {
console.log('Resetting');
child.kill();
}
});