-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
53 lines (51 loc) · 1.56 KB
/
index.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
const spawn = require('child_process').spawn;
const trigger = (triggerCommand, address) => {
const command = {
turnOn: "570101",
turnOff: "570102",
press: "570100"
}
return new Promise((resolve, reject) => {
if (!command[triggerCommand]) {
reject("no such command [" + triggerCommand + "]");
return;
}
if (!triggerCommand) {
triggerCommand = "press"
}
const gatttool = spawn('gatttool', ['-b', address, '-t', 'random', '-I'])
var connectSended = false;
gatttool.stdout.on('data', (data) => {
if (!connectSended && !data.toString().startsWith("connect")) {
gatttool.stdin.write("connect\n")
connectSended = true;
} else if (data.indexOf("Connection successful") >= 0) {
gatttool.stdin.write("char-write-cmd 0x0016 " + command[triggerCommand] + "\n")
setTimeout(() => {
gatttool.kill();
resolve();
}, 1000);
} else if (data.indexOf("Error") >= 0) {
gatttool.kill();
reject();
}
});
gatttool.stderr.on('data', (data) => {
gatttool.kill();
reject();
});
});
}
module.exports = (address) => {
return {
"turnOn" : () => {
return trigger("turnOn", address);
},
"turnOff" : () => {
return trigger("turnOff", address);
},
"press" : () => {
return trigger("press", address);
}
}
}