60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
import asyncio
|
|
import json
|
|
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
|
from app.services.system import SystemService
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.websocket("/ws/system")
|
|
async def websocket_system_stats(websocket: WebSocket):
|
|
"""
|
|
WebSocket endpoint pour stream les stats système en temps réel
|
|
"""
|
|
await websocket.accept()
|
|
|
|
# Initialiser le cache psutil
|
|
import psutil
|
|
psutil.cpu_percent(interval=0.05, percpu=True)
|
|
|
|
try:
|
|
while True:
|
|
# Récupère les stats (très rapide avec cache)
|
|
stats = SystemService.get_system_stats()
|
|
|
|
# Envoie au client
|
|
await websocket.send_json({
|
|
"cpu": {
|
|
"percent": stats.cpu.percent,
|
|
"average": stats.cpu.average,
|
|
"cores": stats.cpu.cores,
|
|
"per_cpu": stats.cpu.per_cpu
|
|
},
|
|
"memory": {
|
|
"percent": stats.memory.percent,
|
|
"used": stats.memory.used,
|
|
"total": stats.memory.total,
|
|
"available": stats.memory.available
|
|
},
|
|
"processes": [
|
|
{
|
|
"pid": p.pid,
|
|
"name": p.name,
|
|
"status": p.status,
|
|
"cpu_percent": p.cpu_percent,
|
|
"memory_percent": p.memory_percent,
|
|
"username": p.username
|
|
}
|
|
for p in stats.processes
|
|
]
|
|
})
|
|
|
|
# Attendre 1 seconde avant le prochain envoi (1 fps, comme GNOME Monitor)
|
|
await asyncio.sleep(1)
|
|
|
|
except WebSocketDisconnect:
|
|
print(f"Client déconnecté")
|
|
except Exception as e:
|
|
print(f"Erreur WebSocket: {e}")
|
|
await websocket.close(code=1000)
|