Skip to content

Instantly share code, notes, and snippets.

@WasabiFan
Created July 12, 2016 21:46
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 WasabiFan/51a395564cf5938cd2dc9d5885bad68d to your computer and use it in GitHub Desktop.
Save WasabiFan/51a395564cf5938cd2dc9d5885bad68d to your computer and use it in GitHub Desktop.
Demo of parsing ev3dev button events from Linux input subsystem in JavaScript
var fs = require('fs');
var EV_KEY = 0x01;
var buttonEventFile = '/dev/input/by-path/platform-gpio-keys.0-event';
// Hard-coded button values for EV3
var buttonNames = {
103: 'up',
108: 'down',
105: 'left',
106: 'right',
28: 'enter',
14: 'back'
}
var eventStream = fs.createReadStream(buttonEventFile);
eventStream.on('data', function (chunk) {
var allEvents = parseInputEvents(chunk);
// Filter events to get only key events
var keyEvents = allEvents.filter(function (event) {
return event.type == EV_KEY;
});
// Process the key events that correspond to known key codes
for (var keyEventIndex in keyEvents) {
var keyEvent = keyEvents[keyEventIndex];
if (keyEvent.code in buttonNames) {
// This will run every time one of the 6 buttons is pressed or released. keyEvent.value contains
// a number indicating whether the button was pressed or released.
console.log("Button " + buttonNames[keyEvent.code] + " is " + (keyEvent.value ? 'released' : 'pressed'));
}
}
});
function parseInputEvents(eventChunk) {
// Parse all events received in this chunk
var events = [];
for (var i = 0; i < eventChunk.length; i += 16) {
events.push({
time: {
sec: eventChunk.readUInt32LE(i + 0),
usec: eventChunk.readUInt32LE(i + 4)
},
type: eventChunk.readUInt16LE(i + 8),
code: eventChunk.readUInt16LE(i + 10),
value: eventChunk.readUInt32LE(i + 12)
});
}
return events;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment