-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (52 loc) · 1.86 KB
/
Copy pathserver.js
File metadata and controls
65 lines (52 loc) · 1.86 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
53
54
55
56
57
58
59
60
61
62
63
64
65
const express = require("express");
const WebSocket = require("ws");
const fetch = require("node-fetch");
const app = express();
const port = process.env.PORT || 3000; // Use Render's dynamic port
let lastStatus = "";
// Serve static files
app.use(express.static("public"));
// WebSocket server setup
const wss = new WebSocket.Server({ noServer: true });
async function checkControllers() {
try {
const response = await fetch("https://api.stopbars.com/all");
const data = await response.json();
const runways = data.runways || [];
const stopbars = data.stopbars || [];
const totalControllers = runways.length + stopbars.length;
if (totalControllers > 0) {
let icaoCodes = new Set();
runways.forEach(r => icaoCodes.add(r.airportICAO));
stopbars.forEach(s => icaoCodes.add(s.airportICAO));
let message = Array.from(icaoCodes).join(", ");
if (message !== lastStatus) {
lastStatus = message;
notifyClients(message);
}
}
} catch (error) {
console.error("Error fetching STOPBARS API:", error);
}
}
// Send messages to WebSocket clients
function notifyClients(message) {
console.log("🔔 Sending notification:", message);
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
// Poll API every 30 seconds
setInterval(checkControllers, 30000);
// Start Express server
const server = app.listen(port, () => {
console.log(`🚀 Server running on http://localhost:${port} or Render's assigned domain`);
});
// WebSocket Upgrade Handling (needed for Render)
server.on("upgrade", (request, socket, head) => {
wss.handleUpgrade(request, socket, head, ws => {
wss.emit("connection", ws, request);
});
});