ninwa/libs/watchers.js

65 lines
No EOL
1.9 KiB
JavaScript

const logger = require('./logger.js');
const Watcher = require('./watcher.js');
const watchers = [];
async function initialize() {
if (global.config == undefined) {
throw new Error('could not initialize watchers, no config defined');
}
if (global.config.watchers == undefined || global.config.watchers.length == 0) {
throw new Error('no watchers in config \'' + global.config.path + '\' defined');
}
for (var index = 0; index < global.config.watchers.length; index++) {
var watcher = new Watcher(global.config.watchers[index], watcherCallback);
try {
await watcher.check();
watchers.push(watcher);
logger.debug('added watcher \'' + watcher.device + '\' to internal map');
} catch(err) {
logger.error(err);
}
}
}
async function start() {
logger.info('starting ' + watchers.length + ' watcher(s)...');
for (var index = 0; index < watchers.length; index++) {
try {
await watchers[index].start();
} catch (err) {
logger.error(err);
}
}
}
async function stop() {
logger.info('stopping ' + watchers.length + ' watcher(s)...');
for (var index = 0; index < watchers.length; index++) {
try {
await watchers[index].stop();
} catch (err) {
logger.error(err);
}
}
}
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 + '\' from internal map');
if (watchers.length === 0) {
logger.info('no watchers are active any longer');
logger.info(global.appName + ' ' + global.appVersion + ' exiting with code \'0\'');
process.exit(0);
}
}
module.exports = {
initialize,
start,
stop
}