-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjoystick.js
72 lines (60 loc) · 1.68 KB
/
joystick.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
var FS = require('fs');
var EventEmitter = require('events').EventEmitter;
function parse(buffer) {
var event = {
time: buffer.readUInt32LE(0),
value: buffer.readInt16LE(4),
number: buffer[7],
}
var type = buffer[6];
if (type & 0x80) event.init = true;
if (type & 0x01) event.type = "button";
if (type & 0x02) event.type = "axis";
return event;
}
// Expose as a nice JavaScript API
function Joystick(id) {
this.wrap("onOpen");
this.wrap("onRead");
this.id = id;
this.buffer = new Buffer(8);
FS.open("/dev/input/js" + id, "r", this.onOpen);
}
Joystick.prototype = Object.create(EventEmitter.prototype, {
constructor: {value: Joystick}
});
// Register a bound version of a method and route errors
Joystick.prototype.wrap = function (name) {
var self = this;
var fn = this[name];
this[name] = function (err) {
if (err) return self.emit("error", err);
return fn.apply(self, Array.prototype.slice.call(arguments, 1));
};
};
Joystick.prototype.onOpen = function (fd) {
this.fd = fd;
this.startRead();
};
Joystick.prototype.startRead = function () {
FS.read(this.fd, this.buffer, 0, 8, null, this.onRead);
};
Joystick.prototype.onRead = function (bytesRead) {
var event = parse(this.buffer);
event.id = this.id;
this.emit(event.type, event);
if (this.fd) this.startRead();
};
Joystick.prototype.close = function (callback) {
FS.close(this.fd, callback);
this.fd = undefined;
};
////////////////////////////////////////////////////////////////////////////////
// Sample usage
var js = new Joystick(0);
js.on('button', console.log);
js.on('axis', console.log);
// Close after 5 seconds
//setTimeout(function () {
// js.close();
//}, 5000);