const { DeviceDiscovery } = require('sonos'); const ease = require('eases/quad-in-out'); // How long to let the SONOS device play for once playing is detected. // The longer you leave it the less likely that your co-worker will // notice that you've turned it off and won't restart it. const PLAY_DELAY = 120000; // 2 minutes. // How long it takes to fade the volume down to zero. const FADE_DELAY = 60000; // 60 seconds. // Easing period, you shouldn't need to change this. Just don't make it // longer than the FADE_DELAY. const FADE_STEP = 500; // 0.5 seconds. // How often to check if the device is playing. const POLL_DELAY = 10000; // 10 seconds. let fadeDown = function(device) { device.getVolume().then((volume) => { console.log(`Device ${device.host} volume ${volume}`); let start = new Date().valueOf(); let lastVolume = volume; let timer = setInterval(() => { let elapsed = (new Date().valueOf()) - start; if (elapsed > FADE_DELAY) { console.log(`Stopping ${device.host}`); if (device.stop()) { console.log(`Resetting ${device.host} volume back to ${volume}`); device.setVolume(volume) clearInterval(timer); setTimeout(pollState, POLL_DELAY, device); } } else { let newVolume = parseInt(ease(1 - (elapsed / FADE_DELAY)) * volume); if (newVolume != lastVolume) { console.log(`Setting ${device.host} volume to ${newVolume}`); device.setVolume(newVolume); lastVolume = newVolume; } } }, FADE_STEP); }); } let pollState = function(device) { device.getCurrentState().then((state) => { if (state === 'playing') { console.log(`Device ${device.host} is playing, queuing fade out`); setTimeout(fadeDown, PLAY_DELAY, device); } else { setTimeout(pollState, POLL_DELAY, device); } }); }; DeviceDiscovery((device) => { console.log(`Found device at ${device.host}`); pollState(device); })