Fix inventory disappearing: add WS keep-alive pings + HTTP API fallback

- Server pings web clients every 25s to keep connections alive through reverse proxies
- Client fetches /api/inventory on page load (doesn't depend solely on WebSocket)
- Prevent duplicate WebSocket connections on reconnect
- Deduplicate initial_state/state_update handlers
This commit is contained in:
MayaTheShy
2026-03-21 18:35:17 -04:00
parent 4af91235e1
commit c25ef9f2cc
2 changed files with 65 additions and 22 deletions

View File

@@ -469,6 +469,7 @@ wss.on('connection', (ws, req) => {
// ---- Web client WebSocket connection ----
console.log('🌐 New web client connected');
webClients.add(ws);
ws.isAlive = true;
// Send current state to new client
ws.send(JSON.stringify({
@@ -484,10 +485,11 @@ wss.on('connection', (ws, req) => {
lastUpdate,
}));
ws.on('pong', () => { ws.isAlive = true; });
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
console.log('📨 Received from web client:', data);
if (data.type === 'command') {
// Forward command to bridge
@@ -508,6 +510,23 @@ wss.on('connection', (ws, req) => {
});
});
// ========== WebSocket Keep-Alive ==========
// Ping all web clients every 25s to keep connections alive through reverse proxies
const WS_PING_INTERVAL = setInterval(() => {
webClients.forEach((ws) => {
if (!ws.isAlive) {
webClients.delete(ws);
return ws.terminate();
}
ws.isAlive = false;
ws.ping();
});
}, 25000);
wss.on('close', () => {
clearInterval(WS_PING_INTERVAL);
});
// ========== Start Server ==========
server.listen(PORT, HOST, () => {