Skip to content

Instantly share code, notes, and snippets.

@Pindar
Last active July 17, 2018 21:09
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 Pindar/987cb03fe99b4549496b59da709b7a6f to your computer and use it in GitHub Desktop.
Save Pindar/987cb03fe99b4549496b59da709b7a6f to your computer and use it in GitHub Desktop.
automate-powerplug-stereoanlage
HUE_HOST=192.168.XX.XX
HUE_USER=iglksjflXXXXXXXXX
LIGHT_NUMBER=00
[Unit]
Description=Automate powerplug when sound is playing
[Service]
TimeoutSec=0
EnvironmentFile=/home/pi/automate-powerplug-stereoanlage/.env
ExecStart=/usr/local/bin/node /home/pi/automate-powerplug-stereoanlage/index.js
[Install]
WantedBy=multi-user.target
const qfgets = require('qfgets');
const glob = require('glob');
const IDLE = 0;
const PLAYING = 1;
var status = {};
var timeoutObj = {};
var config = require('./utils').config,
hue = require("node-hue-api"),
HueApi = hue.HueApi,
lightState = hue.lightState;
var displayResults = function(result) {
console.log(JSON.stringify(result, null, 2));
};
var displayError = function(err) {
console.error(err);
};
var api = new HueApi(config.HUE_HOST, config.HUE_USER);
// https://stackoverflow.com/questions/28400727/from-node-js-which-is-faster-shell-grep-or-fs-readfile
function grepWithFs(filename, regexp, done) {
let fp = new qfgets(filename, "r");
let count = 0;
function loop() {
for (i=0; i<1; i++) {
line = fp.fgets();
if (line && line.match(regexp)) count++;
}
if (!fp.feof()) setImmediate(loop);
else done(count);
}
loop();
}
glob('/proc/asound/card*/*p/*/status', function (err, files) {
setInterval(() => {
files.map(file => {
if (isNaN(status[file])) {
status[file] = IDLE;
timeoutObj[file] = 0;
}
grepWithFs(file, 'RUNNING', function(count) {
if (count === 0 && status[file] === PLAYING) {
console.log('power-off maybe', file);
status[file] = IDLE;
timeoutObj[file] = setTimeout(function () {
console.log('power-off', status, file);
api.setLightState(config.LIGHT_NUMBER, {on: false})
.then(displayResults)
.fail(displayError)
.done();
}, 30000);
return;
}
if (count > 0 && status[file] === IDLE) {
status[file] = PLAYING;
clearTimeout(timeoutObj[file]);
console.log('power on playing', status[file], file);
api.setLightState(config.LIGHT_NUMBER, {on: true})
.then(displayResults)
.fail(displayError)
.done();
}
});
});
}, 2500);
});
{
"name": "automate-powerplug-stereoanlage",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"glob": "^7.1.2",
"nconf": "^0.10.0",
"node-hue-api": "^2.4.2",
"qfgets": "^1.1.1"
}
}
var nconf = require('nconf');
var pkg = require('./package.json');
var config = nconf
.env()
.argv()
.defaults(pkg.appConfig)
.get();
module.exports = {
config: config
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment