Files

24 KiB
Raw Permalink Blame History

Device ↔ Endpoint contract

Written for: whoever implements the server side — framework-neutral, and host-neutral. The firmware only needs an HTTP endpoint at an IP and port, so a Raspberry Pi, a thin client, a NUC or a VM are all the same to it. This document says "the endpoint" throughout for that reason.

This is what the firmware in firmware/ actually sends and expects. It refines SPEC.md §4.1 in two places, both noted below. Base URL is http://<endpoint>:<port>/api/v1, plain HTTP on the LAN, TLS terminating on the endpoint (SPEC C2/C3).


Authentication

Two steps. The long-lived token never exists in firmware source or in a build flag.

1. Enrollment (once per device)

POST /api/v1/enroll
X-Enroll-Secret: <shared provisioning secret>
Content-Type: application/json

{ "device_uid": "a0b7651f2c3d", "device_name": "poorbird-cam-1",
  "hw_revision": "xiao-esp32s3-sense-ld2410", "fw_version": "0.1.0",
  "mac": "A0:B7:65:1F:2C:3D" }

device_uid is the eFuse MAC in hex. It survives reflashing, which is what makes it usable as an identity.

201 { "token": "<64 hex chars>", "device_id": 1,
      "reenroll_secret": "<64 hex chars, per device>",
      "server_time": 1758376267000, "config_version": 7 }

The endpoint stores only token_hash (SPEC §3 devices.token_hash; the token is high-entropy, so a fast hash is defensible here).

reenroll_secret — why the device keeps a credential

The camera cannot be reached over USB once it is mounted. That single fact decides this design. If enrollment wiped the device's secret, rotating a token in the admin UI would permanently lock the device out, and recovering it would mean taking it down and reflashing. So:

  1. The device enrolls with the shared bootstrap secret from secrets.ini.
  2. The endpoint returns a per-device reenroll_secret, which the device stores in NVS in place of the shared one.
  3. On any 401, the device clears its token, re-enrolls with that per-device secret, and retries — mid-burst, without rebooting.

Rotating a token is therefore a normal operation with no physical access. The credential left on the device is scoped to that device and cannot enroll any other identity, which is the part that makes keeping it acceptable.

reenroll_secret is optional. Omit it and the device keeps using the shared bootstrap secret instead — still self-healing, just a coarser credential.

There is one last-resort path: the shared bootstrap secret is compiled into the firmware image, and the device falls back to it if the stored per-device secret is ever rejected. The consequence worth knowing: do not rotate the shared bootstrap secret server-side without also shipping new firmware, or you remove the escape hatch.

Re-enrollment of a known device_uid must return the existing device row with a fresh token, not create a duplicate. Expect to see this on every token rotation and after any endpoint database restore.

2. Everything else

Authorization: Bearer <token>

