ninwa/libs/watchers.js
2022-02-15 04:33:19 +01:00

62 lines
No EOL
1.7 KiB
JavaScript

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('error: no input devices defined');
}
var tmp = []
for (var index = 0; index < configJSON.watchers.length; index++) {
tmp.push(new Watcher(configJSON.watchers[index]));
}
Promise.all(tmp.map(check)).then(resolve);
});
}
function check(watcher) {
return new Promise(function (resolve, reject) {
if (watcher == undefined) {
reject();
}
watcher.check()
.then(() => {
logger.info('watcher \'' + watcher.device)
watcher.start();
watchers.push(watcher);
})
.catch((err) => {
logger.error(err);d
});
});
}
function start() {
logger.debug('starting ' + watchers.size + ' watcher(s)...');
for (const watcher of watchers.entries()) {
watcher[1].start();
}
}
function stop() {
const count = watchers.size;
logger.info('stopping all ' + count + ' watchers...');
for (var index = 0; index < count; index++) {
var watcher = watchers[index];
logger.debug('stopping watcher ' + watcher.id + '...');
watcher.kill();
}
}
function callback(err, id, code) {
this.watchers.delete(id);
logger.debug('removed watcher \'' + id + '\'');
}
module.exports = {
initialize,
start,
stop
}