Skip to content

Instantly share code, notes, and snippets.

@enapupe
Last active June 25, 2018 18:19
Show Gist options
  • Save enapupe/64f05dc2bf973d4a3259db6ddc6c9a02 to your computer and use it in GitHub Desktop.
Save enapupe/64f05dc2bf973d4a3259db6ddc6c9a02 to your computer and use it in GitHub Desktop.

Audio Output Monitor

This script will monitor the linux sound card file and fire an endpoint whenever the system starts to output audio. After a few seconds without audio output the script will fire a different endpoint.

Configurations

Use the -e flag to run a container with the following envs:

FROM node
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
ENV AUDIO_PATH '/proc/asound/card0/pcm0p/sub0/status'
ENV ENDPOINT_ON 'http://localhost:1880/amp/on'
ENV ENDPOINT_OFF 'http://localhost:1880/amp/off'
COPY . /usr/src/app
CMD [ "node", "index.js" ]
const fs = require('fs')
const http = require('http')
const SIGNALS = /state: PREPARED|state: RUNNING/
// initialize it with all states false
const history = Array(18).fill(false)
const AUDIO_PATH = process.env.AUDIO_PATH
const ENDPOINT_ON = process.env.ENDPOINT_ON
const ENDPOINT_OFF = process.env.ENDPOINT_OFF
const ENCODING = 'utf8'
let state = 0
const processFile = (err, data) => {
if (err) {
return console.log(err)
}
saveState(data)
setTimeout(readOutput, 1000)
}
const readOutput = (callback) => {
fs.readFile(AUDIO_PATH, ENCODING, processFile)
}
const processHistory = () => {
const positiveHistoryLength = history.filter(Boolean).length
if (history[history.length - 1]) {
checkIfChanged(1)
return
}
if (positiveHistoryLength === 0) {
checkIfChanged(0)
return
}
}
const checkIfChanged = (newState) => {
if (newState !== state) {
state = newState
doAction(state)
}
}
const doAction = (state) => {
if (state) {
console.info('Power ON')
http.get(ENDPOINT_ON).on('error', console.warn)
return
}
console.info('Power OFF')
http.get(ENDPOINT_OFF).on('error', console.warn)
}
const saveState = (data) => {
history.push(!!data.match(SIGNALS))
history.shift()
processHistory()
}
console.info('Intializing watcher...')
setTimeout(readOutput, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment