This repository has been archived by the owner on Dec 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
49 lines (45 loc) · 1.65 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
import { DynamicMultipleThings } from "./dynamic-server.js";
import { WebThingServer } from "webthing";
import WebSocketThing from "./ws-thing.js";
import express from "express";
import { internalIpV4 } from "internal-ip";
const PORT = 8080;
internalIpV4().then((ip) => {
const things = new DynamicMultipleThings('browser-things');
const server = new WebThingServer(things, PORT, ip, undefined, [
{
path: '/static',
handler: express.static(new URL('./static', import.meta.url).pathname)
},
]);
server.app.ws('/comm/ws', (ws) => {
let thing;
ws.on('message', (rawMessage) => {
const message = JSON.parse(rawMessage);
if(message.type !== 'create' && !thing) {
ws.send(JSON.stringify({type: 'error', message: 'You must first initialize the thing.'}));
}
switch(message.type) {
case 'create':
thing = new WebSocketThing(ws, message);
things.register(thing, thing.id);
thing.registered(`${ip}:${PORT}`);
break;
case 'update':
for(const sensor of message.sensors) {
thing.updateSensor(sensor);
}
break;
case 'visibilitychange':
thing.updateVisibility(message.hidden);
break;
default:
console.log("unknown message", message);
}
});
ws.on('close', () => {
things.unregister(thing);
});
});
server.start();
});