Skip to content

Instantly share code, notes, and snippets.

@jeremychone
Created December 12, 2013 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremychone/7935444 to your computer and use it in GitHub Desktop.
Save jeremychone/7935444 to your computer and use it in GitHub Desktop.
Just a little experiment reading dualshock4 bluetooth inputs with node.js. Uses node-hid.
/**
* Just for fun, hacking Dualshock4 with node.js
* Most of the code comes from https://npmjs.org/package/dualshock-controller
* Just wanted to play with the low level hid protocol.
* Next step: EV3 Control via Bluetooth with Dualshock4 (PC still required).
* Future step: EV3 node.js onboarding with Dualshock4 remote control (Autonomous).
*/
var HID = require('node-hid');
// just a quick configuration with the hardcoded vendor/product id of the Dualshock4
var controllerConfiguration = {
"vendorId": 1356,
"productId": 1476
}
var hidDevice;
// simplest connect method. TODO: error handling and more.
function connect() {
hidDevice = new HID.HID(controllerConfiguration.vendorId, controllerConfiguration.productId);
console.log('node dualshock connecting');
}
// simplest deviceRead
function deviceRead() {
//call device read and process the data.
try {
if (hidDevice) {
hidDevice.read(processFrame);
} else {
this.emit("error", "Could not connect to the device");
}
} catch (ex) {
throw ex
//retry
deviceRead();
}
};
// utility to display some number in binary format
function toBin(n, width) {
width = width || 8;
var z = '0';
n = new Number(n).toString(2);
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
// just print out the data and read next input
function processFrame(error, data) {
//check for errors from node-hid.
if (error) {
//throw the error, will be handled and retry will be done.
throw (error);
}
var val, vals = "";
for (var i = 0; i < data.length; i++) {
val = data[i];
if (i == 5 || i == 6) {
val = toBin(val);
}
vals += " " + val;
}
console.log("read: " + vals);
deviceRead();
}
// connect
connect();
// and start the read process
deviceRead();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment