refactor: implement packet parsing heuristics and introduce device-level state caching to throttle database writes and vitals updates
This commit is contained in:
@@ -3,8 +3,9 @@ import json
|
||||
import logging
|
||||
import socket
|
||||
from typing import List
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect
|
||||
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
@@ -69,27 +70,50 @@ def health_check():
|
||||
return {"status": "ok", "service": "Patient Monitor Vital Signs Forwarder"}
|
||||
|
||||
@router.get("/status")
|
||||
def get_system_status(db: Session = Depends(get_db)):
|
||||
def get_system_status(request: Request, db: Session = Depends(get_db)):
|
||||
total_devices = db.query(Device).count()
|
||||
active_devices = db.query(Device).filter(Device.status == "active").count()
|
||||
total_readings = db.query(VitalReading).count()
|
||||
pending_transmissions = db.query(VitalReading).filter(VitalReading.transmitted == False).count()
|
||||
active_ports = getattr(request.app.state, "active_ports", [])
|
||||
|
||||
return {
|
||||
"total_devices": total_devices,
|
||||
"active_devices": active_devices,
|
||||
"total_readings_stored": total_readings,
|
||||
"pending_transmissions": pending_transmissions
|
||||
"pending_transmissions": pending_transmissions,
|
||||
"active_ports": active_ports
|
||||
}
|
||||
|
||||
@router.get("/devices")
|
||||
def list_devices(db: Session = Depends(get_db)):
|
||||
devices = db.query(Device).all()
|
||||
now = datetime.now(timezone.utc)
|
||||
updated = False
|
||||
for device in devices:
|
||||
last_seen = device.last_seen
|
||||
if last_seen.tzinfo is None:
|
||||
last_seen = last_seen.replace(tzinfo=timezone.utc)
|
||||
|
||||
# If not seen for more than 15 seconds, mark offline
|
||||
if (now - last_seen).total_seconds() > 15.0:
|
||||
if device.status != "offline":
|
||||
device.status = "offline"
|
||||
updated = True
|
||||
else:
|
||||
if device.status != "active":
|
||||
device.status = "active"
|
||||
updated = True
|
||||
if updated:
|
||||
db.commit()
|
||||
return devices
|
||||
|
||||
@router.get("/latest-readings")
|
||||
def get_latest_readings(limit: int = 10, db: Session = Depends(get_db)):
|
||||
readings = db.query(VitalReading).order_by(VitalReading.timestamp.desc()).limit(limit).all()
|
||||
def get_latest_readings(device_id: str = None, limit: int = 10, db: Session = Depends(get_db)):
|
||||
query = db.query(VitalReading)
|
||||
if device_id:
|
||||
query = query.filter(VitalReading.device_id == device_id)
|
||||
readings = query.order_by(VitalReading.timestamp.desc()).limit(limit).all()
|
||||
return readings
|
||||
|
||||
@router.get("/readings")
|
||||
|
||||
Reference in New Issue
Block a user