-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
67 lines (61 loc) · 1.99 KB
/
app.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
require("dotenv").config();
const express = require("express");
const path = require("path");
const http = require("http");
const bodyParser = require("body-parser");
const cors = require("cors");
const { InfluxDB, Point } = require("@influxdata/influxdb-client");
const WebSocket = require("ws");
const INFLUXDB_API_TOKEN = process.env.INFLUXDB_API_TOKEN;
const PORT = 3000;
console.log({ PORT, INFLUXDB_API_TOKEN });
const influxDB = new InfluxDB({
url: "http://localhost:8086",
token: INFLUXDB_API_TOKEN,
});
const writeApi = influxDB.getWriteApi("test-organization", "test-bucket");
const queryApi = influxDB.getQueryApi("test-organization");
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
app.get("/data", (req, res) => {
// Query last 5 minutes of data from InfluxDB
const fluxQuery = `from(bucket: "test-bucket")
|> range(start: -5m, stop: now())`;
const query = async () => {
const data = { times: [], values: [] };
for await (const { values, tableMeta } of queryApi.iterateRows(fluxQuery)) {
const o = tableMeta.toObject(values);
const time = new Date(o._time).getTime();
const value = o._value;
data.times.push(time);
data.values.push(value);
}
res.json(data);
};
query();
});
server.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
wss.on("connection", function connection(ws) {
console.log("ws connection");
});
setInterval(() => {
// Spawn data point
const time = Date.now();
const value = 23.0 + Math.random();
// Add data point to InfluxDB
const point = new Point("temperature")
.floatField("value", value)
.timestamp(time);
writeApi.writePoint(point);
// Broadcast new data point to all active clients
const data = JSON.stringify({ time, value });
wss.clients.forEach((client) => {
client.send(data);
});
}, 1000 / 30);