-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
node_helper.js
executable file
·124 lines (113 loc) · 3.12 KB
/
node_helper.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
123
124
/* MagicMirror²
* Node Helper: MMM-KeyBindings
*
* By shbatm
* MIT Licensed.
*/
/* jshint node: true, esversion: 6*/
const NodeHelper = require("node_helper");
const Log = require("logger");
var evdev;
var udev;
module.exports = NodeHelper.create({
start: function () {
Log.log("MMM-KeyBindings helper has started…");
this.evdevMonitorCreated = false;
},
stop: function () {
if (this.evdevMonitorCreated) {
Log.log("EVDEV: Closing monitor and reader");
try {
this.udevMonitor.close();
} catch (e) {
if (
e.toString().indexOf("Cannot read property 'close' of undefined") ===
-1
) {
Log.error(e);
}
}
try {
this.evdevReader.close();
} catch (e) {
Log.error(e);
}
}
},
waitForDevice: function () {
this.udevMonitor = udev.monitor();
this.udevMonitor.on("add", (device) => {
if (
"DEVLINKS" in device &&
device.DEVLINKS === this.evdevConfig.eventPath
) {
Log.log("UDEV: Device connected.");
this.udevMonitor.close();
this.setupDevice();
}
});
},
setupDevice: function () {
this.device = this.evdevReader.open(this.evdevConfig.eventPath);
this.device.on("open", () => {
Log.log(`EVDEV: Connected to device: ${JSON.stringify(this.device.id)}`);
});
this.device.on("close", () => {
Log.debug(`EVDEV: Connection to device has been closed.`);
this.waitForDevice();
});
},
startEvdevMonitor: function () {
evdev = require("evdev");
udev = require("udev");
this.evdevMonitorCreated = true;
this.evdevReader = new evdev();
this.pendingKeyPress = {};
this.evdevReader
.on("EV_KEY", (data) => {
// Log.log("key : ", data.code, data.value);
if (data.value > 0) {
this.pendingKeyPress.code = data.code;
this.pendingKeyPress.value = data.value;
} else {
if (
"code" in this.pendingKeyPress &&
this.pendingKeyPress.code === data.code
) {
Log.log(
`${this.pendingKeyPress.code} ${
this.pendingKeyPress.value === 2 ? "long " : ""
}pressed.`
);
this.sendSocketNotification("KEYPRESS", {
keyName: data.code,
keyState:
this.pendingKeyPress.value === 2
? "KEY_LONGPRESSED"
: "KEY_PRESSED"
});
}
this.pendingKeyPress = {};
}
})
.on("error", (e) => {
if (e.code === "ENODEV" || e.code === "ENOENT") {
Log.info(
`EVDEV: Device not connected, nothing at path ${e.path}, waiting for device…`
);
this.waitForDevice();
} else {
Log.error("EVDEV: ", e);
}
});
this.setupDevice();
},
socketNotificationReceived: function (notification, payload) {
if (notification === "ENABLE_EVDEV") {
if (!this.evdevMonitorCreated) {
this.evdevConfig = payload;
this.startEvdevMonitor();
}
}
}
});