-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathraw-wiimote.js
130 lines (103 loc) · 2.73 KB
/
raw-wiimote.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
125
126
127
128
129
130
var HID = require('node-hid'),
pakkit = require('pakkit'),
events = require('events');
var Command = {
SetLEDState: 0x11,
SetReportingMode: 0x12
};
var ReportFlags = {
OnChange: 0x00,
Continuous: 0x04
};
var ReportMode = {
Buttons: 0x30,
ButtonsAccelerometer: 0x31
};
function isWiimote(deviceDesc) {
return deviceDesc.vendorId == 1406;
}
var packets = pakkit.export({
BUTTONS : {
buttons: {
mask: [
'dleft', 'dright', 'ddown', 'dup',
'plus', '_', '_', '_',
'2', '1', 'b', 'a',
'minus', '_', '_', 'home'
],
type: 'uint16le'
}
}
}, {});
var Wiimotes = new events.EventEmitter();
Wiimotes.open = function (callback) {
var wiimotes = this,
currentPaths = null,
currentDevices = [];
if (callback) {
wiimotes.on('data', callback);
}
function enumerate() {
return HID.devices().filter(isWiimote).map(function (d) {
return d.path;
}).sort();
}
function checkDevices() {
var devicePaths = enumerate();
if (devicePaths.join(',') !== currentPaths) {
openAll(devicePaths);
}
}
function closeAll() {
currentDevices.forEach(function (d) {
d.close();
});
}
function openAll(devicePaths) {
closeAll();
currentPaths = devicePaths.join(',');
wiimotes.emit('enumerate', devicePaths.length);
currentDevices = devicePaths.map(function(devicePath, index) {
var device = new HID.HID(devicePath),
ledState = 0x10 << (index % 4),
rumblePulse = false,
rumbleTimer = null;
function applyLedAndRumble() {
var rumbleBit = rumblePulse ? 1 : 0;
try {
device.write(new Buffer([Command.SetLEDState, ledState | rumbleBit]));
} catch(e) {
console.log(e);
}
}
function pulseRumble(duration) {
clearTimeout(rumbleTimer);
rumblePulse = true;
applyLedAndRumble();
rumbleTimer = setTimeout(function () {
rumblePulse = false;
applyLedAndRumble();
}, duration);
}
device.on('data', function(data) {
data = data.slice(1);
var parsed = packets.BUTTONS.read(data);
wiimotes.emit('data', index + 1, parsed);
if (parsed.buttons.home) {
pulseRumble(100);
}
applyLedAndRumble();
});
device.on('error', function() {
openAll(enumerate());
});
device.write(new Buffer([Command.SetReportingMode, ReportFlags.OnChange, ReportMode.Buttons]));
pulseRumble(300);
wiimotes.emit('data', index + 1, { buttons: {} });
return device;
});
}
wiimotes.timer = setInterval(checkDevices, 1000);
process.nextTick(checkDevices);
};
module.exports = Wiimotes;