ninwa/libs/watchers.js

51 lines
1.4 KiB
JavaScript
Raw Permalink Normal View History

2022-02-15 04:33:19 +01:00
const logger = require('./logger.js');
const Watcher = require('./watcher.js');
const watchers = [];
async function initialize(config) {
2022-03-11 15:47:48 +01:00
if (config === undefined) {
throw new Error('could not initialize watchers, no config defined');
}
2022-03-11 15:47:48 +01:00
if (config.length === 0) {
throw new Error('no watchers defined');
}
for (var index = 0; index < config.length; index++) {
var watcher = new Watcher(config[index], watcherCallback);
await watcher.check();
watchers.push(watcher);
logger.debug('added watcher \'' + watcher.device + '\' to internal map');
}
2022-02-15 04:33:19 +01:00
}
async function start() {
logger.info('starting ' + watchers.length + ' watcher(s)...');
for (var index = 0; index < watchers.length; index++) {
await watchers[index].start();
}
2022-02-15 04:33:19 +01:00
}
async function stop() {
logger.info('stopping ' + watchers.length + ' watcher(s)...');
for (var index = 0; index < watchers.length; index++) {
await watchers[index].stop();
}
2022-02-15 04:33:19 +01:00
}
async function watcherCallback(watcher) {
if (watcher.restart) {
await watcher.start();
return;
}
watchers.splice(watchers.findIndex((foundWatcher) => foundWatcher.device === watcher), 1);
logger.debug('removed watcher \'' + watcher.device + '\' from internal map');
if (watchers.length === 0) {
logger.warn('no watchers are active any longer');
}
2022-02-15 04:33:19 +01:00
}
module.exports = {
initialize,
start,
stop
}