-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathws-mock.mjs
More file actions
209 lines (174 loc) · 5.8 KB
/
ws-mock.mjs
File metadata and controls
209 lines (174 loc) · 5.8 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
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
#!/usr/bin/env node
import { WebSocketServer } from "ws";
const PORT = 8787;
// Simulate sensor locations in Eldorado National Forest, CA
const SENSOR_LOCATIONS = [
{ id: "eldorado_01", lat: 38.82, lon: -120.35, name: "Crystal Basin" },
{
id: "eldorado_02",
lat: 38.75,
lon: -120.45,
name: "Desolation Wilderness",
},
{ id: "eldorado_03", lat: 38.88, lon: -120.28, name: "Lake Tahoe Basin" },
{ id: "eldorado_04", lat: 38.71, lon: -120.52, name: "American River" },
{ id: "eldorado_05", lat: 38.93, lon: -120.41, name: "Granite Chief" },
{ id: "eldorado_06", lat: 38.67, lon: -120.38, name: "Silver Fork" },
{ id: "eldorado_07", lat: 38.85, lon: -120.48, name: "Hell Hole Reservoir" },
{ id: "eldorado_08", lat: 38.78, lon: -120.32, name: "Echo Lake" },
];
// Track sensor states for realistic progression
const sensorStates = new Map();
function initializeSensorStates() {
SENSOR_LOCATIONS.forEach((location) => {
sensorStates.set(location.id, {
...location,
basePM25: 10 + Math.random() * 20, // Base level 10-30
trend: (Math.random() - 0.5) * 0.5, // Trend factor
lastUpdate: Date.now(),
});
});
}
function generateSensorReading(sensorId) {
const state = sensorStates.get(sensorId);
if (!state) return null;
const now = Date.now();
const timeDelta = (now - state.lastUpdate) / 1000; // seconds
// Add some random walk behavior
const randomChange = (Math.random() - 0.5) * 2; // ±1 μg/m³
const trendChange = state.trend * timeDelta * 0.1;
// Update base level with bounds
state.basePM25 = Math.max(
5,
Math.min(200, state.basePM25 + randomChange + trendChange)
);
state.lastUpdate = now;
// Add some noise
const currentPM25 = Math.max(0, state.basePM25 + (Math.random() - 0.5) * 5);
return {
id: sensorId,
lat: state.lat,
lon: state.lon,
pm25: Math.round(currentPM25 * 10) / 10,
humidity: 40 + Math.random() * 30, // 40-70%
tempC: 18 + Math.random() * 12, // 18-30°C
ts: now,
};
}
function generateBatch(count = 5) {
const sensors = Array.from(sensorStates.keys());
const selectedSensors = sensors
.sort(() => Math.random() - 0.5)
.slice(0, Math.min(count, sensors.length));
const points = selectedSensors.map(generateSensorReading).filter(Boolean);
return {
type: "batch",
points,
};
}
function generateDelta() {
const sensors = Array.from(sensorStates.keys());
const randomSensor = sensors[Math.floor(Math.random() * sensors.length)];
const point = generateSensorReading(randomSensor);
return point
? {
type: "delta",
point,
}
: null;
}
function simulateFireEvent() {
console.log("🔥 Simulating fire event - increasing PM2.5 levels");
// Pick a random sensor as the fire origin
const sensors = Array.from(sensorStates.keys());
const originSensor = sensors[Math.floor(Math.random() * sensors.length)];
const originState = sensorStates.get(originSensor);
// Increase PM2.5 for nearby sensors
sensorStates.forEach((state, id) => {
const distance = Math.sqrt(
Math.pow(state.lat - originState.lat, 2) +
Math.pow(state.lon - originState.lon, 2)
);
// Sensors within 0.2 degrees (~22km) are affected
if (distance < 0.2) {
const intensity = Math.max(0.1, 1 - distance / 0.2); // Closer = more affected
state.basePM25 += 50 * intensity; // Add 50+ μg/m³ based on proximity
state.trend = Math.max(state.trend, 0.5 * intensity); // Positive trend
}
});
}
// Initialize WebSocket server
const wss = new WebSocketServer({ port: PORT });
console.log(`🚀 WebSocket mock server started on ws://localhost:${PORT}/ws`);
console.log("📡 Simulating wildfire sensor data...");
// Initialize sensor states
initializeSensorStates();
wss.on("connection", (ws, req) => {
console.log(`📱 Client connected from ${req.socket.remoteAddress}`);
// Send initial batch
const initialBatch = generateBatch(8);
ws.send(JSON.stringify(initialBatch));
console.log(
`📦 Sent initial batch with ${initialBatch.points.length} sensors`
);
// Send periodic updates
const updateInterval = setInterval(() => {
if (ws.readyState === ws.OPEN) {
// 70% chance of delta, 30% chance of batch
const message = Math.random() < 0.7 ? generateDelta() : generateBatch(3);
if (message) {
ws.send(JSON.stringify(message));
if (message.type === "delta") {
console.log(
`📊 Sent delta: ${message.point.id} = ${message.point.pm25.toFixed(
1
)} μg/m³`
);
} else {
console.log(`📦 Sent batch with ${message.points.length} sensors`);
}
}
}
}, 5000); // Update every 5 seconds for better performance
// Simulate fire events occasionally
const fireInterval = setInterval(() => {
if (Math.random() < 0.1) {
// 10% chance every 30 seconds
simulateFireEvent();
}
}, 30000);
ws.on("close", () => {
console.log("📱 Client disconnected");
clearInterval(updateInterval);
clearInterval(fireInterval);
});
ws.on("error", (error) => {
console.error("❌ WebSocket error:", error);
clearInterval(updateInterval);
clearInterval(fireInterval);
});
});
wss.on("error", (error) => {
console.error("❌ Server error:", error);
});
// Graceful shutdown
process.on("SIGINT", () => {
console.log("\n🛑 Shutting down WebSocket server...");
wss.close(() => {
console.log("✅ Server closed");
process.exit(0);
});
});
// Add some helpful logs
setInterval(() => {
const avgPM25 =
Array.from(sensorStates.values()).reduce(
(sum, state) => sum + state.basePM25,
0
) / sensorStates.size;
console.log(
`📈 Average PM2.5: ${avgPM25.toFixed(1)} μg/m³ | Active connections: ${
wss.clients.size
}`
);
}, 10000); // Every 10 seconds