Skip to content

Instantly share code, notes, and snippets.

@bathos
Created February 23, 2017 15:40
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 bathos/ecf04e982ddcb8d983f85131583da542 to your computer and use it in GitHub Desktop.
Save bathos/ecf04e982ddcb8d983f85131583da542 to your computer and use it in GitHub Desktop.
replacement entry for node-hid?
const assert = require('assert');
const binary = require('node-pre-gyp');
const { Duplex } = require('stream');
const SHARED_METHOD_KEYS = [
'getDeviceInfo',
'getFeatureReport',
'sendFeatureReport',
'setNonBlocking'
];
const binding = require(binary.find(require.resolve('node-hid/package.json')));
const hids = new WeakMap();
class HID extends Duplex {
constructor({ path, productId, vendorId }={}) {
assert(
path || (vendorId && productId),
'HID requires either path or both vendorId and productId'
);
const hid = path
? new binding.HID(path)
: new binding.HID(vendorId, productId);
const handleData = (err, data) => {
if (err) {
this.emit('error', err);
return;
}
if (this.push(data)) {
hid.read(handleData);
}
};
super({
objectMode: true,
read: () => {
if (!this._muted) {
hid.read(handleData);
}
},
write: (chunk, enc, done) => {
try {
hid.write(chunk);
done();
} catch (err) {
done(err);
}
}
});
hids.set(this, hid);
}
mute() {
this._muted = true;
}
unmute() {
this._muted = false;
}
}
for (const key of SHARED_METHOD_KEYS) {
Object.defineProperty(HID.prototype, key, {
configurable: true,
enumerable: false,
value: function() {
return hids.get(this)[key](...arguments);
},
writable: true
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment