wangrong
2026-08-24 beef6536e7c8dd3f5cbe8f73585611479910bea7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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