-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlight.js
79 lines (63 loc) · 1.39 KB
/
light.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
'use strict';
const gpio = require('rpi-gpio-mod');
const doSet = (pin, value, cont) => {
gpio.write(pin, value, err => {
if (err) console.log("error writing", pin, value);
cont();
});
};
const createSet = (pin, value) => {
return cont => doSet(pin, value, cont);
};
const createFlash = pin => {
let delay = (seconds, cont) => {
setTimeout(cont, seconds * 1000);
};
let cycle = (rem, cont) => {
if (rem > 0) {
doSet(pin, true,
() => delay(.1,
() => doSet(pin, false,
() => delay(.1,
() => cycle(rem-1, cont))))
);
} else cont();
};
return cont => cycle(7,cont);
};
const service = queue => {
let next = () => {
if (queue.length !== 0) {
let head = queue.shift();
head(next);
} else setTimeout(next, 50);
};
next();
};
const init = (pin, cont) => {
gpio.setup(pin, err => {
if (err) console.log("cannot setup pin: ", pin);
cont();
});
}
const create = pin => {
var state = false;
const queue =[];
let set = newState => {
if (newState !== state) {
state = newState;
queue.push(createSet(pin, state));
}
};
let flash = () => {
queue.push(createFlash(pin))
queue.push(createSet(pin, state));
};
init(pin, () => service(queue));
return {
on: () => set(true),
off: () => set(false),
flash: flash
};
};
exports.create = create;