Skip to content

node — API Reference

app

node.app.create_app()

Source code in node/app.py
def create_app() -> FastAPI:
    app = FastAPI(
        title="Animontics Node",
        description="Sensor data streaming node for the Animontics distributed AI system.",
        version="0.1.0",
        lifespan=lifespan,
    )

    app.include_router(sensors_router)
    app.include_router(config_router)
    app.include_router(i2c_router)
    app.include_router(camera_router_module.router)
    app.include_router(ir_xcvr_router)
    app.include_router(devices_router)
    app.include_router(effectors_router)
    app.include_router(policies_router)
    app.include_router(vl53l1x_router)

    @app.get("/")
    async def node_info():
        cfg = app.state.config
        return JSONResponse({
            "node_id":   cfg.node_id,
            "node_type": cfg.node_type,
            "hostname":  cfg.hostname,
            "version":   "0.1.0",
            "sensors":   [
                {"id": s.id, "type": s.config.type, "healthy": s.is_healthy()}
                for s in app.state.sensors.values()
            ],
        })

    return app

routers.sensors

node.routers.sensors

get_sensor(sensor_id, request) async

Return the latest reading from a sensor, or null if not yet available.

Source code in node/routers/sensors.py
@router.get("/sensors/{sensor_id}")
async def get_sensor(sensor_id: str, request: Request):
    """Return the latest reading from a sensor, or null if not yet available."""
    sensor = request.app.state.sensors.get(sensor_id)
    if sensor is None:
        raise HTTPException(status_code=404, detail=f"Sensor '{sensor_id}' not found")
    reading = sensor.latest
    return reading.model_dump() if reading else None

list_sensors(request) async

List all configured sensors with their type and enabled status.

Source code in node/routers/sensors.py
@router.get("/sensors")
async def list_sensors(request: Request):
    """List all configured sensors with their type and enabled status."""
    sensors = request.app.state.sensors
    return [
        {
            "id":      sensor.id,
            "type":    sensor.config.type,
            "enabled": sensor.config.enabled,
        }
        for sensor in sensors.values()
    ]

sensor_frames(websocket, sensor_id) async

