-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (54 loc) · 2 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
// server.js
import express from "express";
import mongoose from "mongoose";
import dotenv from 'dotenv';
import { Server } from 'socket.io';
import { verifyToken } from "./middleware/authMiddleware.js";
import { utilizationRoute, authRoute, storeUtilizationRoute, deviceRoute, userDeviceRoute } from "./routes/index.js";
import { SocketDevice } from "./socket/socketDevice.js";
dotenv.config();
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/api/auth", authRoute);
app.use("/api/utilization", verifyToken, utilizationRoute);
app.use("/api/storeutilization", storeUtilizationRoute);
app.use("/api/device", deviceRoute);
app.use("/api/user-device", verifyToken, userDeviceRoute);
const PORT = process.env.PORT || 5000;
let io;
const socketDeviceMap = {};
mongoose.connect(process.env.CONNECTION_URL)
.then(() => {
const server = app.listen(PORT, () => {
console.log(`Server running at ${PORT}`);
});
io = new Server(server);
io.on('connection', (socket) => {
console.log('Client connected');
const socketDevice = new SocketDevice(socket.id);
socketDeviceMap[socket.id] = socketDevice;
socket.on('setDevices', (deviceIds) => {
socketDevice.addDeviceIds(deviceIds);
});
socket.on('disconnect', () => {
delete socketDeviceMap[socket.id];
console.log('Client disconnected');
});
});
})
.catch((error) => {
console.log(error);
});
export const updateDeviceStatus = (deviceId, deviceOn) => {
try {
for (const socketId in socketDeviceMap) {
const socketDevice = socketDeviceMap[socketId];
if (socketDevice.deviceIds.includes(deviceId)) {
io.to(socketId).emit('deviceStatus', { deviceId, deviceOn });
}
}
} catch (error) {
console.error('Error updating device status:', error);
}
};