-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (99 loc) · 3.12 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const express = require('express');
const Battery = require('./lib/battery');
const Speed = require('./lib/speed');
const Timeout = require('./lib/timeout');
const exporter_build = require('./lib/exporter_build');
const {verify_token_from_file} = require('./lib/auth');
const app = express();
const port = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.json());
battery_info = new Battery();
speed_info = new Speed();
timeout = new Timeout();
app.get('/', (req, res) => {
res.send(`
<html lang="en">
<head>
<title>Metrics</title>
</head>
<body>
<a href="/metrics">Metrics</a>
</body>
</html>
`);
});
app.post('/api/battery/', (req, res) => {
try {
const data = req.body;
if (!data) {
res.status(400).send('request body is required');
}
if (!data.auth) {
res.status(403).send('token is required');
}
if (!data.temp) {
res.status(400).send('temp is required');
}
if (!data.voltage) {
res.status(400).send('voltage is required');
}
if (isNaN(data.temp)) {
res.status(400).send('temp must be a number');
}
if (isNaN(data.voltage)) {
res.status(400).send('voltage must be a number');
}
if (verify_token_from_file(data.auth)) {
timeout.resetTimeout();
battery_info.setTemp(data.temp);
battery_info.setVoltage(data.voltage);
res.status(200).send("ok");
} else {
res.status(403).send('invalid token');
}
} catch (err) {
res.status(500).send(err);
}
})
app.post('/api/speed/', (req, res) => {
try {
const data = req.body;
if (!data) {
res.status(400).send('request body is required');
}
if (!data.auth) {
res.status(403).send('token is required');
}
if (!data.speed) {
res.status(400).send('speed is required');
}
if (!data.accel) {
res.status(400).send('accel is required');
}
if (isNaN(data.speed)) {
res.status(400).send('speed must be a number');
}
if (isNaN(data.accel)) {
res.status(400).send('accel must be a number');
}
if (verify_token_from_file(data.auth)) {
timeout.resetTimeout();
speed_info.setSpeed(data.speed);
speed_info.setAccel(data.accel);
res.status(200).send("ok");
} else {
res.status(403).send('invalid token');
}
} catch (err) {
res.status(500).send(err);
}
})
app.get('/metrics', (req, res) => {
res.set('Content-Type', 'text/plain');
res.send(battery_info.getTemp() + battery_info.getVoltage() + speed_info.getSpeed() + speed_info.getAccel() + timeout.getTimeout() + exporter_build());
});
app.listen(port, () => {
console.log(`SRC Exporter listening on http://localhost:${port}`);
console.log(`Metrics: http://localhost:${port}/metrics`);
});