-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (67 loc) · 1.72 KB
/
index.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
/**
*
* Use the node HID module to get gamepads and their data
*
**/
var HID = require('node-hid');
// Get the first game pad for simplicity
var pad,pads = HID.devices().filter(function(d){
return (/gamepad/i).test(d.product)
});
if (pads != undefined && pads.length > 0) {
pad = new HID.HID(pads[0].path);
}
pad.read(function(err,data){}); // discard the first read
var last = [-1,-1,-1]; // empty state to begin with
var ReadPad = function(callback){
pad.read(function(err,data){
// Data is as follows: [128,128,0] => [x-axis,y-axis,buttons(0 for none)]
var state = {
x:data[0]==128 ? 0.5 : data[0]/255.0,
y:data[1]==128 ? 0.5 : data[1]/255.0,
button:data[2],
changed:[]
};
if(data[0] != last[0]) {
state.changed.push({name:"x",state:state.x});
}
if(data[1] != last[1]) {
state.changed.push({name:"y",state:state.y});
}
if(data[2] != 0 && data[2] != last[2]) {
state.changed.push({name:"button",state:state.button});
}
last = data;
console.log(data,state);
callback(err,state);
ReadPad(callback);
});
}
/**
*
* Simple WebSocket Server with Socket.IO
*
**/
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(4242);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
ReadPad(function(err, data){
socket.emit('gamepad',data)
data.changed.map(function(prop){
socket.emit('gamepad.'+prop.name,prop.state);
});
});
});