Skip to content

Commit 87d495e

Browse files
authored
Merge pull request #20 from drizuid/fix-avgping
fix issues with avg ping check race condition
2 parents 7f0c0ea + 0e4c3ad commit 87d495e

1 file changed

Lines changed: 48 additions & 29 deletions

File tree

static/js/app.js

Lines changed: 48 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -326,42 +326,61 @@ const NetworkMonitor = () => {
326326

327327
const results = await Promise.all(
328328
currentDevices.map(async (device) => {
329-
const result = await fetch('/api/ping', {
329+
try {
330+
const response = await fetch('/api/ping', {
330331
method: 'POST',
331332
headers: { 'Content-Type': 'application/json' },
332333
body: JSON.stringify({ ip: device.ip })
333-
}).then(r => r.json()).catch(() => ({ success: false, responseTime: null }));
334-
335-
const status = result.success ? 'up' : 'down';
334+
});
335+
const result = await response.json();
336336

337-
if (result.success && result.responseTime) {
338-
setDeviceStats(prev => {
339-
const deviceData = prev[device.id] || { times: [], count: 0 };
340-
const newTimes = [...deviceData.times, result.responseTime].slice(-10); // Keep last 10
341-
const avg = Math.round(newTimes.reduce((a, b) => a + b, 0) / newTimes.length);
337+
return {
338+
device,
339+
status: result.success ? 'up' : 'down',
340+
responseTime: result.responseTime
341+
};
342+
} catch (error) {
343+
console.error('Ping failed:', error);
344+
return {
345+
device,
346+
status: 'down',
347+
responseTime: null
348+
};
349+
}
350+
})
351+
);
352+
const updatedDevices = results.map(r => ({
353+
...r.device,
354+
status: r.status
355+
}));
356+
setDevices(updatedDevices);
357+
358+
setDeviceStats(prevStats => {
359+
const newStats = { ...prevStats };
360+
361+
results.forEach(r => {
362+
if (r.status === 'up' && r.responseTime) {
363+
const deviceData = newStats[r.device.id] || { times: [], count: 0 };
364+
const newTimes = [...deviceData.times, r.responseTime].slice(-10); // 10 seems good enough, maybe 4 though?
365+
const avg = Math.round(newTimes.reduce((a, b) => a + b, 0) / newTimes.length);
342366

343-
return {
344-
...prev,
345-
[device.id]: {
346-
times: newTimes,
347-
count: deviceData.count + 1,
348-
avg: avg
349-
}
350-
};
351-
});
352-
}
367+
newStats[r.device.id] = {
368+
times: newTimes,
369+
count: deviceData.count + 1,
370+
avg: avg
371+
};
372+
}
373+
});
353374

354-
return { ...device, status };
355-
})
356-
);
357-
setDevices(results);
358-
};
375+
return newStats;
376+
});
377+
};
359378

360-
checkDevices();
361-
const interval = setInterval(checkDevices, 30000);
362-
return () => clearInterval(interval);
363-
}
364-
}, [isLoading]);
379+
checkDevices();
380+
const interval = setInterval(checkDevices, 30000);
381+
return () => clearInterval(interval);
382+
}
383+
}, [isLoading]);
365384

366385
const getDeviceIcon = (type) => {
367386
switch(type) {

0 commit comments

Comments
 (0)