forked from cyberjunky/node-apcupsd
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
executable file
·83 lines (71 loc) · 2.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env node
const exec = require('child_process').exec;
const Mqtt = require('mqtt');
const log = require('yalm');
const pkg = require('./package.json');
const config = require('./config.js');
log.setLevel(config.verbosity);
log.info(pkg.name + ' version ' + pkg.version + ' starting');
const mqtt = Mqtt.connect(config.url);
mqtt.on('connect', () => {
log.info('mqtt connected to', config.url);
});
mqtt.on('close', () => {
log.warn('mqtt connection closed');
});
const datapoints = ['upsname', 'status', 'linev', 'linefreq', 'loadpct', 'battv', 'bcharge', 'timeleft'];
const numeric = ['linev', 'linefreq', 'loadpct', 'battv', 'bcharge', 'timeleft'];
const curvalues = {}; // Holds current values
let devicename = config.upsName;
function executeCmd(cmd, callback) {
exec(cmd, (err, stdout, stderror) => {
if (err) {
callback(err);
} else if (stderror) {
callback(stderror);
} else if (stdout) {
callback(null, stdout);
} else {
callback(null, null);
}
});
}
function poll() {
executeCmd('apcaccess', (err, response) => {
if (err) {
log.error(err);
} else {
log.debug(response);
const lines = response.trim().split('\n');
// Loop over every line
lines.forEach(line => {
// Assign values
let [label, value] = line.split(' : ');
label = label.toLowerCase();
// Remove surrounding spaces
label = label.replace(/(^\s+|\s+$)/g, '');
// If found as wanted value, store it
if (datapoints.indexOf(label) !== -1) {
value = value.replace(/(^\s+|\s+$)/g, '');
if (numeric.indexOf(label) !== -1) {
value = parseFloat(value.split(' ')[0]);
}
if (label === 'upsname') {
devicename = value;
} else if (!config.publishChangesOnly || (curvalues[label] !== value)) {
curvalues[label] = value;
log.debug(value + ' changed!');
// Publish value
const topic = config.name + '/status/' + devicename + '/' + label;
const payload = JSON.stringify({val: value});
log.debug('mqtt >', topic, payload);
mqtt.publish(topic, payload, {retain: true});
}
}
});
}
log.debug(curvalues);
setTimeout(poll, config.interval * 1000);
});
}
poll();