const configJSON = require('../config.json'); const logger = require('./logger.js'); const Watcher = require('./watcher.js'); const watchers = []; function initialize() { return new Promise(function (resolve, reject) { if (configJSON == undefined || configJSON.watchers == undefined || configJSON.watchers.length == 0) { reject('no watchers in \'config.json\' defined'); } var tmp = [] for (var index = 0; index < configJSON.watchers.length; index++) { tmp.push(new Watcher(configJSON.watchers[index], watcherCallback)); } Promise.all(tmp.map(check)) .then(resolve) .catch(reject); }); } function check(watcher) { return new Promise((resolve, reject) => { if (watcher == undefined) { reject(); } watcher.check() .then(() => { watchers.push(watcher) logger.debug('added watcher \'' + watcher.device + '\' to internal map'); }) .then(resolve) .catch(reject); }); } function start() { return new Promise((resolve, reject) => { logger.info('starting ' + watchers.length + ' watcher(s)...'); var promises = []; for (var index = 0; index < watchers.length; index++) { promises.push(watchers[index].start()); } Promise.all(promises) .then(resolve) .catch(reject); }); } function stop() { return new Promise((resolve, reject) => { logger.info('stopping ' + watchers.length + ' watcher(s)...'); var promises = []; for (var index = 0; index < watchers.length; index++) { promises.push(watchers[index].stop()); } Promise.all(promises) .then(resolve) .catch(reject); }); } function watcherCallback(watcher) { watchers.splice(watchers.findIndex((foundWatcher) => foundWatcher.device == watcher), 1); logger.debug('removed watcher \'' + watcher + '\' from internal map'); } module.exports = { initialize, start, stop }