-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBigRedButton.js
104 lines (86 loc) · 2.71 KB
/
BigRedButton.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
// BigRedButton.js - Dream Cheeky Big Red Button node.js/node-hid driver
// MIT licensed. (C) Dj Walker-Morgan 2013
var HID = require('node-hid');
var util = require('util');
var events = require('events');
var allDevices;
var cmdStatus=new Buffer([ 0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 ]);
var lastState;
var LID_DOWN=0x15, LID_UP=0x17, BUTTON_DOWN=0x16;
function getAllDevices()
{
allDevices = HID.devices(7476,13);
return allDevices;
}
function BigRedButton(index)
{
if (!arguments.length) {
index = 0;
}
var bigRedButton = getAllDevices();
if (!bigRedButton.length) {
throw new Error("No BigRedButton could be found");
}
if (index > bigRedButton.length || index < 0) {
throw new Error("Index " + index + " out of range, only " + bigRedButton.length + " BigRedButton found");
}
this.button = bigRedButton[index];
this.hid = new HID.HID(bigRedButton[index].path);
this.hid.write(cmdStatus);
var that=this;
this.hid.read(function(error,data) {
lastState=data[0];
that.hid.read(that.interpretData.bind(that));
});
this.interval = setInterval(this.askForStatus.bind(this),100);
this.close = function() {
clearInterval(this.interval);
this.interval = false;
setTimeout(function() {
this.hid.close();
}.bind(this), 100);
this.emit("buttonGone");
};
}
util.inherits(BigRedButton, events.EventEmitter);
BigRedButton.prototype.askForStatus = function() {
try {
this.hid.write(cmdStatus);
} catch(e) {
this.close();
}
};
BigRedButton.prototype.interpretData = function(error, data) {
if (!this.interval || error || !data) {
this.close();
return;
}
var newState=data[0];
if (lastState!=newState) {
if (lastState==LID_DOWN && newState==LID_UP) {
this.emit("lidRaised");
} else if (lastState==LID_UP && newState==BUTTON_DOWN) {
this.emit("buttonPressed");
} else if (lastState==BUTTON_DOWN && newState==LID_UP) {
this.emit("buttonReleased");
} else if (lastState==BUTTON_DOWN && newState==LID_DOWN) {
this.emit("buttonReleased");
this.emit("lidClosed");
} else if (lastState==LID_UP && newState==LID_DOWN) {
this.emit("lidClosed");
}
lastState=newState;
}
this.hid.read(this.interpretData.bind(this));
}
BigRedButton.prototype.isLidUp = function() {
return lastState==LID_UP || lastState==BUTTON_DOWN;
}
BigRedButton.prototype.isButtonPressed = function() {
return lastState==BUTTON_DOWN;
}
BigRedButton.prototype.isLidDown = function() {
return lastState==LID_DOWN;
}
exports.BigRedButton = BigRedButton;
exports.deviceCount = function () { return getAllDevices().length; }