-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.mjs
53 lines (42 loc) · 1.38 KB
/
server.mjs
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
import express from 'express';
import client from 'prom-client';
import Tesla from './src/tesla.mjs';
import { updateMetrics, logger } from './src/utils.mjs';
// Disable SSL verification since Tesla use self-signed certificates
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const app = express();
app.use(express.json());
app.get('/', (req, res) => res.status(200).send(`
<html>
<head><title>Tesla Powerwall Exporter</title></head>
<body>
<h1>Tesla Powerwall Exporter</h1>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>
`));
app.get('/metrics', async (req, res) => {
res.set('Content-type', client.register.contentType);
res.status(200).send(await client.register.metrics());
});
const PORT = parseInt(process.env.PORT, 10) || 9961;
const SCRAPE_INTERVAL = parseInt(process.env.SCRAPE_INTERVAL, 10) * 1000 || 30000;
['TESLA_ADDR', 'TESLA_EMAIL', 'TESLA_PASSWORD'].forEach((e) => {
if (!(e in process.env)) {
logger.error(`missing ${e} environment variable`);
process.exit(1);
}
});
try {
const tesla = new Tesla(process.env.TESLA_EMAIL, process.env.TESLA_PASSWORD);
await tesla.login();
app.listen(PORT, () => {
logger.info(`Listening on 0.0.0.0:${PORT}`);
});
// Perform an initial scrape of the Powerwalls
await updateMetrics(tesla);
setInterval(updateMetrics, SCRAPE_INTERVAL, tesla);
} catch (error) {
logger.error(error.message);
process.exit(1);
}