const GPIO = require("onoff").Gpio; const WS = require("ws"); const HEARTBEAT_INT = 400; const button = new GPIO(4, "in", "both", {debounceTimeout: 30, activeLow: true}); const ledOnAir = new GPIO(24, "low"); const ledReady = new GPIO(23, "low"); const ws = new WS('ws://10.0.0.4:2000'); let currentID = 0; let heartBeat; ws.on('open', () => { button.watch((e, value) => { if(e) { console.error("Error on button watch:", e); return; } if(value) { ws.send(JSON.stringify({type: 'button-press'})); } else { ws.send(JSON.stringify({type: 'button-release'})); } ledOnAir.write(value, (e) => e && console.error("Error writing to led: ", e)); }); heartBeat = setInterval(() => { button.read((e, buttonState) => { console.log("Button state!", buttonState); if(e) { return console.error("Error reading button state!", e); } ws.send(JSON.stringify({ type: 'button-update', body: {buttonState} })); }); }, 400); ledReady.write(1, console.error); }); ws.on('error', (e) => { console.error(e); cleanup(); process.exit(); }); function cleanup() { ledOnAir.unexport(); ledReady.unexport(); button.unexport(); ws.close(); if(heartBeat) { cancelInterval(heartBeat); heartBeat = null; } } process.on('SIGINT', () => { cleanup(); });