37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
import json
|
|
from typing import List, Dict, Any
|
|
from fastapi import WebSocket
|
|
|
|
class WebSocketManager:
|
|
"""Manages active WebSocket connections for live telemetry and dashboard updates."""
|
|
|
|
def __init__(self):
|
|
self.active_connections: List[WebSocket] = []
|
|
|
|
async def connect(self, websocket: WebSocket):
|
|
await websocket.accept()
|
|
self.active_connections.append(websocket)
|
|
|
|
def disconnect(self, websocket: WebSocket):
|
|
if websocket in self.active_connections:
|
|
self.active_connections.remove(websocket)
|
|
|
|
async def broadcast(self, message_type: str, data: Dict[str, Any]):
|
|
"""Broadcasts a structured JSON event to all connected dashboard clients."""
|
|
payload = {
|
|
"type": message_type,
|
|
"data": data
|
|
}
|
|
message_str = json.dumps(payload, default=str)
|
|
dead_connections = []
|
|
for connection in self.active_connections:
|
|
try:
|
|
await connection.send_text(message_str)
|
|
except Exception:
|
|
dead_connections.append(connection)
|
|
|
|
for dead in dead_connections:
|
|
self.disconnect(dead)
|
|
|
|
ws_manager = WebSocketManager()
|