Binary frame stream for high-rate array/image sensors (thermal, pressure grids). Each message is one raw binary frame whose layout is sensor-defined (see the sensor's README / viewer). Use this instead of the JSON /ws lane when per-frame payloads are large and arrive tens of times per second — it avoids json.dumps on the server and a parse + GC of a big array on the client. Sensors without produces_frames are rejected with 4003.

Source code in node/routers/sensors.py
@router.websocket("/sensors/{sensor_id}/frames")
async def sensor_frames(websocket: WebSocket, sensor_id: str):
    """
    Binary frame stream for high-rate array/image sensors (thermal, pressure
    grids). Each message is one raw binary frame whose layout is sensor-defined
    (see the sensor's README / viewer). Use this instead of the JSON /ws lane
    when per-frame payloads are large and arrive tens of times per second — it
    avoids json.dumps on the server and a parse + GC of a big array on the
    client. Sensors without produces_frames are rejected with 4003.
    """
    sensor = websocket.app.state.sensors.get(sensor_id)
    if sensor is None:
        await websocket.close(code=4004, reason=f"Sensor '{sensor_id}' not found")
        return
    if not getattr(sensor, "produces_frames", False):
        await websocket.close(code=4003, reason=f"Sensor '{sensor_id}' has no frame stream")
        return

    await websocket.accept()
    q = sensor.subscribe_frames()
    try:
        while True:
            frame = await _q_get(q)
            if frame is None:
                await websocket.send_bytes(b"")   # keepalive ping (zero-length)
                continue
            await websocket.send_bytes(frame)
    except WebSocketDisconnect:
        pass
    finally:
        sensor.unsubscribe_frames(q)

sensor_stream(sensor_id, request) async

Server-sent events stream for a sensor. Each event is a JSON-encoded SensorReading. A keepalive comment is sent every 25 s when no reading is available.

Source code in node/routers/sensors.py
@router.get("/sensors/{sensor_id}/stream")
async def sensor_stream(sensor_id: str, request: Request):
    """
    Server-sent events stream for a sensor.
    Each event is a JSON-encoded SensorReading.
    A keepalive comment is sent every 25 s when no reading is available.
    """
    sensor = request.app.state.sensors.get(sensor_id)
    if sensor is None:
        raise HTTPException(status_code=404, detail=f"Sensor '{sensor_id}' not found")

    async def generate():
        q = sensor.subscribe()
        try:
            # Send latest reading immediately if available
            latest = sensor.latest
            if latest:
                yield latest.to_sse()

            while True:
                payload = await _q_get(q)
                yield payload if payload is not None else ": keepalive\n\n"
        finally:
            sensor.unsubscribe(q)

    return StreamingResponse(
        generate(),
        media_type="text/event-stream",
        headers={
            "Cache-Control":    "no-cache",
            "X-Accel-Buffering": "no",
            "Access-Control-Allow-Origin": "*",
        },
    )

sensor_ws(websocket, sensor_id) async

WebSocket stream — sends the same JSON payload as the SSE stream.

Source code in node/routers/sensors.py
@router.websocket("/sensors/{sensor_id}/ws")
async def sensor_ws(websocket: WebSocket, sensor_id: str):
    """WebSocket stream — sends the same JSON payload as the SSE stream."""
    sensor = websocket.app.state.sensors.get(sensor_id)
    if sensor is None:
        await websocket.close(code=4004, reason=f"Sensor '{sensor_id}' not found")
        return

    await websocket.accept()
    q = sensor.subscribe()
    try:
        latest = sensor.latest
        if latest:
            await websocket.send_text(latest.model_dump_json())

        while True:
            payload = await _q_get(q)
            if payload is None:
                await websocket.send_text('{"keepalive":true}')
                continue
            # Strip the SSE framing ("data: ...\n\n") — send raw JSON
            json_str = payload.removeprefix("data: ").rstrip("\n")
            await websocket.send_text(json_str)
    except WebSocketDisconnect:
        pass
    finally:
        sensor.unsubscribe(q)

routers.devices

node.routers.devices

Device tier introspection — health with gating awareness.

A device behind a switched-off power rail is gated, not failed: the cut is a deliberate body state commanded through a power_rail effector that lists the device in its members. This router is the surface that tells the two apart, so fleet tooling and dashboards never report an intentional power-down as a fault. Reads request.app.state (never module-level registries).

list_devices(request) async

All devices with health + gating: healthy | gated | down.

Source code in node/routers/devices.py
@router.get("/devices")
async def list_devices(request: Request):
    """All devices with health + gating: healthy | gated | down."""
    devices = request.app.state.devices
    gated = _gated_ids(request.app.state.effectors)
    out = []
    for dev in devices.values():
        healthy = bool(dev.is_healthy())
        is_gated = dev.id in gated
        out.append({
            "id": dev.id,
            "kind": dev.config.kind,
            "healthy": healthy,
            "gated": is_gated,
            "status": "healthy" if healthy else ("gated" if is_gated else "down"),
        })
    return out

routers.effectors

node.routers.effectors

Effector control routes — the efferent dual of the sensor routes.

Two lanes, chosen by the effector type (not a universal verb): • request — POST /effectors/{id} with a type-defined body (e.g. pwm levels). • stream — WS /effectors/{id}/stream, binary frames fed continuously. Node-implicit and logical; the backing device is metadata, never a path segment.

drive_effector(effector_id, request, payload=Body(...)) async

Request-lane drive. Body schema is defined by the effector's type.

Source code in node/routers/effectors.py
@router.post("/effectors/{effector_id}")
async def drive_effector(effector_id: str, request: Request, payload: dict = Body(...)):
    """Request-lane drive. Body schema is defined by the effector's type."""
    e = _get(request, effector_id)
    if "request" not in e.lanes:
        raise HTTPException(status_code=400, detail=f"'{e.id}' has no request lane")
    try:
        return e.handle_request(payload)
    except NotImplementedError as exc:
        raise HTTPException(status_code=400, detail=str(exc))

stream_effector(websocket, effector_id) async

Stream-lane drive: binary frames fed to the effector (audio, LED animation).

Source code in node/routers/effectors.py
@router.websocket("/effectors/{effector_id}/stream")
async def stream_effector(websocket: WebSocket, effector_id: str):
    """Stream-lane drive: binary frames fed to the effector (audio, LED animation)."""
    effector = getattr(websocket.app.state, "effectors", {}).get(effector_id)
    if effector is None:
        await websocket.close(code=4004, reason=f"Effector '{effector_id}' not found")
        return
    if "stream" not in effector.lanes:
        await websocket.close(code=4003, reason=f"'{effector_id}' has no stream lane")
        return
    await websocket.accept()
    try:
        while True:
            chunk = await websocket.receive_bytes()
            effector.feed(chunk)
    except Exception:
        return  # client disconnected / stream ended

routers.policies

node.routers.policies

Policy routes — inspect and toggle the node's control loops.

A policy maps observations (relay signals) to actions (effector channels). These routes expose its wiring and current obs/action, and let an operator (or an upstream cortex) enable/disable it. Hot-swapping a policy's behavior is a later addition; the interface is the seam.

routers.camera

node.routers.camera.CameraThread(config)

Reads raw MJPEG bytes from V4L2 without decode/re-encode. CAP_PROP_CONVERT_RGB=0 tells OpenCV to return the compressed frame the camera already produced in hardware.

Source code in node/routers/camera.py
def __init__(self, config: CameraConfig) -> None:
    self._config = config
    self._jpeg: Optional[bytes] = None
    self._seq   = 0
    self._lock  = threading.Lock()
    self._stop  = threading.Event()

node.routers.camera.start_camera(config)

Source code in node/routers/camera.py
def start_camera(config: CameraConfig) -> CameraThread:
    global _camera
    if cv2 is None:
        raise RuntimeError(
            "camera is enabled in this board's config but opencv is not "
            "installed — pip install opencv-python-headless"
        )
    _camera = CameraThread(config)
    _camera.start()
    return _camera

node.routers.camera.stop_camera()

Source code in node/routers/camera.py
def stop_camera() -> None:
    if _camera:
        _camera.stop()

routers.i2c

node.routers.i2c

scan_i2c_buses()

Run i2cdetect on every /dev/i2c-* bus. Returns {bus_num: [addrs] | {"error": str}}.

Source code in node/routers/i2c.py
def scan_i2c_buses() -> dict:
    """Run i2cdetect on every /dev/i2c-* bus. Returns {bus_num: [addrs] | {"error": str}}."""
    result = {}
    for path in sorted(glob.glob("/dev/i2c-*")):
        try:
            bus_num = int(path.rsplit("-", 1)[-1])
        except ValueError:
            continue
        try:
            proc = subprocess.run(
                ["i2cdetect", "-y", "-r", str(bus_num)],
                capture_output=True, text=True, timeout=5,
            )
            result[bus_num] = _parse_i2cdetect(proc.stdout)
        except FileNotFoundError:
            result[bus_num] = {"error": "i2cdetect not found — run: sudo apt install i2c-tools"}
        except subprocess.TimeoutExpired:
            result[bus_num] = {"error": "timeout"}
        except Exception as exc:
            result[bus_num] = {"error": str(exc)}
    return result