from fastapi import APIRouter, HTTPException, Request from app.models.schemas import MqttCommand router = APIRouter(prefix="/api/v1/devices", tags=["devices"]) def _get_mqtt(request: Request): return request.app.state.mqtt @router.get("/initialized") async def list_initialized_devices(request: Request): registry = request.app.state.init_registry return {"devices": registry.list_initialized()} @router.delete("/initialized/{device_id}") async def reset_initialized_device(request: Request, device_id: str): registry = request.app.state.init_registry if not registry.remove(device_id): raise HTTPException(status_code=404, detail="Device not in initialized registry") return {"device_id": device_id, "status": "removed"} @router.get("/{device_id}/init-status") async def get_device_init_status(request: Request, device_id: str): registry = request.app.state.init_registry record = registry.get_record(device_id) return { "device_id": device_id, "initialized": record is not None, "record": record, } @router.get("") async def list_devices(request: Request): store = request.app.state.device_store return {"devices": [d.model_dump() for d in store.list_devices()]} @router.get("/{device_id}") async def get_device(request: Request, device_id: str): store = request.app.state.device_store device = store.get_device(device_id) if not device: raise HTTPException(status_code=404, detail="Device not found") return device @router.get("/{device_id}/acks") async def get_device_acks(request: Request, device_id: str): store = request.app.state.device_store return {"device_id": device_id, "acks": store.get_acks(device_id)} @router.get("/{device_id}/events") async def get_device_events(request: Request, device_id: str): store = request.app.state.device_store return {"device_id": device_id, "events": store.get_events(device_id)} @router.post("/{device_id}/cmd") async def send_command(request: Request, device_id: str, command: MqttCommand): mqtt = _get_mqtt(request) result = mqtt.publish_ctl(device_id, command.action, command.payload, command.header.ttl or 60) return result @router.post("/{device_id}/task") async def send_task(request: Request, device_id: str, command: MqttCommand): mqtt = _get_mqtt(request) result = mqtt.publish_task(device_id, command.action, command.payload, command.header.ttl or 3600) return result