-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathexporter.js
80 lines (71 loc) · 1.91 KB
/
exporter.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
#!/usr/bin/env node
'use strict';
const http = require('http');
const prom = require('prom-client');
const CO2Monitor = require('node-co2-monitor');
const argv = require('yargs').argv;
const settings = {
port: argv.port || 9101,
host: argv.host || '127.0.0.1'
};
// Initialize prometheus metrics.
const _co2Gauge = new prom.Gauge({
'name': 'air_co2',
'help': 'Relative Concentration of CO2 (CntR) in ppm.',
'labels': ['tag']
});
const _tempGauge = new prom.Gauge({
'name': 'air_temp',
'help': 'Ambient Temperature (Tamb) in ℃.',
'labels': ['tag']
});
const register = new prom.Registry();
register.registerMetric(_tempGauge);
register.registerMetric(_co2Gauge);
// Setup CO2 Monitor.
const monitor = new CO2Monitor();
monitor.connect((err) => {
if (err) {
console.error(err.stack);
return process.exit(1);
}
monitor.transfer();
});
let _err;
// Register update events.
monitor.on('temp', (temperature) => {
_tempGauge.set(temperature);
_err = undefined;
});
monitor.on('co2', (co2) => {
_co2Gauge.set(co2);
_err = undefined;
});
monitor.on('error', (err) => {
_err = err;
});
// Start Server.
const server = http.createServer((req, res) => {
// Only allowed to poll prometheus metrics.
if (req.method !== 'GET' && req.url !== '/metrics') {
res.writeHead(404, { 'Content-Type': 'text/html' });
return res.end('Not Found.');
}
if (_err) {
res.writeHead(400, { 'Content-Type': 'text/html' });
return res.end('Device Error.');
}
res.setHeader('Content-Type', register.contentType);
return res.end(register.metrics());
}).listen(settings.port);
server.setTimeout(30000);
// Graceful shutdown.
const shutdown = () => {
server.close(() => {
monitor.disconnect(() => {
process.exit(0);
});
});
};
process.on('SIGTERM', () => shutdown());
process.on('SIGINT', () => shutdown());