-
Notifications
You must be signed in to change notification settings - Fork 0
/
phone-commands.js
122 lines (104 loc) · 2.28 KB
/
phone-commands.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const { Gpio } = require('onoff');
const canUseGpio = require('./can-use-gpios');
const [ON, OFF] = [1, 0];
const stateStringToValue = stateStr =>
new Map([
['on', ON],
['off', OFF],
]).get(stateStr);
const getCommandsFromSequence = sequence => sequence
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
.map((line) => {
const [msDelta, pinName, state] = line.split(' ');
return {
msDelta: +msDelta,
pin: pinName,
state: stateStringToValue(state),
};
});
const getTimeFromCommands = commands => commands.reduce((time, { msDelta }) => time + msDelta, 0);
// ms-delta pin-name state
const openCommands = getCommandsFromSequence(`
0 end on
300 end off
200 zero on
2000 zero off
300 accept on
300 accept off
10000 zero on
300 zero off
200 zero on
300 zero off
5000 end on
300 end off
`);
/*
const answerCommands = getCommandsFromSequence(`
0 accept on
300 accept off
400 zero on
300 zero off
200 zero on
300 zero off
1000 end on
300 end off
`);
*/
const answerCommands = getCommandsFromSequence(`
0 accept on
300 accept off
400 zero on
300 zero off
200 zero on
300 zero off
1000 end on
300 end off
`);
const sharedExports = {
openTime: getTimeFromCommands(openCommands),
answerTime: getTimeFromCommands(answerCommands),
};
if (canUseGpio) {
const relays = {
accept: new Gpio(23, 'out'),
end: new Gpio(24, 'out'),
zero: new Gpio(25, 'out'),
};
const useCommands = commands => new Promise((resolve, reject) => {
let time = 0;
const timeouts = [];
commands.forEach(({ msDelta, pin, state }, i) => {
time += msDelta;
const timeoutId = setTimeout(() => {
try {
relays[pin].writeSync(state);
if (i === commands.length - 1) {
resolve();
}
} catch (e) {
timeouts.forEach(clearTimeout);
reject();
}
}, time);
timeouts.push(timeoutId);
});
});
const open = () =>
useCommands(openCommands);
const answer = () =>
useCommands(answerCommands);
module.exports = {
...sharedExports,
open,
answer,
};
} else {
const noopPromise = () => Promise.resolve();
module.exports = {
...sharedExports,
open: noopPromise,
answer: noopPromise,
};
}