Sebebeb commited on
Commit
e4bb8c1
·
verified ·
1 Parent(s): 6f6a05d

Create app.js

Browse files
Files changed (1) hide show
  1. app.js +81 -0
app.js ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require("express");
2
+ const http = require("http");
3
+ const WebSocket = require("ws");
4
+ const path = require("path");
5
+
6
+ const PORT = process.env.PORT || 7860;
7
+
8
+ const app = express();
9
+ const server = http.createServer(app);
10
+
11
+ app.use(express.static(path.join(__dirname, "public")));
12
+
13
+ const wss = new WebSocket.Server({ server, path: "/ws" });
14
+
15
+ const uuidToSocket = new Map();
16
+ const socketToUUID = new Map();
17
+
18
+ let devices = [];
19
+
20
+ function getDevice(uuid) {
21
+ return devices.find(device => device.uuid === uuid);
22
+ }
23
+
24
+ function generateUUID() {
25
+ let id;
26
+ do {
27
+ id = Math.floor(Math.random() * 1e16);
28
+ } while (getDevice(id));
29
+ return id;
30
+ }
31
+
32
+ wss.on("connection", (ws) => {
33
+
34
+ ws.send(JSON.stringify({"method": "request", "content": "UUID"}));
35
+
36
+ ws.on("message", (message) => {
37
+ if (message["UUID"] == null) {
38
+ id = generateUUID();
39
+ ws.UUID = id;
40
+ devices.push({
41
+ "UUID": id,
42
+ "Name": null,
43
+ "Notifications": [{
44
+ "Displayed": false,
45
+ "Time": Date.now(),
46
+ "Heading": "Success",
47
+ "Content": "Successfully connected to server."
48
+ }],
49
+ "LastConnection": 0
50
+ });
51
+ } else if (!message["UUID"] && !ws.UUID) {
52
+ ws.send(JSON.stringify({"request": "UUID"}));
53
+ } else if (typeof message["UUID"] === "number" && !Number.isNaN(value)) {
54
+ ws.UUID = message["UUID"];
55
+ ws.
56
+ ws.send(JSON.stringify({"method": "request", "content": "all"}));
57
+ }
58
+
59
+ // Request response handling
60
+ else if (message["method"] === "response") {
61
+ if (message["response"] === "all") {
62
+ const serverDevice = getDevice(ws.UUID);
63
+ const clientDevice = JSON.parse(message["content"]);
64
+ if (!clientDevice["Name"]) { console.error("Device " + ws.UUID + " missing name on 'all' response");}
65
+ if (!clientDevice["Notifications"]) { console.error("Device " + ws.UUID + " missing notifications on 'all' response");}
66
+ serverDevice.Name = clientDevice["Name"];
67
+ serverDevice.Notifications.push(...clientDevice["Notifications"]);
68
+ }
69
+ }
70
+ });
71
+
72
+ ws.on("close", () => {
73
+ const device = getDevice(ws.UUID);
74
+ device.LastConnection = Date.now();
75
+ });
76
+
77
+ });
78
+
79
+ server.listen(PORT, "0.0.0.0", () => {
80
+ console.log(`Server running on ${PORT}`);
81
+ });