Capability report: PUT /devices/{id}/report, a Capabilities section, offline devices degraded
A device reports its board, screen, camera and ports from its own credential (16 KB, schema 1, replacing the last report), and the flows are validated against it again. The node panel turns a reported port's config schema into a form, a reported screen is a canvas preset and a touch screen's first report turns Touch friendly on. An offline device node is degraded: amber on the canvas, a warning on Home, never a fault. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0138N7k5PT4dcR1iEqXaaQ9k
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a9d453c9d9
commit
ad76200d3d
@@ -189,10 +189,10 @@ def _device_may(payload: dict[str, Any], request: Request) -> None:
|
||||
A panel credential names the account that approved the pairing, so without
|
||||
this it would be that person's session hanging on a wall. What a panel
|
||||
genuinely needs is small and worth writing out: the dashboards it was
|
||||
assigned, its own definition, the messages its own widgets and ports bind
|
||||
to, and the bytes those messages currently point at, for a tile drawing a
|
||||
camera frame — plus an upload named after one of its ``in`` ports, for a
|
||||
microphone whose recording is the value it publishes.
|
||||
assigned, its own definition and report, the messages its own widgets and
|
||||
ports bind to, and the bytes those messages currently point at, for a tile
|
||||
drawing a camera frame — plus an upload named after one of its ``in``
|
||||
ports, for a microphone whose recording is the value it publishes.
|
||||
|
||||
Publishing is in the list because a panel cannot be strictly read-only — a
|
||||
control on a panel is the point of putting one there, and a querying chart
|
||||
@@ -239,6 +239,9 @@ def _device_may(payload: dict[str, Any], request: Request) -> None:
|
||||
f"{api}/panels/{device.id}",
|
||||
):
|
||||
allowed = True
|
||||
elif method == "PUT" and path == f"{api}/devices/{device.id}/report":
|
||||
# What it has, said about itself and nobody else.
|
||||
allowed = True
|
||||
elif method == "POST" and path == f"{api}/flows/ws-ticket":
|
||||
# How its live socket opens; the socket applies the panel's own scope.
|
||||
allowed = True
|
||||
|
||||
@@ -18,8 +18,13 @@ device nodes in published flows wire its own ports to, and nothing else.
|
||||
Deleting the device revokes it, and so does unpairing, which bumps the
|
||||
device's nonce and leaves what it shows as it was.
|
||||
|
||||
``/panels/pair``, ``/panels/pair/{code}`` and ``GET /panels/{id}`` are what the
|
||||
openpanel firmware calls, and stay as aliases until every device has updated.
|
||||
Once paired, a device says what it has with ``PUT /devices/{id}/report``: its
|
||||
board, its screen and the ports it serves, which the device node's ports are
|
||||
checked against.
|
||||
|
||||
``/panels/pair``, ``/panels/pair/{code}`` and ``GET /panels/{id}`` are what
|
||||
openpanel firmware from before devices calls, and stay as aliases until every
|
||||
device has updated.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,7 +39,7 @@ import httpx
|
||||
import redis
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, Field, ValidationError, field_validator
|
||||
|
||||
from fluksio.api.deps import (
|
||||
CurrentUser,
|
||||
@@ -52,6 +57,7 @@ from fluksio.flow.devices import (
|
||||
DeviceExists,
|
||||
DeviceIo,
|
||||
DeviceNotFound,
|
||||
DeviceReport,
|
||||
DeviceStore,
|
||||
is_lan,
|
||||
presence,
|
||||
@@ -88,6 +94,10 @@ RESERVED = {"pair", "pending"}
|
||||
#: How much of what a device says about itself is kept.
|
||||
HELLO_LENGTH = 64
|
||||
|
||||
#: The most a capability report may weigh. A panel with every header pin
|
||||
#: reported is a few kB.
|
||||
REPORT_MAX = 16 * 1024
|
||||
|
||||
|
||||
class _Pending(BaseModel):
|
||||
"""A device waiting to be told what it is."""
|
||||
@@ -314,6 +324,7 @@ class DevicePublic(DeviceDocument):
|
||||
last_seen: datetime | None = None
|
||||
#: What the device says it has, as it last said so. None until it reports.
|
||||
report: dict[str, Any] | None = None
|
||||
reported_at: datetime | None = None
|
||||
|
||||
|
||||
class DevicesPublic(BaseModel):
|
||||
@@ -499,15 +510,19 @@ async def read_devices(store: DeviceStoreDep) -> Any:
|
||||
"""Every device, what each one shows, and whether it is connected."""
|
||||
|
||||
def gather() -> list[DevicePublic]:
|
||||
return [
|
||||
DevicePublic(
|
||||
**_document(device, store).model_dump(),
|
||||
online=presence.online(device.id),
|
||||
last_seen=presence.last_seen(device.id),
|
||||
report=store.state(device.id).report,
|
||||
found = []
|
||||
for device in store.list():
|
||||
state = store.state(device.id)
|
||||
found.append(
|
||||
DevicePublic(
|
||||
**_document(device, store).model_dump(),
|
||||
online=presence.online(device.id),
|
||||
last_seen=presence.last_seen(device.id),
|
||||
report=state.report,
|
||||
reported_at=state.reported_at,
|
||||
)
|
||||
)
|
||||
for device in store.list()
|
||||
]
|
||||
return found
|
||||
|
||||
data = await run_in_threadpool(gather)
|
||||
return DevicesPublic(
|
||||
@@ -596,6 +611,57 @@ panels_router.add_api_route(
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{device_id}/report",
|
||||
response_model=Message,
|
||||
dependencies=[Depends(get_current_user)],
|
||||
)
|
||||
async def put_report(device_id: str, request: Request, store: DeviceStoreDep) -> Any:
|
||||
"""A device says what it has: its board, its screen, its ports.
|
||||
|
||||
Only the device itself, through its own credential, which ``_device_may``
|
||||
holds to its own id. The report replaces the one before it, and the flows
|
||||
are validated again, since a device node's ports are checked against it.
|
||||
|
||||
The first report of a touch screen makes the device touch friendly, as
|
||||
the switch would have been set by hand. Later ones leave the setting to
|
||||
whoever changed it since.
|
||||
"""
|
||||
device: DeviceDef | None = getattr(request.state, "device", None)
|
||||
if device is None or device.id != device_id:
|
||||
raise HTTPException(
|
||||
status_code=403, detail="Only the device itself reports what it has"
|
||||
)
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw += chunk
|
||||
if len(raw) > REPORT_MAX:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"A report is at most {REPORT_MAX // 1024} KB",
|
||||
)
|
||||
try:
|
||||
report = DeviceReport.model_validate_json(bytes(raw))
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(
|
||||
status_code=422,
|
||||
detail=exc.errors(
|
||||
include_url=False, include_input=False, include_context=False
|
||||
),
|
||||
)
|
||||
first = await run_in_threadpool(store.report, device_id, report)
|
||||
if first and report.display and report.display.touch and not device.touch:
|
||||
with suppress(StaleVersion, DeviceNotFound):
|
||||
await run_in_threadpool(
|
||||
store.write,
|
||||
device.model_copy(update={"touch": True}),
|
||||
device.version,
|
||||
)
|
||||
_changed()
|
||||
await _recheck(request)
|
||||
return Message(message=f"{len(report.ports)} ports reported")
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{device_id}",
|
||||
response_model=DeviceDef,
|
||||
|
||||
@@ -53,6 +53,8 @@ def _epoch(column: Any) -> ColumnElement[int]:
|
||||
class HealthSummary(BaseModel):
|
||||
status: str
|
||||
problems: list[str]
|
||||
#: Worth a look, but not faults: they leave ``status`` as it is.
|
||||
warnings: list[str] = []
|
||||
flows: dict[str, int]
|
||||
nodes: dict[str, int]
|
||||
queue: dict[str, Any]
|
||||
@@ -241,9 +243,24 @@ async def read_summary(request: Request, controller: FlowControllerDep) -> Any:
|
||||
if invalid:
|
||||
problems.append(f"{len(invalid)} flow(s) cannot run: {', '.join(invalid)}")
|
||||
|
||||
# Working, if not as well as they should: a device switched off, a send
|
||||
# queue full. A warning, held back by the same floor as `unhealthy`.
|
||||
degraded = controller.unhealthy_nodes(health="degraded")
|
||||
warnings = (
|
||||
[
|
||||
f"{len(degraded)} node(s) degraded: "
|
||||
+ ", ".join(
|
||||
sorted(f"{e.id} ({e.health_detail or 'no detail'})" for e in degraded)
|
||||
)
|
||||
]
|
||||
if degraded
|
||||
else []
|
||||
)
|
||||
|
||||
return HealthSummary(
|
||||
status="degraded" if problems else "ok",
|
||||
problems=problems,
|
||||
warnings=warnings,
|
||||
flows={
|
||||
"total": len(names),
|
||||
# What the engine will actually act on. Enabled is not enough:
|
||||
@@ -267,6 +284,7 @@ async def read_summary(request: Request, controller: FlowControllerDep) -> Any:
|
||||
"total": len(entries),
|
||||
"error": len(errored),
|
||||
"unhealthy": len(unhealthy),
|
||||
"degraded": len(degraded),
|
||||
"failing": len(failing),
|
||||
},
|
||||
queue=queue,
|
||||
|
||||
Reference in New Issue
Block a user