-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
52 lines (41 loc) · 1.23 KB
/
server.js
File metadata and controls
52 lines (41 loc) · 1.23 KB
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
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import cors from "cors";
import dotenv from 'dotenv';
import os from "os";
dotenv.config({ quiet: true });
const app = express();
const server = createServer(app);
const io = new Server(server, { cors: { origin: "*" } });
app.use(cors());
app.use(express.static("public"));
let servoAngles = [0, 0, 0, 0];
io.on("connection", (socket) => {
console.log("User connected.");
socket.on("servoData", (data) => {
servoAngles = data;
console.log("New angle values:", servoAngles);
});
socket.on("disconnect", () => {
console.log("User left.");
});
});
app.get("/servo", (req, res) => {
res.json({ angles: servoAngles });
});
function getIPv4Address() {
const interfaces = os.networkInterfaces();
for (const interfaceName in interfaces) {
for (const interfaceDetails of interfaces[interfaceName]) {
if (interfaceDetails.family === 'IPv4' && !interfaceDetails.internal) {
return interfaceDetails.address;
}
}
}
return null;
}
const PORT = process.env.PORT || 3000;
server.listen(PORT, `${getIPv4Address()}`, () => {
console.log(`Server is running at http://${getIPv4Address()}:${PORT}`);
});