cyberpower-exporter/ups-exporter.js

55 lines
1.7 KiB
JavaScript
Raw Normal View History

2024-07-22 13:44:29 -04:00
import { $ } from 'bun';
import http from 'http';
2024-07-22 13:58:53 -04:00
const port = 1024;
2024-07-22 13:44:29 -04:00
async function scrape() {
const data = await $`pwrstat -status`.text();
const r = /^\s*(.+?)\.{3,} (.+)$/gm;
let found, map = {};
while(!!(found = r.exec(data)))
map[found[1]] = found[2];
2024-07-22 15:29:56 -04:00
if(map["Remaining Runtime"]) {
const parsed = /(\d+) (.)/gi.exec(map["Remaining Runtime"]);
const unit = parsed[2].toLowerCase();
if(unit == 'm') map["Remaining Runtime"] = Number(parsed[1]) * 60;
if(unit == 'h') map["Remaining Runtime"] = Number(parsed[1]) * 60 * 60;
}
2024-07-22 13:44:29 -04:00
return {
2024-07-22 15:21:10 -04:00
model: map["Model Name"],
vendor: map["Power Supply by"],
state: map["State"],
charge: Number(/\d+/g.exec(map["Battery Capacity"])[0]) / 100,
2024-07-22 15:29:56 -04:00
battery_time: map["Remaining Runtime"],
2024-07-22 15:21:10 -04:00
rated_voltage: Number(/\d+/g.exec(map["Rating Voltage"])[0]),
rated_wattage: Number(/\d+/g.exec(map["Rating Power"])[0]),
2024-07-22 16:29:15 -04:00
input_state: map["State"] == 'Normal' ? 1 : 0,
2024-07-22 15:21:10 -04:00
input_voltage: Number(/\d+/g.exec(map["Utility Voltage"])[0]),
output_voltage: Number(/\d+/g.exec(map["Output Voltage"])[0]),
load_wattage: Number(/\d+/g.exec(map["Load"])[0]),
load_percentage: Number(/(\d+) %/g.exec(map["Load"])[1]) / 100,
// last_test: map["Test Result"],
// last_outage: map["Last Power Event"],
2024-07-22 13:44:29 -04:00
};
}
function format(a) {
2024-07-22 15:21:10 -04:00
let labels = Object.entries(a).filter(([key, value]) => typeof value == 'string')
.map(([key, value]) => `${key}="${value}"`)
.join(', ');
if(labels) labels = `{${labels}}`;
2024-07-22 15:29:56 -04:00
return Object.entries(a)
.map(([key, value]) => `ups_${key}${labels} ${typeof value == 'string' ? 1 : value}`)
2024-07-22 15:21:10 -04:00
.join('\n');
2024-07-22 13:44:29 -04:00
}
http.createServer(async (req, res) => {
res.end(format(await scrape()));
}).listen(port, () => {
console.log(`Exporter running on http://localhost:${port}`)
});