diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 0f84bd9..0b1b5e6 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -8,7 +8,7 @@ from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging -from .routes import enroll, health +from .routes import conditions, enroll, health log = logging.getLogger(__name__) @@ -46,9 +46,10 @@ def create_app() -> FastAPI: # Phase 2 device endpoints. See firmware/API.md for the contract. app.include_router(enroll.router, prefix=API_PREFIX) + app.include_router(conditions.router, prefix=API_PREFIX) - # Still to come: /ingest, /heartbeat, /status, /config, - # /commands/{id}/ack, /firmware/{version}.bin. + # Still to come: /ingest, /config, /commands/{id}/ack, + # /firmware/{version}.bin. # Phase 3 mounts the UI endpoints. return app diff --git a/server/src/poorbird/api/envelope.py b/server/src/poorbird/api/envelope.py new file mode 100644 index 0000000..6fbb942 --- /dev/null +++ b/server/src/poorbird/api/envelope.py @@ -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), + ) diff --git a/server/src/poorbird/api/routes/conditions.py b/server/src/poorbird/api/routes/conditions.py new file mode 100644 index 0000000..18cb926 --- /dev/null +++ b/server/src/poorbird/api/routes/conditions.py @@ -0,0 +1,138 @@ +"""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) diff --git a/server/tests/test_conditions.py b/server/tests/test_conditions.py new file mode 100644 index 0000000..4ae5e63 --- /dev/null +++ b/server/tests/test_conditions.py @@ -0,0 +1,350 @@ +"""POST /api/v1/heartbeat and POST /api/v1/status. + +One body, two endpoints. The tests that matter most are the ones pinning the +difference between them, because the split exists for a reason that is not +obvious from the payload. +""" + +from __future__ import annotations + +import secrets +from datetime import UTC, datetime, timedelta + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus, Firmware + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + """A live, enrolled device, removed again afterwards.""" + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="test-cam", + token_hash=hash_credential(token), + fw_version="0.1.0", + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +def body(reason: str = "periodic", **over) -> dict: + b = { + "reason": reason, + "fw_version": "0.1.0", + "config_version": 8, + "power": {"awake_ms": 91204, "boot_count": 37, "wake_cause": "radar"}, + "battery": {"valid": True, "mv": 3912, "pct": 74}, + "counters": {"captured_today": 412, "delivered_today": 407, "day_index": 20716}, + "camera": {"profile": "day", "ready": True}, + "night": {"is_night": False}, + "stream": {"active": False}, + "radar": {"baud": 256000, "uart_ok": True}, + "system": {"rssi": -61, "ip": "192.168.1.88", "free_heap": 184320}, + "time_synced": True, + "device_time": "2026-09-20T14:31:07Z", + } + b.update(over) + return b + + +# --- the split between the two endpoints ------------------------------------ + + +@needs_db +def test_heartbeat_returns_the_envelope(client, device): + _, auth = device + r = client.post("/api/v1/heartbeat", json=body(), headers=auth) + + assert r.status_code == 200 + e = r.json() + assert e["server_time"] > 1_700_000_000_000 + assert "config_version" in e + assert e["commands"] == [] + + +@needs_db +def test_status_returns_204_and_no_body(client, device): + _, auth = device + r = client.post("/api/v1/status", json=body("before_sleep"), headers=auth) + + assert r.status_code == 204 + assert r.content == b"" + + +@needs_db +def test_status_does_not_hand_out_commands(client, device, db): + """The whole reason the two endpoints exist. + + The device posts status immediately before deep sleep. Delivering commands + there would mark them delivered to a device about to be unable to run them. + """ + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="capture_now")) + db.commit() + + assert client.post("/api/v1/status", json=body("before_sleep"), headers=auth).status_code == 204 + + cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) + db.refresh(cmd) + assert cmd.delivered_at is None, "status must not claim commands" + + # ... but the next heartbeat still gets it. + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["capture_now"] + + +# --- commands --------------------------------------------------------------- + + +@needs_db +def test_heartbeat_claims_commands_and_marks_them_delivered(client, device, db): + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="reboot")) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["reboot"] + + cmd = db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) + db.refresh(cmd) + assert cmd.delivered_at is not None + + # Not handed out twice. + again = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert again["commands"] == [] + + +@needs_db +def test_expired_commands_are_not_delivered_but_are_kept(client, device, db): + """Kept so the admin UI can show that a command timed out.""" + d, auth = device + db.add( + DeviceCommand( + device_id=d.id, + type="capture_now", + expires_at=datetime.now(UTC) - timedelta(minutes=1), + ) + ) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["commands"] == [] + assert db.scalar(select(DeviceCommand).where(DeviceCommand.device_id == d.id)) is not None + + +@needs_db +def test_commands_come_back_in_creation_order(client, device, db): + d, auth = device + for t in ("wake_and_hold", "capture_now", "reboot"): + db.add(DeviceCommand(device_id=d.id, type=t)) + db.commit() # distinct created_at + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert [c["type"] for c in e["commands"]] == ["wake_and_hold", "capture_now", "reboot"] + + +@needs_db +def test_one_devices_commands_do_not_leak_to_another(client, device, db): + d, auth = device + other = Device(device_uid=secrets.token_hex(6), name="other") + db.add(other) + db.commit() + db.add(DeviceCommand(device_id=other.id, type="reboot")) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["commands"] == [] + + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == other.id)) + db.delete(db.get(Device, other.id)) + db.commit() + + +# --- firmware target -------------------------------------------------------- + + +@needs_db +def test_firmware_key_is_absent_when_the_device_is_on_target(client, device, db): + """Absent, not null: present-and-different is itself the flash instruction.""" + d, auth = device + fw = Firmware( + version="0.1.0", # same as the device + file_path="/srv/poorbird/fw/0.1.0.bin", + sha256="a" * 64, + size_bytes=1148320, + is_target=True, + ) + db.add(fw) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert "firmware" not in e + + db.delete(db.get(Firmware, fw.id)) + db.commit() + + +@needs_db +def test_a_different_target_is_offered_with_a_relative_url(client, device, db): + """ota_mgr.cpp appends a non-http url to the API base, which already ends + in /api/v1 -- so this must not carry the prefix itself.""" + d, auth = device + fw = Firmware( + version="0.2.0", + file_path="/srv/poorbird/fw/0.2.0.bin", + sha256="b" * 64, + size_bytes=1148320, + is_target=True, + ) + db.add(fw) + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() + assert e["firmware"]["version"] == "0.2.0" + assert e["firmware"]["url"] == "/firmware/0.2.0.bin" + assert not e["firmware"]["url"].startswith("/api/v1") + assert e["firmware"]["size"] == 1148320 + + db.delete(db.get(Firmware, fw.id)) + db.commit() + + +# --- telemetry recording ---------------------------------------------------- + + +@needs_db +def test_a_row_is_appended_per_report(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + client.post("/api/v1/status", json=body("after_event"), headers=auth) + + rows = db.scalars( + select(DeviceStatus).where(DeviceStatus.device_id == d.id).order_by(DeviceStatus.at) + ).all() + assert [r.reason for r in rows] == ["periodic", "after_event"] + assert rows[0].battery_mv == 3912 + assert rows[0].rssi == -61 + assert rows[0].day_index == 20716 + assert rows[0].free_heap == 184320 + + +@needs_db +def test_unknown_fields_survive_in_raw(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(quantum_flux=42), headers=auth) + + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.raw["quantum_flux"] == 42 + + +@needs_db +def test_last_known_conditions_are_denormalised_onto_the_device(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + + db.refresh(d) + assert d.battery_mv == 3912 + assert d.battery_pct == 74 + assert d.battery_valid is True + assert d.rssi == -61 + assert d.last_seen_at is not None + + +@needs_db +def test_a_field_the_device_omits_does_not_erase_the_last_good_value(client, device, db): + """None means 'not sent', not 'zero'.""" + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + client.post("/api/v1/heartbeat", json=body(battery={}, system={}), headers=auth) + + db.refresh(d) + assert d.battery_mv == 3912 + assert d.rssi == -61 + + +@needs_db +def test_battery_valid_false_is_recorded_as_false(client, device, db): + """false means NOT MEASURED. It must reach the UI as false, not as missing.""" + d, auth = device + client.post("/api/v1/heartbeat", json=body(battery={"valid": False}), headers=auth) + + db.refresh(d) + assert d.battery_valid is False + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.battery_valid is False + + +@needs_db +def test_the_device_is_marked_asleep_when_it_says_it_is_going_quiet(client, device, db): + d, auth = device + client.post("/api/v1/heartbeat", json=body(), headers=auth) + db.refresh(d) + assert d.awake is True + + client.post("/api/v1/status", json=body("before_night_sleep"), headers=auth) + db.refresh(d) + assert d.awake is False + + +@needs_db +def test_the_devices_reported_config_version_does_not_overwrite_the_servers(client, device, db): + """The difference between the two is exactly what tells the device to + GET /config. Letting the report win would erase the instruction.""" + d, auth = device + d.config_version = 9 + db.commit() + + e = client.post("/api/v1/heartbeat", json=body(config_version=3), headers=auth).json() + + db.refresh(d) + assert d.config_version == 9 + assert e["config_version"] == 9 + row = db.scalar(select(DeviceStatus).where(DeviceStatus.device_id == d.id)) + assert row.config_version == 3 # what the device said, kept as telemetry + + +# --- auth ------------------------------------------------------------------- + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_both_endpoints_require_a_bearer_token(client, path): + assert client.post(path, json=body()).status_code == 401 + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_a_disabled_device_is_refused(client, device, db, path): + d, auth = device + d.enabled = False + db.commit() + assert client.post(path, json=body(), headers=auth).status_code == 403 + + +@needs_db +@pytest.mark.parametrize("path", ["/api/v1/heartbeat", "/api/v1/status"]) +def test_an_unknown_reason_is_422(client, device, path): + _, auth = device + assert client.post(path, json=body("whenever"), headers=auth).status_code == 422