-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (60 loc) · 1.92 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
const express = require("express");
require('dotenv').config()
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
cors: {
origin: "*",
},
});
const axios = require("axios");
const port = process.env.PORT || 3000;
var sleep = (time) => new Promise((resolve) => setTimeout(resolve, time));
var poll = (promiseFn, time) =>
promiseFn().then(sleep(time).then(() => poll(promiseFn, time)));
// Greet the World every second
poll(
() =>
new Promise(() => {
// Make a request for a user with a given ID
axios
.get(process.env.NIGHTSCOUT_URL + "api/v1/entries/sgv.json?find[device]=share2&count=30")
.then(function (response) {
// handle success
if (global.dateString !== response.data[0].dateString) {
console.log("New reading detected");
io.emit("reading", response.data[0]);
}
global.dateString = response.data[0].dateString;
global.lastReading = response.data[0];
global.retro = response.data;
console.log(
"tick: " + response.data[0].sgv + " at " + response.data[0].dateString
);
})
.catch(function (error) {
// handle error
console.log(error);
});
}),
15000
);
io.on("connect", (socket) => {
console.log("User " + socket.id + " connected");
//emit retro to that new connection only
io.to(socket.id).emit("retro", global.retro);
//first time emit the last reading to that new connection only
io.to(socket.id).emit("reading", global.lastReading);
socket.on("disconnect", () => {
console.log("User " + socket.id + " disconnected");
});
});
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.use(express.static("static"));
server.listen(port, () => {
console.log("listening " + port);
});