const logger = require('./logger.js'); const { CONTROL_BYPASS } = require('./constants.js'); const { httpPOST } = require('./util.js'); let enabled; async function initialize() { enabled = global.config.blinky !== undefined && global.config.blinky.enabled && global.config.blinky.host !== undefined && global.config.blinky.port !== undefined; } async function setActive(active) { if (!enabled) { return; } logger.info('handling blinky event \'setActive\' (argument: \'' + active + '\')...'); try { if (active) { await httpPOST( global.config.blinky.host, global.config.blinky.port, '/set', { blinkstick: 'square', color: '#0f0f0f' } ); return; } let mode = '/poweroff'; await httpPOST( global.config.blinky.host, global.config.blinky.port, mode, { blinkstick: 'square' } ); await httpPOST( global.config.blinky.host, global.config.blinky.port, mode, { blinkstick: 'strip' } ); } catch (err) { logger.error(err); } } async function setPedalStatus(pedal) { if (!enabled || pedal === undefined || pedal.controls === undefined) { return; } for (let index = 0; index < pedal.controls.length; index++) { const bypass = pedal.controls[index]; if (bypass.name !== CONTROL_BYPASS) { continue; } const args = { blinkstick: "strip", index: pedal.id }; let mode = 'poweroff'; if (bypass.value !== undefined && bypass.value > 0) { mode = 'set'; args.color = getPedalColorByName(pedal.name); } return httpPOST(global.config.blinky.host, global.config.blinky.port, mode, args); } } async function setStatus(pedals) { if (!enabled) { return; } try { await httpPOST(global.config.blinky.host, global.config.blinky.port, '/poweroff', { blinkstick: 'strip' }); if (pedals === undefined || pedals.length === 0) { return; } const promises = []; for (let index = 0; index < pedals.length; index++) { if (pedals[index]?.controls === undefined || pedals[index]?.controls.length === 0) { continue; } promises.push(setPedalStatus(pedals[index])); } const results = await Promise.allSettled(promises); for (let index = 0; index < results.length; index++) { const result = results[index]; if (result.status !== 'fulfilled') { logger.error(result.reason); } } } catch (err) { logger.error(err); } } async function setBypass(bypassActive) { if (!enabled) { return; } try { if (!bypassActive) { return await setActive(true); } await httpPOST(global.config.blinky.host, global.config.blinky.port, 'pulse', { blinkstick: 'square', color: '#660000' }); } catch (err) { logger.error(err); } } function getPedalColorByName(name) { return global.config.blinky?.colors[name] || 'random'; } module.exports = { initialize, setActive, setBypass, setStatus, setPedalStatus }