Files
Hello/server/src/poorbird/api/routes/conditions.py
T
Thomas KarnerandClaude Opus 5 5fd3c094a4 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>
2026-09-21 12:46:59 +02:00

139 lines
5.2 KiB
Python

"""POST /api/v1/heartbeat and POST /api/v1/status -- one body, two endpoints.
Both take the identical conditions payload (firmware/src/api_client.cpp builds
it once, in ``buildConditions``). They differ only in the response:
* ``/heartbeat`` -> 200 and the envelope: commands, config version, firmware
target.
* ``/status`` -> 204 and nothing.
The split is not cosmetic. The device posts status immediately before deep
sleep, and pulling down a command queue at that moment would mark commands
delivered that the device is about to become unable to execute. So /status
deliberately returns nothing actionable (API.md).
A heartbeat the endpoint *accepts* is also what confirms an OTA trial boot:
the device calls esp_ota_mark_app_valid only after one succeeds. Returning 5xx
to a device on a trial image will roll it back -- correct behaviour, but worth
knowing before restarting the server mid-rollout.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from fastapi import APIRouter, Response, status
from ...models.devices import DeviceStatus
from ..deps import DbDep, DeviceDep
from ..envelope import build_envelope
from ..schemas import DeviceConditions, Envelope
log = logging.getLogger(__name__)
router = APIRouter()
# Reasons that mean "this is the last thing I will say for a while".
_GOING_QUIET = {"before_sleep", "before_night_sleep"}
def _record(db: DbDep, device, body: DeviceConditions) -> None:
"""Append a telemetry row and refresh the device's last-known conditions.
The row is the time series; the columns on ``devices`` are a denormalised
copy so the device list does not need a correlated subquery per row.
"""
raw = body.model_dump(mode="json")
db.add(
DeviceStatus(
device_id=device.id,
reason=body.reason,
battery_mv=body.battery.mv,
battery_pct=body.battery.pct,
battery_valid=body.battery.valid,
awake_ms=body.power.awake_ms,
boot_count=body.power.boot_count,
wake_cause=body.power.wake_cause,
last_sleep_s=body.power.last_sleep_s,
total_sleep_s=body.power.total_sleep_s,
captured_today=body.counters.captured_today,
delivered_today=body.counters.delivered_today,
failed_today=body.counters.failed_today,
events_today=body.counters.events_today,
day_index=body.counters.day_index,
is_night=body.night.is_night,
nightlight_on=body.night.nightlight_on,
cam_profile=body.camera.profile,
radar_baud=body.radar.baud,
radar_uart_ok=body.radar.uart_ok,
stream_active=body.stream.active,
rssi=body.system.rssi,
ip=body.system.ip,
free_heap=body.system.free_heap,
free_psram=body.system.free_psram,
ring_depth=body.system.ring_depth,
time_synced=body.time_synced,
device_time=body.device_time,
fw_version=body.fw_version,
config_version=body.config_version,
# Everything as posted, including keys this server does not know
# about yet. The flat columns above are what is worth charting.
raw=raw,
)
)
device.last_seen_at = datetime.now(UTC)
# Only overwrite a denormalised value when the device actually reported
# one. None means "not sent", which must not erase a good earlier reading.
if body.battery.mv is not None:
device.battery_mv = body.battery.mv
if body.battery.pct is not None:
device.battery_pct = body.battery.pct
if body.battery.valid is not None:
# false means NOT MEASURED, not empty. Stored as reported so the UI can
# render an em dash instead of inventing a low-battery alarm.
device.battery_valid = body.battery.valid
if body.system.rssi is not None:
device.rssi = body.system.rssi
if body.fw_version is not None:
device.fw_version = body.fw_version
# A device that has just announced it is going to sleep will not answer
# commands, and the UI should say so rather than show it as reachable.
device.awake = body.reason not in _GOING_QUIET
# device.config_version is the server's intent and is NOT touched here.
# body.config_version is what the device currently runs; the difference is
# exactly what tells it to GET /config.
@router.post(
"/heartbeat",
response_model=Envelope,
response_model_exclude_none=True,
summary="Device conditions; returns the command envelope",
tags=["devices"],
)
def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope:
_record(db, device, body)
envelope = build_envelope(db, device)
db.commit()
return envelope
@router.post(
"/status",
status_code=status.HTTP_204_NO_CONTENT,
response_class=Response,
summary="Device conditions; returns nothing actionable",
tags=["devices"],
)
def device_status(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Response:
_record(db, device, body)
db.commit()
# Deliberately no envelope: see the module docstring.
return Response(status_code=status.HTTP_204_NO_CONTENT)