pi-rfid-jukebox/player.js

80 lines
1.9 KiB
JavaScript

const glob = require('glob');
const spawn = require('child_process').spawn;
const tag_reader = spawn('/home/annika/rfid/run-tag-reader');
const player = spawn('/usr/bin/sudo', ['-n', '/usr/bin/mpg321', '-R', '-']);
tag_reader.on('error', function(err) {
console.log(`[tag_reader:error] ${err}`);
});
player.on('error', function(err) {
console.log(`[player:error] ${err}`);
});
// player.stdin.write("GAIN 100");
last_tag = null;
debounce_until = 0;
function lookup(tag, cb) {
if (tag === 'b9506555d9') {
return cb('STOP');
}
if (tag === 'aa89665510') {
return cb('PAUSE', 2);
}
glob('media/' + tag + ' - *.mp3', function(er, files) {
if (files.length > 0) {
return cb("LOAD " + files[0], 5);
}
});
}
tag_reader.stdout.on('data', (data) => {
if (Date.now() / 1000 < debounce_until) {
return;
}
last_tag = String(data).trim();
console.log("Tag: " + last_tag);
lookup(last_tag, function(action, wait_sec) {
wait_sec = wait_sec || 1;
if (action) {
debounce_until = Date.now() / 1000 + wait_sec;
console.log(`Running ${action} for ${last_tag}`);
player.stdin.write(action + "\n");
}
});
});
tag_reader.stderr.on('data', (data) => {
console.log(`[tag_reader:stderr] ${data}`);
});
player.stderr.on('data', (data) => {
if (String(data).substr(0, 3) === "@F ") {
return;
}
console.log(`[player:stderr] ${data}`);
});
var express = require('express')
, logger = require('morgan')
, app = express()
, template = require('jade').compileFile(__dirname + '/source/templates/homepage.jade')
app.use(logger('dev'))
app.use(express.static(__dirname + '/static'))
app.get('/', function (req, res, next) {
try {
var html = template({ title: 'Home', last_tag: last_tag })
res.send(html)
} catch (e) {
next(e)
}
})
app.listen(process.env.PORT || 80, function () {
console.log('Listening on http://localhost:' + (process.env.PORT || 80))
})