64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
|
|
import json
|
||
|
|
from datetime import datetime
|
||
|
|
from typing import Set
|
||
|
|
from fastapi import WebSocket
|
||
|
|
|
||
|
|
from app.models import Position, Event
|
||
|
|
|
||
|
|
|
||
|
|
class ConnectionManager:
|
||
|
|
def __init__(self):
|
||
|
|
self.active_connections: Set[WebSocket] = set()
|
||
|
|
|
||
|
|
async def connect(self, websocket: WebSocket):
|
||
|
|
await websocket.accept()
|
||
|
|
self.active_connections.add(websocket)
|
||
|
|
|
||
|
|
def disconnect(self, websocket: WebSocket):
|
||
|
|
self.active_connections.discard(websocket)
|
||
|
|
|
||
|
|
async def broadcast(self, message: dict):
|
||
|
|
"""Отправить сообщение всем подключенным клиентам"""
|
||
|
|
disconnected = set()
|
||
|
|
for connection in self.active_connections:
|
||
|
|
try:
|
||
|
|
await connection.send_json(message)
|
||
|
|
except Exception:
|
||
|
|
disconnected.add(connection)
|
||
|
|
|
||
|
|
# Remove disconnected clients
|
||
|
|
self.active_connections -= disconnected
|
||
|
|
|
||
|
|
async def broadcast_position(self, position: Position):
|
||
|
|
"""Отправить обновление позиции"""
|
||
|
|
message = {
|
||
|
|
"type": "position_update",
|
||
|
|
"data": {
|
||
|
|
"vehicle_id": position.vehicle_id,
|
||
|
|
"lat": position.lat,
|
||
|
|
"lon": position.lon,
|
||
|
|
"speed": position.speed,
|
||
|
|
"heading": position.heading,
|
||
|
|
"timestamp": position.timestamp.isoformat()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
await self.broadcast(message)
|
||
|
|
|
||
|
|
async def broadcast_event(self, event: Event):
|
||
|
|
"""Отправить событие"""
|
||
|
|
message = {
|
||
|
|
"type": "event",
|
||
|
|
"data": {
|
||
|
|
"id": event.id,
|
||
|
|
"vehicle_id": event.vehicle_id,
|
||
|
|
"type": event.type,
|
||
|
|
"payload": event.payload,
|
||
|
|
"timestamp": event.timestamp.isoformat()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
await self.broadcast(message)
|
||
|
|
|
||
|
|
|
||
|
|
# Global instance
|
||
|
|
manager = ConnectionManager()
|