forked from Jopyth/MMM-Buttons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
95 lines (76 loc) · 2.71 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
/* Magic Mirror
* Node Helper: Buttons
*
* By Joseph Bethge
* MIT Licensed.
*/
const Gpio = require('onoff').Gpio;
const NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
// Subclass start method.
start: function() {
var self = this;
console.log("Starting node helper for: " + self.name);
this.loaded = false;
},
// Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
if (notification === 'BUTTON_CONFIG') {
this.config = payload.config;
this.intializeButtons();
};
},
watchHandler: function(index) {
var self = this;
return function (err, value) {
if (value == 1) {
var start = new Date().getTime();
if (self.buttons[index].downBounceTimeoutEnd > start) {
// We're bouncing!
return;
}
self.buttons[index].pressed = start;
self.buttons[index].downBounceTimeoutEnd = start + self.config.bounceTimeout;
self.sendSocketNotification("BUTTON_DOWN", {
index: index
});
return;
}
if (value == 0 && self.buttons[index].pressed !== undefined) {
var start = self.buttons[index].pressed;
var end = new Date().getTime();
if (self.buttons[index].upBounceTimeoutEnd > end) {
// We're bouncing!
return;
}
self.buttons[index].pressed = undefined;
self.buttons[index].upBounceTimeoutEnd = end + self.config.bounceTimeout;
var time = end - start;
self.sendSocketNotification("BUTTON_UP", {
index: index,
duration: time
});
return;
}
}
},
intializeButton: function(index) {
const self = this;
var options = { persistentWatch: true , activeLow: !!self.buttons[index].activeLow};
var pir = new Gpio(self.buttons[index].pin, 'in', 'both', options);
pir.watch(this.watchHandler(index));
},
intializeButtons: function() {
const self = this;
if (self.loaded) {
return;
}
self.buttons = self.config.buttons;
for (var i = 0; i < self.buttons.length; i++) {
console.log("Initialize button " + self.buttons[i].name + " on PIN " + self.buttons[i].pin);
self.buttons[i].pressed = undefined;
self.intializeButton(i);
}
self.loaded = true;
}
});