import os import subprocess from fastapi import FastAPI, HTTPException, Header, Depends from typing import Optional import psutil app = FastAPI() # Get auth token from env (or default if not set) AUTH_TOKEN = os.getenv("LUNA_API_TOKEN", "fallback-secret-luna") def verify_token(x_token: str = Header(...)): if x_token != AUTH_TOKEN: raise HTTPException(status_code=403, detail="Unauthorized access") return x_token @app.get("/status") def get_status(): net = psutil.net_io_counters() return { "cpu_usage": psutil.cpu_percent(interval=1), "memory": psutil.virtual_memory()._asdict(), "temperature": get_temp(), "load_avg": os.getloadavg(), "network": { "bytes_sent": net.bytes_sent, "bytes_recv": net.bytes_recv, "packets_sent": net.packets_sent, "packets_recv": net.packets_recv, "errin": net.errin, "errout": net.errout, "dropin": net.dropin, "dropout": net.dropout } } def get_temp(): try: with open("/sys/class/thermal/thermal_zone0/temp", "r") as f: return float(f.read()) / 1000.0 except: return None @app.post("/led/blink") def blink_led(token: str = Depends(verify_token)): try: # Run the flash_led.py script according to the established protocol subprocess.Popen(["python3", "/root/flash_led.py"]) return {"status": "LED blink triggered"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.get("/health") def health(): return {"status": "online"}