ninwa/libs/watchers.js

74 lines
No EOL
2.1 KiB
JavaScript

const logger = require('./logger.js');
const Watcher = require('./watcher.js');
const watchers = [];
function initialize(config) {
return new Promise(function (resolve, reject) {
if (config == undefined || config.path == undefined) {
reject('no config defined');
}
config = require(config.path);
if (config.watchers == undefined || config.watchers.length == 0) {
reject('no watchers in config defined');
}
var tmp = []
for (var index = 0; index < config.watchers.length; index++) {
tmp.push(new Watcher(config.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
}