Spaces:
Running
Running
File size: 15,018 Bytes
5774ae9 22311b8 5774ae9 5981742 5774ae9 5981742 5774ae9 5981742 5774ae9 5981742 5774ae9 5981742 5774ae9 5981742 22311b8 5981742 5774ae9 5981742 5774ae9 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5774ae9 22311b8 5774ae9 22311b8 5774ae9 22311b8 5981742 5774ae9 22311b8 5774ae9 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 22311b8 5981742 1c677e7 22311b8 5981742 22311b8 5774ae9 22311b8 0f7cf98 2a260f0 22311b8 5774ae9 22311b8 5774ae9 22311b8 5774ae9 22311b8 5774ae9 22311b8 5774ae9 22311b8 5774ae9 22311b8 5774ae9 |
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
// server.js (Node.js with Express and ws)
const express = require('express');
const { WebSocketServer } = require('ws');
const cors = require('cors'); // Import CORS
const { initializeApp, cert } = require('firebase-admin/app');
const { getFirestore } = require('firebase-admin/firestore');
var admin = require("firebase-admin");
const serviceAccount = require("./serviceAcc.json");
initializeApp({
credential: cert(serviceAccount)
});
const db = getFirestore();
const app = express();
const port = process.env.PORT || 8080;
const wss = new WebSocketServer({ noServer: true });
app.use(cors());
initialData = { devices: [], rooms: [], users: [] }; // Provide default empty data on error
let currentDeviceStates = {};
// const fetchInitialData = async () => {
// const devices = [];
// const rooms = [];
// const users = [];
// try {
// const deviceSnapshot = await db.collection('Devices').get();
// deviceSnapshot.forEach(doc => devices.push({ id: doc.id, ...doc.data() }));
// const roomsSnapshot = await db.collectionGroup('Rooms').get(); // Get all rooms across hostels
// roomsSnapshot.forEach(doc => rooms.push({ id: doc.id, ...doc.data(), hostelId: doc.ref.parent.parent.id })); // Include hostelId
// const usersSnapshot = await db.collection('Users').get();
// usersSnapshot.forEach(doc => users.push({ id: doc.id, ...doc.data() }));
// initialData = { devices, rooms, users };
// // console.log("Initial data fetched:", initialData);
// //for each hostel id mantain a list of rooms with devices pertaining to that hostel
// //setall to off
// initialData.devices.forEach(device => {
// device.state = false;
// } );
// initialData.rooms.forEach(room => {
// if (!currentDeviceStates[room.id]) {
// currentDeviceStates[room.id] = [];
// }
// const roomDevices = initialData.devices.filter(device => device.hostelId === room.hostelId);
// currentDeviceStates[room.id] = { ...room, devices: roomDevices };
// });
// } catch (error) {
// console.error("Error fetching initial data:", error);
// // return { devices: [], rooms: [], users: [] };
// initialData = { devices, rooms, users };
// }
// };
// const fetchInitialData = async () => {
// try {
// const [deviceSnapshot, roomsSnapshot, usersSnapshot] = await Promise.all([
// db.collection('Devices').get(),
// db.collectionGroup('Rooms').get(),
// db.collection('Users').get()
// ]);
// const devices = deviceSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// const rooms = roomsSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), hostelId: doc.ref.parent.parent.id }));
// const users = usersSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
// initialData = { devices, rooms, users };
// initialData.devices.forEach(device => {
// device.state = false;
// });
// initialData.rooms.forEach(room => {
// const roomDevices = initialData.devices.filter(device => device.hostelId === room.hostelId);
// currentDeviceStates[room.id] = { ...room, devices: roomDevices.map(device => ({...device})) }; // Deep copy to avoid modifying initialData
// });
// console.log("Initial data fetched and processed.");
// } catch (error) {
// console.error("Error fetching initial data:", error);
// initialData = { devices: [], rooms: [], users: [] }; // Provide default empty data on error
// currentDeviceStates = {};
// }
// };
// fetchInitialData().then(() => {
// setupFirestoreListeners();
// });
// const updateInitialData = (collectionName, snapshot) => {
// const changes = snapshot.docChanges();
// changes.forEach(change => {
// const docData = { id: change.doc.id, ...change.doc.data() };
// console.log(change.type, collectionName, "\t");
// var index;
// switch (change.type) {
// case 'added':
// index = initialData[collectionName]?.findIndex(item => item.id === change.doc.id);
// if (index !== -1) {
// initialData[collectionName][index] = docData;
// }
// else {
// initialData[collectionName].push(docData);
// }
// console.log("Length of ", collectionName, " is ", initialData[collectionName].length);
// console.log("DATA: ",docData);
// break;
// case 'modified':
// index = initialData[collectionName].findIndex(item => item.id === change.doc.id);
// if (index !== -1) {
// initialData[collectionName][index] = docData;
// for (const roomId in currentDeviceStates) {
// const roomDevices = currentDeviceStates[roomId].devices;
// const deviceIndex = roomDevices.findIndex(dev => dev.id === change.doc.id);
// if (deviceIndex !== -1) {
// currentDeviceStates[roomId].devices[deviceIndex] = {...docData, state: roomDevices[deviceIndex].state}
// }
// }
// }
// break;
// case 'removed':
// initialData[collectionName] = initialData[collectionName].filter(item => item.id !== change.doc.id);
// break;
// }
// });
// console.log(`Updated ${collectionName} in initialData.\n\n`);
// if (collectionName === 'devices' || collectionName === 'rooms') {
// rebuildCurrentDeviceStates();
// }
// };
// const setupFirestoreListeners = () => {
// db.collection('Devices').onSnapshot(snapshot => {
// updateInitialData('devices', snapshot);
// });
// db.collectionGroup('Rooms').onSnapshot(snapshot => {
// updateInitialData('rooms', snapshot);
// });
// db.collection('Users').onSnapshot(snapshot => {
// updateInitialData('users', snapshot);
// });
// }
// const rebuildCurrentDeviceStates = () => {
// currentDeviceStates = {};
// initialData.rooms.forEach(room => {
// const roomDevices = initialData.devices.filter(device => device.hostelId === room.hostelId);
// currentDeviceStates[room.id] = { ...room, devices: roomDevices.map(device => ({ ...device})) };
// console.log("Rebuilt room: ", room.roomNumber, " with ", roomDevices.length, " devices.","all Devices", room.hostelId);
// });
// console.log("currentDeviceStates rebuilt.");
// }
// // fetchInitialData().then(() => {
// // setupFirestoreListeners();
// // });
// setupFirestoreListeners();
const fetchInitialData = async () => {
try {
const [deviceSnapshot, roomsSnapshot, usersSnapshot] = await Promise.all([
db.collection('Devices').get(),
db.collectionGroup('Rooms').get(),
db.collection('Users').get()
]);
initialData.devices = deviceSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), state: false })); // Initialize state to false
initialData.rooms = roomsSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), hostelId: doc.ref.parent.parent.id }));
initialData.users = usersSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
rebuildCurrentDeviceStates(); // Rebuild after fetching initial data
console.log("Initial data fetched and processed.");
} catch (error) {
console.error("Error fetching initial data:", error);
initialData = { devices: [], rooms: [], users: [] };
currentDeviceStates = {};
}
};
const updateInitialData = (collectionName, snapshot) => {
snapshot.docChanges().forEach(change => {
let docData;
if (collectionName === 'rooms') {
docData = { id: change.doc.id, ...change.doc.data(), hostelId: change.doc.ref.parent.parent.id };
} else {
docData = { id: change.doc.id, ...change.doc.data() };
}
let index;
switch (change.type) {
case 'added':
console.log('added', collectionName, docData);
if (!initialData[collectionName].some(item => item.id === change.doc.id)) {
initialData[collectionName].push(docData);
if (collectionName === 'devices') {
initialData[collectionName][initialData[collectionName].length - 1].state = false;
}
}
break;
case 'modified':
console.log('modified', collectionName, docData);
index = initialData[collectionName].findIndex(item => item.id === change.doc.id);
if (index !== -1) {
initialData[collectionName][index] = docData;
if (collectionName === 'devices') {
for (const roomId in currentDeviceStates) {
const roomDevices = currentDeviceStates[roomId].devices;
const deviceIndex = roomDevices?.findIndex(dev => dev.id === change.doc.id);
if (deviceIndex !== -1) {
console.log("Device found in room", roomId, "old state", roomDevices[deviceIndex].state, "new state", docData.state);
currentDeviceStates[roomId].devices[deviceIndex] = { ...docData, state: roomDevices[deviceIndex].state };
console.log(currentDeviceStates[roomId]);
}
}
}
}
break;
case 'removed':
console.log('removed', collectionName, docData);
initialData[collectionName] = initialData[collectionName].filter(item => item.id !== change.doc.id);
break;
}
});
console.log(`Updated ${collectionName} in initialData.\n\n`);
if (collectionName === 'devices' || collectionName === 'rooms') {
rebuildCurrentDeviceStates();
}
};
const setupFirestoreListeners = () => {
db.collection('Devices').onSnapshot(snapshot => updateInitialData('devices', snapshot));
db.collectionGroup('Rooms').onSnapshot(snapshot => updateInitialData('rooms', snapshot));
db.collection('Users').onSnapshot(snapshot => updateInitialData('users', snapshot));
};
const rebuildCurrentDeviceStates = () => {
initialData.rooms.forEach(room => {
if (!room.hostelId) {
console.warn(`Room ${room.id} is missing hostelId`);
return;
}
const roomDevices = initialData.devices.filter(device => device.hostelId === room.hostelId);
if (!currentDeviceStates[room.id]) {
currentDeviceStates[room.id] = { ...room, devices: roomDevices.map(device => ({ ...device })) };
} else {
currentDeviceStates[room.id] = {
...room,
devices: roomDevices.map(device => ({
...device,
state: currentDeviceStates[room.id].devices.find(dev => dev.id === device.id)?.state || false,
})),
};
}
});
console.log("currentDeviceStates rebuilt.");
broadcastRoomData();
};
const broadcastRoomData = () => {
for (const roomId in connectedClients) {
connectedClients[roomId].forEach(client => {
if (currentDeviceStates[roomId]) {
console.log(currentDeviceStates[roomId]);
client.send(JSON.stringify({ type: 'roomData', roomData: currentDeviceStates[roomId] , roomId: roomId}));
}
});
}
};
// Call fetchInitialData and then set up listeners
fetchInitialData()
.then(setupFirestoreListeners) // Set up listeners AFTER fetching initial data
.catch(error => {
console.error("Error initializing:", error);
});
const connectedClients = {}; // Store connected clients per room
wss.on('connection', (ws) => {
ws.on('message', async (message) => {
try {
const parsedMessage = JSON.parse(message);
const { roomId, userId, apiKey } = parsedMessage;
// Helper function to check authorization
const isAuthorized = (roomId, userId, apiKey) => {
return initialData.users.some(user => user.id === userId && user.roomId === roomId) || apiKey === "masterPassword@tiet@123";
};
switch (parsedMessage.type) {
case 'joinRoom':
if (!roomId || !(userId || apiKey)) {
ws.send(JSON.stringify({ error: 'Invalid room or user ID or apikey' }));
return;
}
if (!isAuthorized(roomId, userId, apiKey)) {
console.log("Unauthorized joinRoom attempt.");
ws.send(JSON.stringify({ error: 'Unauthorized' }));
return;
}
// Store the connected client
if (!connectedClients[roomId]) {
connectedClients[roomId] = [];
}
connectedClients[roomId].push(ws);
ws.send(JSON.stringify({ type: 'roomData', roomData: currentDeviceStates[roomId], roomId: roomId }));
break;
case 'updateDeviceState':
const { deviceId, state } = parsedMessage;
if (!deviceId || state === undefined || !roomId || (!userId && !apiKey)) { // Check for undefined state or missing userId/apiKey
ws.send(JSON.stringify({ error: 'Invalid device ID, state, room ID, user ID, or API key' }));
return;
}
if (!isAuthorized(roomId, userId, apiKey)) {
console.log("Unauthorized updateDeviceState attempt.");
ws.send(JSON.stringify({ error: 'Unauthorized' }));
return;
}
const room = currentDeviceStates[roomId];
if (room) { // Check if the room exists
const device = room.devices.find(dev => dev.id === deviceId);
if (device) { // Check if the device exists
device.state = state;
// Broadcast to all clients in the room
if (connectedClients[roomId]) {
connectedClients[roomId].forEach(client => {
client.send(JSON.stringify({ type: 'deviceUpdate', deviceId, state, roomId: roomId }));
});
}
} else {
ws.send(JSON.stringify({ error: 'Device not found' }));
}
} else {
ws.send(JSON.stringify({ error: 'Room not found' }));
}
break;
default:
console.log('Unknown message type:', parsedMessage.type);
}
} catch (error) {
console.error('Error handling message:', error);
ws.send(JSON.stringify({ error: 'Invalid message format' })); // Send error back to client
}
});
ws.on('close', () => {
for (const roomId in connectedClients) {
connectedClients[roomId] = connectedClients[roomId].filter(client => client !== ws);
}
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
});
console.log('WebSocket server started on port 8080');
const server = app.listen(port, () => console.log(`Listening on port ${port}`));
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, ws => {
wss.emit('connection', ws, request);
});
}); |