Add POST /heartbeat and POST /status, and the shared envelope (Phase 2)
One body, two endpoints. The firmware builds the conditions payload once, in
buildConditions, and posts it to both; they differ only in the response.
/heartbeat -> 200 and the envelope: commands, config version, firmware
/status -> 204 and nothing
The split is not cosmetic and is now pinned by a test. The device posts
status immediately before deep sleep, so delivering commands there would mark
them delivered to a device about to be unable to run them.
api/envelope.py holds the shared builder, because /ingest returns the same
shape and parseEnvelope handles both with one function - they must not drift.
- Commands are marked delivered when handed over, not on ack: the ack may
never come, since the device runs reboot and sleep_now and is gone.
acked_at stays the separate, later signal that it actually ran.
- Expired commands are skipped but left in place, so the admin UI can show
that a command timed out rather than silently losing it. The worker's
prune job is what removes them.
- The firmware URL is deliberately relative. ota_mgr.cpp:86 appends any
non-http url to the API base, which already ends in /api/v1, so
/firmware/0.2.0.bin resolves to /api/v1/firmware/0.2.0.bin.
- Being on target means the firmware key is absent, not null: naming a
different version is itself the instruction to flash (main.cpp:104).
Recording conditions appends a device_status row and refreshes the
denormalised columns on devices. Three details worth stating:
- A field the device omits does not erase the last good value. None means
not sent, not zero.
- battery.valid false means NOT MEASURED and is stored as false, so the UI
renders an em dash instead of inventing a low-battery alarm.
- The device's reported config_version never overwrites the server's. The
difference between them is exactly what tells the device to GET /config.
Tests: 77 -> 99. Verified by making /status build the envelope: the contract
test fails, as intended.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
bde67e9a41
commit
5fd3c094a4
4 files changed
+600
-3
No files matched your search
@@ -0,0 +1,108 @@
|
||||
"""The response envelope shared by /ingest and /heartbeat.
|
||||
|
||||
SPEC 4.1 and firmware/API.md: both endpoints return the *same* shape, so a
|
||||
capture that was going to happen anyway also delivers the command queue at no
|
||||
extra cost. ``parseEnvelope`` in firmware/src/api_client.cpp handles both with
|
||||
one function, which is why they must not drift.
|
||||
|
||||
``/status`` deliberately does not use this. The device posts status
|
||||
immediately before deep sleep, and handing it commands there would mark them
|
||||
delivered to a device that is about to be unable to run them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models.devices import Device, DeviceCommand, Firmware
|
||||
from .deps import server_time_ms
|
||||
from .schemas import Command, Envelope, FirmwareTarget
|
||||
|
||||
|
||||
def _epoch_ms(value: datetime | None) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=UTC)
|
||||
return int(value.timestamp() * 1000)
|
||||
|
||||
|
||||
def take_pending_commands(db: Session, device: Device) -> list[Command]:
|
||||
"""Claim this device's queued commands and mark them delivered.
|
||||
|
||||
Delivery is recorded here rather than on ack, because the ack may never
|
||||
come: the device runs ``reboot`` and ``sleep_now`` and is gone. ``acked_at``
|
||||
is the separate, later signal that it actually ran.
|
||||
|
||||
Expired commands are skipped but left in place; the worker's
|
||||
``prune_expired_commands`` job is what removes them, so the admin UI can
|
||||
still show that a command timed out rather than silently losing it.
|
||||
"""
|
||||
now = datetime.now(UTC)
|
||||
|
||||
rows = list(
|
||||
db.scalars(
|
||||
select(DeviceCommand)
|
||||
.where(
|
||||
DeviceCommand.device_id == device.id,
|
||||
DeviceCommand.delivered_at.is_(None),
|
||||
or_(DeviceCommand.expires_at.is_(None), DeviceCommand.expires_at > now),
|
||||
)
|
||||
.order_by(DeviceCommand.created_at)
|
||||
)
|
||||
)
|
||||
|
||||
for row in rows:
|
||||
row.delivered_at = now
|
||||
|
||||
return [
|
||||
Command(
|
||||
id=row.id,
|
||||
type=row.type,
|
||||
payload=row.payload,
|
||||
expires_at=_epoch_ms(row.expires_at),
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def firmware_target(db: Session, device: Device) -> FirmwareTarget | None:
|
||||
"""The image this device should be running, or None when it is on target.
|
||||
|
||||
Naming a different version is itself the instruction to flash
|
||||
(main.cpp:104); an explicit ``ota_update`` command is only for staged
|
||||
rollouts. So "on target" must mean the key is absent, not null.
|
||||
|
||||
The URL is relative on purpose. ota_mgr.cpp:86 appends anything that does
|
||||
not start with "http" to the API base, which already ends in /api/v1, so
|
||||
"/firmware/0.2.0.bin" resolves to /api/v1/firmware/0.2.0.bin -- the
|
||||
endpoint API.md documents.
|
||||
"""
|
||||
target = db.scalar(select(Firmware).where(Firmware.is_target.is_(True)))
|
||||
if target is None or target.version == device.fw_version:
|
||||
return None
|
||||
|
||||
return FirmwareTarget(
|
||||
version=target.version,
|
||||
url=f"/firmware/{target.version}.bin",
|
||||
sha256=target.sha256,
|
||||
size=target.size_bytes,
|
||||
)
|
||||
|
||||
|
||||
def build_envelope(db: Session, device: Device, capture_id: str | None = None) -> Envelope:
|
||||
"""Assemble the envelope, claiming any pending commands as a side effect.
|
||||
|
||||
The caller commits. Nothing here flushes, so a handler that fails after
|
||||
this point does not leave commands marked delivered that never went out.
|
||||
"""
|
||||
return Envelope(
|
||||
capture_id=capture_id,
|
||||
server_time=server_time_ms(),
|
||||
config_version=device.config_version,
|
||||
firmware=firmware_target(db, device),
|
||||
commands=take_pending_commands(db, device),
|
||||
)
|
||||
Reference in new issue
Block a user