import json from datetime import datetime from fastapi import APIRouter, HTTPException from app.config import STATE_PATH router = APIRouter() @router.get("/status") async def get_status(): """Current monitor status: connected, CPS, last isotopes detected.""" if not STATE_PATH.exists(): raise HTTPException(status_code=503, detail="Monitor not started yet") try: with open(STATE_PATH) as f: state = json.load(f) except (json.JSONDecodeError, OSError): raise HTTPException(status_code=503, detail="Monitor state file corrupt") # Check staleness (> 5 minutes old) try: ts = datetime.fromisoformat(state["timestamp"]) age = (datetime.now() - ts).total_seconds() state["stale"] = age > 300 state["age_seconds"] = int(age) except (KeyError, ValueError): state["stale"] = True return { "connected": state.get("connected", False), "stale": state.get("stale", True), "age_seconds": state.get("age_seconds", 0), "timestamp": state.get("timestamp", ""), "cps": state.get("cps", 0), "cumulated_live_time_h": state.get("cumulated_live_time_h", 0), "total_counts": state.get("total_counts", 0), "background_subtracted": state.get("background_subtracted", False), "isotopes_detected": state.get("isotopes_detected", []), }