Skip to content

Instantly share code, notes, and snippets.

@flexd
Created November 29, 2012 17:46
Show Gist options
  • Save flexd/4170706 to your computer and use it in GitHub Desktop.
Save flexd/4170706 to your computer and use it in GitHub Desktop.
var spawn = require('child_process').spawn;
var util = require('util');
var EventEmitter = require('events').EventEmitter;
function CardReader() {
var reader;
var lastUID = "";
var me = this;
function spawnReader() {
reader = spawn('python', ['uidgrabber.py']);
console.log("uidgrabber running pid: " + reader.pid);
}
function handleExit(reader) {
reader.on('exit', function (code) {
console.log('uidgrabber process exited with code ' + code);
me.emit('exit', code);
spawnReader();
handleExit(reader);
});
}
spawnReader();
handleExit(reader);
// Handle stuff.
reader.stderr.on('data', function (data) {
console.log('stderr: ' + data);
me.emit('error', data);
});
reader.stdout.on('data', function (data) {
var data = data.toString();
data = data.replace(/\u001b\[\d{0,2}m/g, ''); // Remove ANSI colors.
var uid = /UID: (.+)/.exec(data);
if (uid) {
uid = uid[1];
if (uid != lastUID) {
// This is not the last card we read, so lets emit it.
me.emit('cardRead', uid);
}
lastUID = uid;
}
});
}
util.inherits(CardReader, EventEmitter);
exports.createReader = function () {
return new CardReader();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment