-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
98 lines (83 loc) · 2.31 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
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
/* eslint prefer-destructuring: ["error", {VariableDeclarator: {array: true}}] */
const { exec } = require('child_process');
const hid = require('node-hid');
const fs = require('fs');
const { parser } = require('json-based-conditions-and-rules-logic-evaluator');
const ARGS = process.argv.slice(2);
const path = ARGS[0] || './config.json';
let timerID;
let device;
if (!fs.existsSync(path)) {
console.log('configuration file needed');
process.exit();
}
const configfile = fs.readFileSync(path);
const config = JSON.parse(configfile);
const {
PRODUCT,
TIMERS,
DEFAULT,
CONDITIONS,
RULES,
} = config;
const isTargetDevice = function (d) {
return d.product === PRODUCT && d.usagePage === 0xFF60 && d.usage === 0x61;
};
function connect() {
const devices = hid.devices();
const deviceInfo = devices.find((d) => isTargetDevice(d));
let was = DEFAULT;
let wasApp = '';
let wasTitle = '';
let output;
let appData;
let titleData;
if (deviceInfo) {
device = new hid.HID(deviceInfo.path);
if (device) {
device.on('data', () => {});
device.on('error', (err) => {
console.error('device error:', err);
device.close();
clearInterval(timerID);
connect();
});
device.write([DEFAULT]); // default layer code
setTimeout(() => {
timerID = setInterval(() => {
exec('npx active-win', (e, stdout) => {
if (e instanceof Error) {
console.error('error:', e);
}
if (stdout) {
const arr = stdout.toString().trim().toLowerCase().split('\n');
appData = arr[2];
titleData = arr[0];
if (wasApp !== appData || wasTitle !== titleData) {
output = parser({
CONDITIONS,
RULES,
DEFAULT,
}, {
app: appData,
title: titleData,
});
}
if (output && was !== output) {
device.write([output]);
was = output;
wasApp = appData;
wasTitle = titleData;
}
}
});
}, TIMERS.RUNNER);
}, TIMERS.LINK);
}
} else {
setTimeout(() => {
connect();
}, TIMERS.RELINK);
}
}
connect();