Scoped to /ingest, /heartbeat, /status, /config, /commands/*/ack, /firmware/*, /stream/*. Never the gallery (SPEC §3.1: devices are not users).

Rotating a token in the admin UI needs no device-side action: the next request gets a 401 and the device re-enrolls itself, as described above.


Common request headers

Present on every authenticated request:

Header Meaning
X-Device-Uid eFuse MAC hex
X-Fw-Version running firmware version
X-Hw-Revision build-time hardware tag
X-Config-Version config version the device is running
X-Rssi current WiFi RSSI in dBm

X-Config-Version is what lets the Pi push settings without the device polling: if it differs from the server's, put the new version in the response envelope and the device pulls /config.


Response envelope

/ingest and /heartbeat return the same JSON shape. This is deliberate — SPEC §4.1 — so a capture that was going to happen anyway also delivers the command queue at no extra cost.

{
  "capture_id": 4711,
  "server_time": 1758376267000,
  "config_version": 7,
  "firmware": {
    "version": "0.2.0",
    "url": "/firmware/0.2.0.bin",
    "sha256": "3f786850e387550fdab836ed7e6dc881de23001b…",
    "size": 1148320
  },
  "commands": [
    { "id": 12, "type": "stream_start",
      "payload": { "session_id": "s-88f1", "duration_s": 45, "mode": 0 },
      "expires_at": 1758376400000 }
  ]
}
  • server_time — epoch ms, UTC. Authoritative (SPEC C7). The device adopts it whenever it is unsynced or more than 2 s out, so the Pi works as the clock even if SNTP is unavailable.
  • firmware — omit the key entirely when the device is on target. Present and different ⇒ the device flashes it on its own; no command needed. Use an explicit ota_update command only for staged rollouts.
  • commands — omit or send [] when empty.

POST /api/v1/ingest

Deviation from SPEC §4.1. The spec says multipart/form-data with image + JSON meta. The firmware sends the raw JPEG as the body with metadata in headers.

Why: multipart makes the device assemble a second buffer purely to add a wrapper the server strips immediately. Raw body hands the framebuffer pointer straight to the HTTP client — no copy, less heap, fewer failure modes. The metadata is a dozen flat scalars, which is exactly what headers are good at. It is still plainly REST:

curl -X POST http://pi:8080/api/v1/ingest \
  -H 'Authorization: Bearer …' -H 'Content-Type: image/jpeg' \
  -H 'X-Trigger: radar' -H 'X-Burst-Id: a0b765-3-91204' \
  --data-binary @frame.jpg
Header Type Notes
Content-Type image/jpeg body is the JPEG, nothing else
X-Trigger enum radar · manual · timer · stream_grab
X-Burst-Id string groups the frames of one event → captures.burst_id
X-Burst-Index int 0-based → captures.burst_index
X-Burst-Count int frames in this burst
X-Pre-Trigger 0/1 1 = this frame predates the trigger (see below)
X-Captured-At int64 epoch ms UTC, 0 when the device clock is unsynced
X-Frame-Seq int monotonic per boot
X-Radar-State 0–3 none / moving / stationary / both
X-Radar-Distance-Cm int
X-Radar-Energy 0–100

Response: 201 + the envelope above.

X-Pre-Trigger — worth a column in the database

With mains power the camera runs continuously into a PSRAM ring, so a burst contains frames from before the radar fired. Those are usually the good ones: the bird is still arriving rather than already leaving.

Add a pre_trigger BOOL column to captures and surface it in the gallery as a sort key within a burst. X-Captured-At already orders them correctly, but the flag tells you why a frame predates its own trigger, which is otherwise a confusing thing to see in the data.

X-Captured-At: 0 means unsynced, not 1970. Store NULL, not an epoch date. received_at stays authoritative either way (SPEC C7).


Device conditions — POST /heartbeat and POST /status

One body, two endpoints. Both send exactly the same JSON; they differ only in what comes back:

POST /api/v1/heartbeat POST /api/v1/status
Response 200 + the envelope (commands, config, firmware) 204, no body
Cadence heartbeat_interval_s (default 300 s) status_interval_s (default 900 s), plus on events
Also sent — after an upload burst, before sleep, before night sleep, on report_status

The split exists for one reason: 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. If you only want to implement one endpoint, implement /heartbeat and return 204 from /status — everything still works, you just get coarser telemetry.

{
  "reason": "periodic",
  "fw_version": "0.1.0", "hw_revision": "xiao-esp32s3-sense-ld2410",
  "config_version": 8,

  "power": {
    "uptime_ms": 91204,
    "awake_ms": 91204,          // ticks since the last wake
    "boot_count": 37,
    "wake_cause": "radar",      // power-on | radar | timer | other
    "last_sleep_s": 300,
    "total_sleep_s": 10800,
    "sleep_enabled": false,
    "sleep_allowed": false,
    "inhibits": "stream,upload"
  },

  "battery": {
    "valid": true,              // false = no divider wired
    "mv": 3912, "pct": 74, "raw_mv": 1956,
    "chemistry": 1, "low": false
  },

  "counters": {
    "captured_today": 412, "delivered_today": 407,
    "failed_today": 5, "events_today": 41,
    "day_index": 20716,
    "captured_boot": 88, "delivered_boot": 88
  },

  "camera": { "frame_size": 8, "jpeg_quality": 12, "profile": "day", "ready": true },
  "night":  { "is_night": false, "nightlight_on": false,
              "behaviour": 2, "capture_allowed": true },
  "stream": { "enabled": false, "active": false, "frames_sent": 0, "seconds_left": 0 },
  "radar":  { "baud": 256000, "uart_ok": true, "out_pin": false, "state": 0,
              "moving_cm": 0, "moving_energy": 0,
              "stationary_cm": 0, "stationary_energy": 0 },
  "system": { "rssi": -61, "ip": "192.168.1.88",
              "free_heap": 184320, "free_psram": 6815744,
              "ring_depth": 24, "ring_bytes": 1179648 },

  "time_synced": true,
  "device_time": "2026-09-20T14:31:07Z"
}

reason is one of heartbeat · periodic · after_event · before_sleep · before_night_sleep · on_request. Useful for spotting why a device went quiet: the last row before a gap tells you whether it slept deliberately.

Reading the fields that are easy to misread

battery.valid: false means not measured, not empty. No divider is wired by default — the XIAO does not bring its battery rail out to a readable pin. Render this as "—", never as 0 V, and do not raise a low-battery alarm on it. chemistry: 0 likewise means pct is meaningless; show the voltage only.

The counters are the device's opinion, not the truth. They live in RTC memory: they survive deep sleep and reset on power loss, and they are approximate by design. Your captures table is authoritative. What the counters are genuinely good for is the gap: captured_today well above delivered_today means frames are being taken and not arriving, which is a WiFi or disk problem you would otherwise only notice as "quiet camera".

day_index is days since epoch in local time, and it is the rollover key. It stays 0 until the clock syncs, so counters accumulated before the first sync land in a phantom day and then roll over once. Do not chart that bucket.

power.awake_ms is the "ticks since last sleep" — it resets on every wake, unlike uptime_ms, which also resets but only on reboot. In awake mode they are identical; in sleep mode awake_ms is the useful one.

A heartbeat the endpoint accepts is also what confirms an OTA trial boot. Returning 5xx to a device on a trial image will roll it back — correct behaviour, but worth knowing before you restart the Pi mid-rollout.


GET /api/v1/config

Returns the full device config. Every key optional; the device merges and clamps. See AppConfig in include/app_config.h for the authoritative list.

{
  "config_version": 8,

  "frame_size": "SVGA", "jpeg_quality": 12, "vflip": false, "hmirror": false,
  "cam_day":   { "...": "see below" },
  "cam_night": { "...": "see below" },

  "ring_frames": 24, "pre_roll": 4, "post_roll": 6,
  "post_roll_gap_ms": 250, "cooldown_s": 5, "idle_period_ms": 400,

  "radar_mode": 2, "accept_stationary": true,
  "min_distance_cm": 20, "max_distance_cm": 300, "min_energy": 20,
  "radar_baud": 0,

  "stream_enabled": false, "stream_frame_size": "VGA", "stream_jpeg_quality": 15,
  "stream_duration_s": 60, "stream_fps": 10, "stream_mode": 0,
  "stream_blocks_sleep": true,

  "night_start_min": 1260, "night_end_min": 360,
  "night_behaviour": 2, "nightlight_mode": 0, "nightlight_brightness": 128,

  "battery_chemistry": 0, "battery_divider_x100": 200,
  "battery_offset_mv": 0, "battery_min_pct_ota": 50, "battery_warn_pct": 20,

  "heartbeat_interval_s": 300, "status_interval_s": 900, "ota_enabled": true,

  "deep_sleep_enabled": false, "deep_sleep_s": 300,
  "sleep_wake_on_radar": true, "sleep_idle_timeout_s": 20,
  "sleep_max_awake_s": 300,

  "tz": "CET-1CEST,M3.5.0,M10.5.0/3"
}

Bump config_version on every change — that is the only thing the device compares. Every key is optional and the device clamps out-of-range values, so partial pushes are fine.

Enums

Key Values
frame_size, stream_frame_size a name: QVGA CIF VGA SVGA XGA HD SXGA UXGA QXGA QSXGA 5MP — see below
stream_mode 0=watch 1=record 2=both
radar_mode 0=OUT pin only 1=UART only 2=both
night_behaviour 0=capture 1=idle 2=sleep
nightlight_mode 0=off 1=on during burst 2=always on at night
battery_chemistry 0=none 1=Li-ion/LiPo 2=LiFePO4
radar_baud 0=autodetect (recommended), or an explicit rate to pin

radar.baud in the status payload reports what the device actually settled on, and 0 there means no valid frame was decoded at any rate — wiring or a dead module, worth an alert.

Send frame sizes by name, not by number

framesize_t is an enum in the camera driver, and entries have been inserted into the middle of it between driver releases — FRAMESIZE_128X128 and FRAMESIZE_320X320 both landed after the original ordering. A stored numeric index therefore means a different resolution after a firmware update built against a newer driver.

This bit this very firmware: an early draft defaulted to frame_size: 8 believing it was SVGA 800×600. In the driver actually installed, index 8 is CIF 400×296.

So the device accepts a name and resolves it against the enum symbols:

Name Pixels Note
QVGA 320×240
CIF 400×296
VGA 640×480 stream default
SVGA 800×600 stills default
XGA 1024×768
HD 1280×720
SXGA 1280×1024
UXGA 1600×1200 OV2640 maximum
QXGA 2048×1536 OV3660 / OV5640 only
QSXGA / 5MP 2560×1920 / 2592×1944 OV5640 only

A raw index is still accepted for compatibility, but store names.

The status payload reports both, plus the dimensions and the sensor's PID, so the UI never has to guess:

"camera": { "frame_size": "SVGA", "frame_size_id": 11,
            "width": 800, "height": 600,
            "sensor_pid": 9646, "profile": "day", "ready": true }

sensor_pid is 0x2640 OV2640, 0x3660 OV3660, 0x5640 OV5640. Worth surfacing: newer XIAO Sense units have shipped with OV3660 rather than OV2640, so do not assume from the product listing. A frame size the fitted sensor cannot reach is refused by the driver and logged, and the previous size stays in effect.

Camera tuning — cam_day and cam_night

Two complete OV2640 profiles. The device switches between them at the night boundary on its own, so dusk costs no round trip.

"cam_day": {
  "brightness": 0, "contrast": 1, "saturation": 0, "sharpness": 0,
  "ae_level": 1, "special_effect": 0, "wb_mode": 0,
  "gainceiling": 1, "agc_gain": 0, "aec_value": 300,
  "whitebal": true, "awb_gain": true,
  "exposure_ctrl": true, "aec2": true, "gain_ctrl": true,
  "bpc": true, "wpc": true, "raw_gma": true, "lenc": true,
  "dcw": true, "colorbar": false
}
Key Range What it does here
brightness, contrast, saturation, sharpness −2…2 Cosmetic. sharpness support on the OV2640 is patchy.
ae_level −2…2 Exposure bias. Raise it. Birds are usually backlit against bright sky, which fools metering into underexposing the bird.
gainceiling 0…6 (2×…128×) The setting that matters most. High gain lets the sensor pick a shorter shutter (freezes the bird, noisier); low gain forces a longer one (clean, smeared). Day default 4×, night 32×.
exposure_ctrl bool false = manual, use aec_value. Set this if motion blur turns out to be your limiting factor — it is the direct lever.
aec_value 0…1200 Manual shutter. Only read when exposure_ctrl is false.
gain_ctrl / agc_gain bool / 0…30 Same pattern for gain.
aec2 bool DSP-assisted metering. On.
wb_mode 0…4 auto / sunny / cloudy / office / home. Auto is fine outdoors.
whitebal, awb_gain bool Leave on.
bpc, wpc, raw_gma, lenc bool Dead-pixel, gamma and lens-shading correction. Leave on.
dcw bool Downsize/crop. On.
special_effect 0…6 none/negative/grayscale/red/green/blue/sepia. Grayscale (2) is arguably right for a night profile with IR illumination.
colorbar bool Test pattern. Set true to prove the whole pipeline works before you have optics or light — very useful during bring-up.

Night window and nightlight

night_start_min / night_end_min are minutes from local midnight (1260 = 21:00, 360 = 06:00). The fixed defaults are a fallback: the Pi knows the site's latitude, so the intended design is for it to compute real sunset/sunrise and push them daily via apply_config. That is a much better boundary than a fixed clock time, which is two hours wrong by December.

night_behaviour decides what happens inside that window:

Behaviour Reachable at night?
0 capture Keep working, using cam_night and the illuminator yes
1 idle Stay awake and reachable, capture nothing yes
2 sleep Deep sleep until morning, even when deep_sleep_enabled is false no

Mode 2 is the one that answers "nightlight off could make the ESP sleep by night". It is deliberately independent of the deep-sleep switch: a camera with no illuminator has nothing to do at 03:00 whether it is mains-powered or not. The cost is that the device is unreachable until night_end_min, so a config change made at 23:00 lands at dawn. It wakes a minute early to let auto-exposure settle.

Night sleep never wakes on the radar — the point is to ignore the night, not to photograph every cat that walks past.

Before you buy an illuminator, read the warning at the top of include/nightlight.h. Short version: the obvious choice is 850 nm IR, because birds barely perceive it — but the OV2640 on the XIAO Sense has an IR cut filter bonded over the sensor, so an IR LED produces a black frame. Your options are to accept no night capture (mode 2, and most garden birds are diurnal anyway), use dim continuous white light, or remove the IR filter.

Streaming vs sleeping

stream_blocks_sleep (default true) is the coupling between the two. A sleeping device cannot be told to start a stream (SPEC C1), so with this set, merely enabling streaming keeps the device awake and reachable — not just while a session runs. Clear it to let the device sleep anyway and accept that stream_start waits for the next wake.

The status payload reports this: power.sleep_allowed: false with inhibits naming the reason, so the WebUI can explain why a device that is configured to sleep is not sleeping.

Battery sensing

Nothing is wired by default and readings report valid: false. To enable it, add an external divider from BAT+ to PIN_BATTERY_ADC (default D3/GPIO4) — the wiring diagram is at the top of include/battery.h — then set battery_divider_x100 to your measured ratio and trim battery_offset_mv against a multimeter.

battery_min_pct_ota is SPEC C6's flash gate. Note the deliberate choice in batteryAboveOtaThreshold(): with no sensing hardware the gate allows the flash rather than blocking it, because refusing every OTA on a mains-powered device because an optional sensor is absent would be worse than the risk. Wire the divider if you want the gate to bite.


Commands

POST /api/v1/commands/{id}/ack → { "status": "done|failed|rejected", "detail": "…" }

type payload when it runs
apply_config inline config object, or omit to make the device GET /config immediately
capture_now — next capture-task tick
report_status — main loop; posts /status with reason: on_request
wake_and_hold {"seconds": 60} (capped at 900) immediately
sleep_now {"seconds": 0} (0 = deep_sleep_s) after the ack is sent
stream_start {"session_id","duration_s","mode","frame_size"} main loop
stream_stop — immediately
ota_update {"url","sha256","size"}, or empty to use the envelope target main loop
reboot — immediately, acked first

sleep_now on a device with sleep switched off acks rejected.


Firmware / OTA

GET /api/v1/firmware/{version}.bin — bearer auth, must send Content-Length (the device refuses chunked: it wants to size-check against the manifest before erasing a partition).

The device verifies SHA-256 over the whole image before activating the slot, then boots it in PENDING_VERIFY. It calls esp_ota_mark_app_valid only after a heartbeat the endpoint accepted — that proves WiFi, HTTP, auth and JSON parsing all work on the new image. Anything weaker would confirm a firmware that boots but cannot talk. If the trial image never checks in, the next reset rolls back automatically.

So: a bad firmware costs a reboot cycle, not a ladder.


Streaming

POST /api/v1/stream/{session_id}
Authorization: Bearer …
Content-Type: multipart/x-mixed-replace; boundary=poorbirdframe
X-Stream-Mode: watch | record | both
X-Duration-S: 60
Transfer-Encoding: chunked

The device pushes; the endpoint relays and/or records (SPEC C3 — the ESP32 never serves a stream and is never reachable from outside the LAN).

Getting it outside is then entirely the endpoint's problem, which is the point of the design: the hard parts (TLS, certificate renewal, auth, rate limiting, abuse handling) live on the machine with a package manager and logs, not on the camera. In rough order of effort:

  • LAN only — the endpoint re-serves the same multipart/x-mixed-replace stream to a browser. An <img src="/stream/live"> tag renders it with no JavaScript. Maybe thirty lines of server code.
  • Public, low effort — the same MJPEG endpoint behind a Cloudflare Tunnel: public hostname and TLS, no port forwarding, nothing exposed inbound. MJPEG is bandwidth-hungry but perfectly watchable for one or two viewers.
  • Public, done properly — feed the frames into MediaMTX and serve WebRTC or HLS. Lower latency, many viewers, and the transcode happens on the endpoint where there is CPU to spare.

None of these change anything on the device. It pushes JPEGs to one URL in every case.

Each part:

--poorbirdframe
Content-Type: image/jpeg
Content-Length: 18422
X-Timestamp: 1758376267123

<jpeg bytes>

Terminated by --poorbirdframe--. The device stops itself at X-Duration-S (hard-capped at 600 s in firmware, SPEC C9). Closing the connection server-side is a supported way to stop a stream — the device treats five consecutive failed writes as a normal end, so a viewer navigating away does not need a stream_stop command.

mode is advisory to the Pi; the device sends identical bytes in all three.


Behaviour the Pi should expect

  • Bounded retries, always. Three WiFi attempts with exponential backoff, then give up until the next cycle (SPEC §4.3). The device never hammers.
  • Heartbeat backoff. After four consecutive failures the interval doubles per failure up to one hour. A Pi that is down for maintenance does not generate a wall of failed requests.
  • Burst uploads are sequential, not concurrent. One connection at a time.
  • 401 anywhere clears the stored token and triggers re-enrollment.
  • Events are dropped while a stream is running. You will see a gap in captures for the duration of a session.