From 3f129ceec2c1709bad9d1be2bfb2d85d650f22cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ab=C3=A1sz?= <> Date: Tue, 3 Jan 2023 10:50:27 +0100 Subject: [PATCH] Add peripheral shutdown for app termination In order to avoid errors with peripheral processes on the next startup (e.g. ANT Stick getting stuck) graceful explicit shutdown of these is necessary on app termination. --- app/peripherals/PeripheralManager.js | 14 ++++++++++++++ app/server.js | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/app/peripherals/PeripheralManager.js b/app/peripherals/PeripheralManager.js index 349863a..df793d7 100644 --- a/app/peripherals/PeripheralManager.js +++ b/app/peripherals/PeripheralManager.js @@ -264,7 +264,21 @@ function createPeripheralManager () { emitter.emit('control', event) } + async function shutdownAllPeripherals () { + log.debug('shutting down all peripherals') + + try { + await blePeripheral?.destroy() + await antPeripheral?.destroy() + await hrmPeripheral?.destroy() + await _antManager?.closeAntStick() + } catch (error) { + log.error('peripheral shutdown was unsuccessful, restart of Pi may required', error) + } + } + return Object.assign(emitter, { + shutdownAllPeripherals, getBlePeripheral, getBlePeripheralMode, getAntPeripheral, diff --git a/app/server.js b/app/server.js index b64bb26..b6a28fc 100644 --- a/app/server.js +++ b/app/server.js @@ -140,6 +140,22 @@ function resetWorkout () { const gpioTimerService = child_process.fork('./app/gpio/GpioTimerService.js') gpioTimerService.on('message', handleRotationImpulse) +process.once('SIGINT', async (signal) => { + log.debug(`${signal} signal was received, shutting down gracefully`) + await peripheralManager.shutdownAllPeripherals() + process.exit(0) +}) +process.once('SIGTERM', async (signal) => { + log.debug(`${signal} signal was received, shutting down gracefully`) + await peripheralManager.shutdownAllPeripherals() + process.exit(0) +}) +process.once('uncaughtException', async (error) => { + log.error('Uncaught Exception:', error) + await peripheralManager.shutdownAllPeripherals() + process.exit(1) +}) + function handleRotationImpulse (dataPoint) { workoutRecorder.recordRotationImpulse(dataPoint) rowingStatistics.handleRotationImpulse(dataPoint)