Files

40 KiB
Raw Permalink Blame History

SPEC: poorBird — PIR-triggered bird camera with Raspberry Pi backend

Status: Draft for decision · Date: 2026-09-08 Purpose: Three complete, self-consistent full-stack options at increasing effort levels. Pick one, then this document becomes the baseline.

Written in English for consistency with the working language of the review; say the word and I'll translate to German to match TODO.md.


0. Decisions taken (2026-09-20)

Hardware and transport are settled. The firmware skeleton in firmware/ implements these; firmware/API.md is the contract for the Pi side.

Decision Consequence
Board: Seeed XIAO ESP32S3 Sense Closes open question 2. 8 MB PSRAM, 8 MB flash, OV2640, built-in charging. Resolves C5 in favour of "low-power board".
Sensor: HLK-LD2410 24 GHz radar instead of PIR Works through plastic (sealed enclosure, no sensor cutout), reports distance + energy per gate, detects stationary targets. Supersedes most of C4's mitigations — see below.
Mains power, not battery + solar Voids C1, C5 and C9 as written. See below.
OTA mandatory C6 unchanged and now non-negotiable. Dual slots, SHA-256 verify, trial boot with automatic rollback, implemented.
Live stream: build the plumbing now Config surface (on/off, resolution, duration, record/watch/both) and a working chunked MJPEG push, device → Pi. Public relay stays out of scope (C3).
Time server on the endpoint SNTP against the endpoint, with server_time in every API response as the fallback. C7 unchanged: received_at stays authoritative.
Radar: plain LD2410, 5 V, no Bluetooth Baud rate is autodetected, not chosen: a factory-default module (256000), a reconfigured one (115200) and one that has been factory-reset all work without intervention.
The camera is not physically reachable once mounted No USB recovery. Drives the enrollment design below, and raises the stakes on OTA rollback and on verifying the LD2410's logic levels before connecting them.
Server host undecided — Pi, thin client, or something else Nothing on the ESP side depends on it; the firmware needs an HTTP endpoint at an IP and port. What it does change is below.
Language: C++ / Arduino-ESP32 3.x under PlatformIO Not MicroPython. Reasoning in the reply that accompanied this change; short version: camera + OTA rollback + PSRAM streaming are all first-class in C and third-party or absent in MicroPython.

What mains power changes

C1 is void in the default configuration. The device stays awake, so commands execute within a loop tick rather than at the next heartbeat. The device_commands queue is kept unchanged — it is still the right mechanism, and it is what makes the optional sleep mode work — but "Responsive Mode" is no longer a special tier with a documented battery cost. It is simply how the device runs.

C5 is void. Idle sleep current no longer constrains anything. Panel and battery sizing drop out of scope entirely.

C9 is void as a constraint, kept as a policy. Streaming no longer threatens the power budget. Sessions remain time-boxed (default 60 s, firmware-capped at 600 s) because an unbounded stream is still a bad default, not because of the battery.

C4 is largely solved, by a mechanism the battery design could not use. With the camera permanently initialised, the firmware captures continuously into a PSRAM ring buffer and, on a trigger, uploads the frames from before it. Effective trigger latency goes negative. This is the single biggest quality gain from the mains decision — see firmware/README.md.

Two schema additions follow from that:

  • captures.pre_trigger BOOL — was this frame captured before the trigger fired
  • devices.awake BOOL — reported in every heartbeat, so the WebUI can show command latency honestly

Device conditions and settings

The device posts a full conditions report (POST /status, and the same body on /heartbeat) carrying battery voltage, ticks since last wake, and daily captured/delivered counters; it pulls its settings from GET /config. Both are specified in firmware/API.md. Further schema additions:

device_status(                    -- time series, one row per report
  id, device_id, at, reason,      -- heartbeat | periodic | after_event |
                                  -- before_sleep | before_night_sleep | on_request
  battery_mv, battery_pct, battery_valid,
  awake_ms, boot_count, wake_cause, last_sleep_s, total_sleep_s,
  captured_today, delivered_today, failed_today, events_today,
  is_night, nightlight_on, cam_profile,
  rssi, free_heap, free_psram, ring_depth
)

devices also gains the settings surface: the camera tuning profiles (cam_day, cam_night — full OV2640 parameter sets), the night window and behaviour, nightlight mode and brightness, and battery calibration. Per §3.4 these are pushed via apply_config and versioned by config_version.

Two things the WebUI must get right, because both are easy to render as an alarm when they are not one: battery_valid = false means not measured (no divider is wired by default), not flat; and the daily counters live in RTC memory and reset on power loss, so the captures table stays authoritative — the counters' real value is the gap between captured and delivered, which is an upload-health signal.

Night behaviour supersedes part of C1 in the other direction. With night_behaviour = sleep (the default, since the OV2640's IR cut filter makes IR illumination useless without modification) the device is deliberately unreachable between dusk and dawn, even on mains. That is a decision about what the camera is for, not a power constraint.

C2, C3, C6, C7, C8 are unchanged.

Deep sleep is implemented anyway, as a switch

deep_sleep_enabled is a per-device config flag, flippable from the WebUI without a reflash. Off by default. Turning it on restores the battery-oriented behaviour described in C1 and §4.3 — and reinstates their costs: no pre-trigger ring, 1–3 s trigger latency, command latency up to deep_sleep_s, streaming only from the next wake.

One caveat worth recording: the LD2410 draws ~80 mA continuously and must stay powered to serve as a wake source, so with radar wake enabled the ESP sleeping saves very little. Real savings need either timer-only wake with the radar power-gated, or a low-quiescent PIR (AM312) as the wake source with the radar confirming once awake. This is a wiring decision; the firmware supports both.

Enrollment must be self-healing

Because there is no USB access to a mounted camera, a rotated token cannot be allowed to strand the device. The firmware therefore keeps a credential in NVS, deliberately:

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

The credential left on the device is scoped to that device and cannot enroll another identity, which is what makes keeping it acceptable under C2's threat model. The shared bootstrap secret stays in the firmware image as a last-resort path, so rotating it server-side without shipping new firmware removes the escape hatch.

Schema follow-on: devices.reenroll_secret_hash, and re-enrollment of a known device_uid must return the existing row with a fresh token rather than creating a duplicate.

Server host: Pi vs thin client

Undecided, and it does not block the ESP work. What it changes on the server side:

Raspberry Pi 4/5 Thin client (x86)
Power 3–8 W 10–20 W
Storage SSD over USB, or NVMe on a Pi 5 hat Native SATA/NVMe, no SD card to wear out
Container images linux/arm64 — cross-build or build on the device linux/amd64 — matches your dev machine
Detection (Option C) Marginal; wants a Coral or Hailo accelerator Comfortable on CPU, and a GPU is an option
Cost New Often €40–80 secondhand, with more RAM and CPU

A thin client is the better machine for everything except idle power, and it removes the SD-card-corruption failure mode that eats Pi deployments. If detection is ever likely to matter, it is the stronger choice. Revisit §10 question 5 once decided.

Still open from §10

Question 4 is answered: the stream is watched on the internal server first, and relayed outward from there if and when that is wanted. That is what §5–§7 already assume (C3), so nothing changes.

Questions 1 (option A/B/C), 5–9 and 11–17 are unanswered. Question 3 (does the trigger work for your birds) is now a radar-tuning question rather than a PIR one, and remains the biggest unknown in the project.

On question 1: A, B and C are whole server-side stacks, not just database choices — §5, §6 and §7 each pick a web framework, database, frontend, auth model, backup tool and deployment method together, because those choices constrain each other. The ESP firmware is identical under all three. Given the decisions above, Option B: record mode means the stream writer and the ingest writer are two concurrent writers, which is C8's actual argument for PostgreSQL. That was the one thing genuinely pushing past Option A, and streaming is now in scope.


1. Scope

1.1 In scope

ESP32-CAM (outdoor, battery + solar)

  • Photo capture triggered by PIR motion sensor
  • Upload to Raspberry Pi over LAN
  • Battery voltage reporting, low-battery alarm surfaced in the WebUI
  • Deep sleep with the longest practical duty cycle
  • Wake-up / command initiation from the WebUI (see constraint C1 — this needs redefining)
  • OTA firmware updates, driven from a WebUI admin view

Raspberry Pi (headless, SSD)

  • Database holding all capture and observation data
  • WebUI: gallery + edit functions
  • Backup to a remote NAS
  • Authentication and authorization (roles)
  • Configurable through the UI, with three themes: light, dark, blue

Observation data (editable)

  • Species, biologically grounded (scientific name, family, order, stable taxon ID — not free text)
  • Capture timestamp
  • Plus: individuals, age, sex, behaviour, certainty, notes, tags, favourite/reject — see §3

1.2 Future (design for, do not build)

  • Live stream to an external webspace on an own domain (see constraint C9)
  • Automatic species detection (see Option C, and §3 for the schema hooks)

1.3 Out of scope

  • Audio recording / BirdNET-style song identification (different sensor, different pipeline)
  • Multi-site deployment, mobile apps

2. Design constraints (apply to all three options)

These are not preferences. They are properties of the hardware and the network, and every option below respects them identically. Read this section before comparing the options — most of the interesting design work is here, not in the framework choice.

C1 — A deep-sleeping ESP32 cannot be contacted. At all.

Superseded by §0 for the default (mains-powered, always-awake) configuration. Still applies in full whenever deep_sleep_enabled is switched on.

In deep sleep the radio and the CPU are off. There is no packet, no magic frame, no server push that reaches the device. "Wake-up triggered by WebUI" as literally stated is not implementable.

What is implementable, and what all three options do:

Command queue, polled by the device. The WebUI writes a command row (wake_and_hold, capture_now, apply_config, ota_update, stream_start). The device drains the queue on every wake — PIR-triggered or on a scheduled heartbeat wake. Worst-case latency to a command equals the heartbeat interval.

Commands ride along on the upload response (§4.4), so a PIR event that happens to occur costs zero extra energy to also deliver a pending command.

Optional "Responsive Mode" for when you genuinely need low latency: light sleep with WiFi association retained (modem sleep, DTIM wake). Reachable within a beacon interval, at roughly 1–3 mA average instead of 15–40 µA — a factor of ~100. Viable while mains-powered, or in summer with a healthy battery; not viable as the default. Expose it as a per-device toggle with the power cost stated in the UI, defaulting to off.

So the honest requirement reads: "Commands issued in the WebUI are executed at the device's next wake; an admin may enable Responsive Mode for near-immediate execution at a documented battery cost."

C2 — No TLS on the ESP32

The device speaks plain HTTP with a bearer token to a fixed LAN address. All TLS terminates on the Pi.

Rationale: TLS on the ESP32 means a CA certificate baked into firmware. Certificate chains rotate. When that happens, a device mounted outdoors silently stops uploading and needs physical reflashing. The LAN threat model does not justify that failure mode. The bearer token prevents a stray device on your WiFi from filling the disk.

C3 — The Pi is the only internet-facing component

Now and in future. The ESP32 is never reachable from outside the LAN; the future public stream and public gallery are served by the Pi, outbound. This keeps the hard problems (TLS, certificate renewal, authn/authz, abuse handling, rate limiting) on the device that has a package manager and logs.

C4 — Trigger latency is physical, and birds are fast

Stage Typical
PIR assert after motion 0.3–2 s (sensor dependent)
ESP32 boot from deep sleep ~0.2–0.4 s
Camera init + auto-exposure settle 0.3–0.6 s (discard first 2–3 frames)
First usable frame ~1–3 s after the bird arrives

A bird flying through is gone. Mitigations, all three options:

  • Capture a burst of 3–5 frames, store all, let the UI pick
  • Aim at a place where birds linger — feeder, perch, water bath — not open air
  • Tune PIR sensitivity and cooldown from the UI

Also note PIR limitations that specifically hurt here: small warm targets at distance are marginal, direct sunlight and hot surfaces cause false triggers, and it does not work through glass. Validate the PIR + placement physically before writing backend code. If the false-trigger rate is unacceptable, the fallback is on-device frame differencing (Option C) or a beam-break / capacitive perch sensor.

C5 — Idle sleep current dominates the energy budget, not the photos

Superseded by §0. Mains powered; the board choice (XIAO ESP32S3 Sense) was made anyway. Kept for the record and for a future battery deployment.

Rough figures, to be validated by measurement:

AI-Thinker ESP32-CAM (unmodified) Low-power board (e.g. XIAO ESP32S3 Sense)
Deep sleep current ~1–3 mA (LDO + camera rail leak) ~15–40 µA
Idle drain per day 24–72 mAh 0.4–1 mAh
50 PIR events + 48 heartbeats/day ~12 mAh ~12 mAh
Total per day ~36–84 mAh ~13 mAh
Runtime on 3000 mAh, zero sun ~5–12 weeks ~30 weeks

The AI-Thinker board is not designed for low power. Its idle leak is 2–6× the entire photographic workload. Either hardware-mod it (bypass the LDO, gate the camera rail with a MOSFET) or pick a board built for battery use. Both are fine; doing neither means a 2 W panel that is comfortable in June and dead in December.

Panel sizing follows from that, not the reverse. Very rough Central European figures: a 2 W / 6 V panel yields on the order of ~1200 mAh/day in summer and ~300 mAh/day averaged over December, with multi-day near-zero stretches under snow. Size the battery for a ~2-week no-sun reserve.

Related: a weak WiFi signal at the camera location extends transmit time and therefore drains battery. Measure RSSI at the mounting point before committing.

C6 — OTA must be planned from the first flash

Dual OTA partitions and a rollback slot have to exist in the partition table from the beginning. Retrofitting them means a physical reflash of a device that is by then mounted outdoors.

Rules in all options:

  • Device compares its running version against the server's target on wake
  • Refuse to flash below a battery threshold (default 50 %) — a brownout mid-write bricks the device
  • Verify SHA-256 before activating the new slot
  • Boot the new image once in a trial state; roll back automatically if it fails to check in

C7 — Time: the server clock is authoritative

The ESP32 RTC survives deep sleep but drifts, and is lost on any power cycle. So:

  • Device sends best-effort NTP time plus a monotonic boot counter
  • Server received_at is authoritative for ordering and for the gallery's date filter
  • Store both captured_at_device and received_at
  • Store UTC everywhere; render in local timezone. Set TZ explicitly on every service — a container defaulting to UTC while you think in CEST is a bug that surfaces months later at a DST boundary.

C8 — If SQLite, exactly one writer

SQLite is entirely adequate for this project's volume. Its real constraint is not scale, it is concurrency: two processes writing produces intermittent database is locked. Options A and B therefore keep all writes inside a single process, with WAL mode and an explicit busy_timeout. Option C introduces a genuine second writer and moves to PostgreSQL for that reason — not for "scalability".

C9 — Live streaming is incompatible with battery operation

Superseded by §0 as a constraint. The time-boxing survives as policy, not as a power measure.

MJPEG streaming from an ESP32-CAM draws roughly 200 mA continuously and cannot deep sleep while doing it. A 60-second stream costs about 3.3 mAh — several PIR events' worth.

Therefore the future stream is: admin-triggered, time-boxed (default 60 s), rate-limited, gated on battery level, and only reachable after the device's next wake. Not "always available". The ESP32 pushes to the Pi; the Pi relays outward (C3). Reserve the stream_start command type in the schema now and build nothing else.


3. Common data model

Identical across all three options; only the engine and the migration tooling change.

The important structural decision: captures 1—n observations. One photo can contain two birds of different species, and a photo can legitimately have zero observations (false PIR trigger, empty frame). A single species column on the image would have to be undone later.

The second important decision: human labels and model predictions share one table, distinguished by source. This means the edit UI is the training-data pipeline for any future detection model, with no migration needed when you get there.

-- Devices ------------------------------------------------------------------
devices(
  id, name, hw_revision, fw_version,
  token_hash,                     -- bearer token for ingest, rotatable from admin UI
  last_seen_at, battery_mv, battery_pct, rssi, temp_c,
  responsive_mode BOOL DEFAULT false,     -- C1
  heartbeat_interval_s INT DEFAULT 1800,
  enabled BOOL, created_at
)

device_commands(                  -- C1: the wake-up mechanism
  id, device_id,
  type,        -- wake_and_hold | capture_now | apply_config | ota_update | stream_start | reboot
  payload,     -- JSON
  created_by, created_at,
  delivered_at, acked_at, result, expires_at
)

firmware(
  id, version, semver, file_path, sha256, size_bytes,
  release_notes, min_battery_pct DEFAULT 50,   -- C6
  uploaded_by, uploaded_at, is_target BOOL
)

-- Captures -----------------------------------------------------------------
captures(
  id, device_id,
  path, thumb_path, sha256, width, height, bytes,
  captured_at_device, received_at,             -- C7, received_at authoritative
  trigger,          -- pir | timer | manual | stream_grab
  burst_id, burst_index,                       -- C4: 3-5 frames per event
  battery_mv, rssi, temp_c,
  reviewed BOOL DEFAULT false,
  kept BOOL DEFAULT true,                      -- soft reject, drives retention
  created_at
)

observations(
  id, capture_id, taxon_id NULL,
  individuals INT DEFAULT 1,
  age,          -- adult | juvenile | unknown
  sex,          -- male | female | unknown
  behaviour,    -- feeding | bathing | perching | nesting | fighting | other
  certainty,    -- certain | probable | uncertain
  notes,
  source,       -- human | model
  model_version NULL, confidence NULL, bbox NULL,   -- future detection
  created_by, created_at, updated_at
)

taxa(                             -- seeded, not user-entered free text
  id, gbif_key, scientific_name,
  name_de, name_en, family, "order",
  iucn_status, is_local_common BOOL     -- drives autocomplete ranking
)

tags(id, label, colour)
capture_tags(capture_id, tag_id)

-- Access -------------------------------------------------------------------
users(
  id, username, email, password_hash,          -- Argon2id
  role,        -- admin | editor | viewer
  totp_secret NULL, is_active,
  theme,       -- light | dark | blue
  locale, created_at, last_login_at
)
sessions(id, user_id, created_at, expires_at, ip, user_agent)

-- Operations ---------------------------------------------------------------
settings(key, value, value_type, scope, updated_by, updated_at)   -- scope: server | device
audit_log(id, at, user_id, action, entity, entity_id, before, after, ip)
backup_runs(id, started_at, finished_at, status, bytes, snapshot_id, error)

3.1 Roles

viewer editor admin
Browse gallery, view data ✅ ✅ ✅
Create/edit observations, tags ❌ ✅ ✅
Delete captures ❌ ❌ ✅
Device settings, commands, wake ❌ ❌ ✅
Firmware upload / OTA ❌ ❌ ✅
Users, backup, server settings ❌ ❌ ✅

Devices are not users. The ESP32 authenticates with a per-device bearer token scoped to POST /ingest, POST /heartbeat, GET /firmware. It can never read the gallery.

3.2 Taxonomy

Seed taxa from a curated list of ~60–80 Central European garden species with GBIF taxon keys, German and scientific names, family and order. The edit form autocompletes on either name and ranks is_local_common first. Anything beyond the seed list is a one-row admin addition, not free text.

This is what makes "information about species (biologically)" real rather than a string column that accumulates Kohlmeise, kohlmeise, Parus major and Kohlmeise? as four distinct species.

3.3 Storage layout

Images on the SSD, date-sharded, never in the database:

/srv/poorbird/images/2026/09/08/<uuid>.jpg
/srv/poorbird/thumbs/2026/09/08/<uuid>_400.webp

Auth-checked image serving in all options: the app authorizes the request and hands off the bytes to the reverse proxy (nginx X-Accel-Redirect / Caddy equivalent). An unguessable URL is not access control — without this, images are effectively public even though the UI is behind a login.

3.4 Settings exposed in the UI

"Fully configurable" needs a boundary, or it never finishes. The enumerated list:

Device settings (pushed to NVS via apply_config on next wake): resolution, JPEG quality, burst count, PIR cooldown, heartbeat interval, battery alarm threshold, responsive mode, timezone.

Server settings: retention policy, thumbnail size, backup schedule + target, alarm thresholds and channels, default theme, default locale, session lifetime.

Anything not on this list is a code change, deliberately.


4. Shared API shape

Same in all options; the framework differs.

4.1 Device endpoints (bearer token, plain HTTP, LAN only)

POST /api/v1/ingest             multipart: image + JSON meta  → 201 {capture_id, commands[], config_version, firmware}
POST /api/v1/heartbeat          JSON: battery, rssi, fw, uptime → 200 {commands[], config_version, firmware}
GET  /api/v1/firmware/{version}.bin
POST /api/v1/commands/{id}/ack  JSON: {status, detail}

The upload response carries the pending command queue. The device is already awake and associated, so this delivers commands and config at zero extra energy cost. A separate poll only happens on heartbeat wakes when no PIR event occurred.

GET/PATCH/DELETE  /api/v1/captures[/{id}]        filter: date range, taxon, device, tag, reviewed, kept
POST/PATCH/DELETE /api/v1/captures/{id}/observations[/{oid}]
GET               /api/v1/taxa?q=               autocomplete
GET/POST          /api/v1/devices[/{id}/commands]
POST              /api/v1/firmware               admin upload
GET/PATCH         /api/v1/settings
GET               /api/v1/health                 device online, battery, disk, last backup

4.3 Firmware state machine (all options)

deep sleep
   │  PIR (ext0/ext1) ──or── timer (heartbeat)
   ▼
boot → read NVS config → init camera → discard 2-3 frames
   │
   ├─ PIR wake:  capture burst → connect WiFi → POST /ingest  ──┐
   └─ timer wake:            → connect WiFi → POST /heartbeat ──┤
                                                                ▼
                                              process commands + config
                                                                │
                              ┌─────────────────────────────────┤
                              ▼                                 ▼
                   ota_update & battery ok?            wake_and_hold?
                   download → verify sha256            stay awake N seconds
                   → flash inactive slot → reboot      (bounded, then sleep)
                              │                                 │
                              └──────────────┬──────────────────┘
                                             ▼
                              back to deep sleep (bounded retries,
                              exponential backoff, always sleep on failure)

Every failure path ends in sleep. An unbounded retry loop on a WiFi outage is the fastest way to flatten the battery — bound retries (e.g. 3 attempts with backoff), then sleep and try at the next wake.


5. Option A — Minimal

Goal: bird photos visible in a browser with the least moving parts. No JavaScript build step, no Docker, no broker.

Layer Choice
Firmware Arduino-ESP32 core (built on ESP-IDF), esp32-camera, HTTPClient, Update.h for OTA, Preferences for NVS
Transport HTTP POST multipart/form-data — no MQTT, no broker
Backend Python 3.13 + Flask, gunicorn (1 process / 4 threads → satisfies C8 structurally)
Database SQLite, WAL mode, busy_timeout=5000
Migrations Plain numbered .sql files applied by a small runner
Frontend Jinja2 server-rendered + HTMX for inline edit and filtering. No npm, no bundler, no Node on the Pi.
Themes Hand-written CSS custom properties, data-theme on <html>, three token sets, persisted per user + localStorage for first paint
Images Pillow for thumbnails on upload, served via nginx X-Accel-Redirect
Auth Flask-Login, Argon2id (argon2-cffi), server-side sessions, Flask-WTF CSRF, 3 roles via decorator
Reverse proxy nginx, self-signed cert or Tailscale-provided cert
Remote access Tailscale
Backup cron → VACUUM INTO snapshot + rsync -a --delete over SSH to NAS
Deploy systemd units (poorbird-web.service), apt + venv. No containers.
Alarms WebUI health banner + a nightly email or ntfy push on low battery / device offline / backup failure

Note on the DB backup: cp poorbird.db on a live WAL database can produce a corrupt copy. Use VACUUM INTO (or sqlite3 .backup) to get a consistent snapshot. This is the single most common way home-lab backups turn out to be worthless.

How the tricky requirements are met

  • Wake-up: device_commands table, drained on upload response + 30-minute heartbeat. Responsive Mode not implemented in this tier.
  • OTA: admin uploads a .bin, marks it target; device pulls on next wake if version differs and battery ≥ 50 %.
  • Low battery: voltage in every payload; threshold check server-side; banner + push.
  • Backup: rsync to NAS. Non-blocking, alerts on failure.
  • 3 themes: CSS variables, no framework.

What you give up

  • No task queue: thumbnailing happens inline in the request (~100–300 ms, acceptable at this volume)
  • No 2FA, no audit log, no fine-grained permissions beyond the three roles
  • Server-rendered UI — snappy, but not a client-side SPA gallery
  • No detection pipeline, and Postgres would be a migration if you ever need concurrent writers
  • Restore is manual, from a documented procedure

Rough effort: walking skeleton (PIR → photo → gallery) in a weekend or two; the full spec above in ~4–6 weeks part-time.


6. Option B — Solid

Goal: the version you can still maintain in three years. Proper migrations, typed API, real backups, containerised.

Layer Choice
Firmware ESP-IDF v5.x — dual OTA partitions + esp_ota rollback, calibrated ADC battery read with a MOSFET-gated divider, exponential backoff, structured logging
Transport HTTP POST + bearer token (C2)
Backend Python 3.13 + FastAPI, Pydantic v2, SQLAlchemy 2.0, Alembic migrations
Database PostgreSQL 17
Job queue Postgres-backed, FOR UPDATE SKIP LOCKED — thumbnails, backups, retention, exports. No Redis.
Frontend React + TypeScript + Vite + TanStack Query/Router, virtualised gallery grid. Built on your dev machine, shipped as static files.
Themes Design tokens → CSS custom properties, ThemeProvider, three themes, per-user persisted
Auth Session cookies, Argon2id, optional TOTP 2FA, per-device tokens, RBAC with an explicit permission matrix, full audit_log
Reverse proxy Caddy — automatic TLS; valid Let's Encrypt certs for a LAN-only hostname via DNS-01, so no port forwarding and no browser warnings
Remote access Tailscale
Backup restic → NAS over SFTP; pg_dump pre-hook; retention 7 daily / 4 weekly / 12 monthly; healthcheck ping; monthly automated restore test into a scratch container
Deploy Docker Compose — now justified, because there are genuinely several services. Images built with buildx --platform linux/arm64 on the dev machine. Healthchecks + condition: service_healthy, log rotation (max-size/max-file), .env for secrets, .dockerignore, explicit TZ
Alarms ntfy/Gotify push + WebUI, for low battery, device offline > N hours, disk > 80 %, backup failure

Why PostgreSQL here and not in Option A: this tier introduces a background worker, which is a second writer (C8). Multiple writers is a good reason for Postgres. "Scalability" for a one-camera garden project is not — ignore that argument if you meet it.

How the tricky requirements are met

  • Wake-up: command queue + adaptive heartbeat (e.g. 5 min in daylight, 60 min at night — better latency when birds are active, less drain when they aren't) + Responsive Mode toggle with the mA cost shown in the UI
  • OTA: signed manifest, SHA-256 verify, trial boot with automatic rollback, battery gate, staged rollout per device
  • Backup: restic with a tested restore. A backup you have never restored is a hypothesis.
  • Config: settings table → config_version → device pulls and writes NVS on next wake

What you give up

  • No automatic species detection (schema is ready; the pipeline is not built)
  • No public stream
  • No metrics/dashboards beyond the health endpoint

Rough effort: ~3–4 months part-time. This is the recommendation.


7. Option C — Full platform

Goal: everything in the brief plus automatic species detection, observability, and a real path to the public stream.

Everything in Option B, plus:

Area Addition
Hardware Low-power board (C5) · DS3231 RTC for reliable time across power cycles · BME280 for temperature/humidity enrichment · multi-camera support
Firmware On-device frame differencing to confirm PIR triggers before spending WiFi energy — cuts false positives and battery drain together · Secure Boot v2 + flash encryption + anti-rollback · device provisioning flow
Detection Two-stage: an animal/bird detector (YOLO-class or MegaDetector) then a species classifier fine-tuned on your own labelled captures. ONNX Runtime or LiteRT in a dedicated container. Predictions land in observations with source='model' alongside human labels.
The loop The edit UI doubles as a labelling tool — keyboard-driven (j/k to move, 1–9 for the top species, Enter to confirm) — feeding periodic retraining. This is what makes detection actually work on your garden and your camera angle, rather than a generic model that confuses Blaumeise and Kohlmeise.
Storage Content-addressed image store, optional MinIO
Auth External OIDC (Pocket ID / Authelia / Keycloak), fine-grained RBAC, ready for the public site's OAuth2
Observability Prometheus + Grafana + Loki; alerting on battery, device offline, disk, backup failure, detection queue depth
Backup restic → NAS and offsite (B2/S3), monitored with a dead-man switch, documented RPO/RTO, automated restore verification
Public stream MediaMTX on the Pi: ESP32 pushes on demand → MediaMTX → WebRTC/HLS out via Cloudflare Tunnel (public domain + TLS, no port forwarding, ESP32 still never internet-facing per C3). Time-boxed and battery-gated per C9.
Provisioning Ansible playbook for the whole Pi, so a card failure is a rebuild rather than an archaeology project
Frontend PWA, offline-capable, full design-token system across the three themes

Deliberately still not included: Kubernetes. k3s on a single Pi adds a control plane and gains nothing here. Docker Compose remains correct even at this tier.

Honest note on detection accuracy: a generic pretrained model will disappoint on small, partly obscured, motion-blurred garden birds. Expect to label 500–2000 of your own images before fine-tuning earns its keep. Budget for that, or treat detection as pre-filtering ("bird / no bird", which works well and immediately) rather than species identification.

Rough effort: ~6–12 months part-time. Only worth it if the detection loop is the point.


8. Comparison

A — Minimal B — Solid C — Full platform
Firmware Arduino core ESP-IDF v5 ESP-IDF v5 + secure boot
Backend Flask FastAPI FastAPI + workers
Database SQLite PostgreSQL 17 PostgreSQL 17 + Redis
Frontend Jinja2 + HTMX React + TS React PWA
Node.js needed ❌ dev machine only dev machine only
Containers ❌ systemd ✅ Compose ✅ Compose
Migrations numbered SQL Alembic Alembic
2FA / audit log ❌ ✅ ✅ + OIDC
Backup rsync + snapshot restic + restore test restic + offsite + verify
Responsive Mode ❌ ✅ ✅
Species detection ❌ ❌ (schema ready) ✅
Public stream ❌ ❌ ✅
Metrics/alerting banner + push push Prometheus/Grafana
Effort (part-time) 4–6 weeks 3–4 months 6–12 months

Recommendation

Build Option A's walking skeleton first, then grow into Option B.

Not because A is the goal, but because the riskiest unknowns in this project are physical, not architectural: does PIR reliably trigger on the birds at your feeder, at your distance, in your light? What is the real sleep current of your board? How many usable frames per day do you actually get? All three options share §2, §3 and §4 — so a week spent proving the hardware with Flask and SQLite is not wasted work if you then move to FastAPI and Postgres. The data model does not change.

Deciding between B and C can wait until you have a few thousand real captures, at which point you will also know whether you want detection badly enough to label them.


9. Shared hardware notes

Item Note
Camera board AI-Thinker ESP32-CAM works, but see C5 — either mod it or use a low-power board with built-in charging
PIR sensor AM312 preferred over HC-SR501: 3.3 V native, far lower quiescent draw. Wake via ext0 on an RTC-capable GPIO — check pin conflicts carefully, the ESP32-CAM has very few free pins once camera and SD are wired
Battery LiFePO4 worth considering over LiPo: better cold tolerance, far more cycles, and 3.2–3.65 V suits a 3.3 V rail. Either chemistry: neither can be safely charged below 0 °C — use a charger with NTC cutoff, or inhibit charging in frost
Panel Size after measuring sleep current, not before. ~2 W/6 V is a reasonable starting point with a low-power board
Battery sense Voltage divider on an ADC pin, gated by a MOSFET — an always-connected divider drains the battery continuously. Calibrate; the ESP32 ADC is non-linear
Enclosure IP65 minimum, sun shade over the lens, drainage, desiccant. Condensation on the lens ruins more photos than any software bug
Pi Model matters (see open questions). Put Docker's data-root on the SSD; set up log rotation or the SD card dies
Network Measure RSSI at the mounting point. DHCP reservation for the Pi, then hardcode that IP in firmware — simpler and more reliable than mDNS

10. Open questions

Ordered by how much they block. The first four change the build; the rest can be answered as you go.

Blocking

  1. Which option — A, B or C? Or A-now-then-B, as recommended in §8?
  2. Camera board: unmodified AI-Thinker, hardware-modified AI-Thinker, or a low-power board with built-in charging? Per C5 this decides the solar/battery sizing more than anything else does.
  3. Does PIR actually work for your birds, at your placement? Needs a physical test before software. If not: on-device frame differencing, or a perch/beam sensor?
  4. Is Tailscale-only remote access enough, or do you want a public domain and a public gallery reasonably soon? Answering "public soon" pulls OAuth2, rate limiting, and a hardened ingress back into scope.

Shapes the design

  1. Raspberry Pi model and RAM? Pi 4 vs Pi 5 vs NVMe-capable — affects boot-from-SSD setup and rules Option C's detection in or out.
  2. How many cameras, eventually? One, or several? The schema supports many; device management UI and OTA staging get more work if it's really more than one.
  3. Expected volume: captures per day, roughly? Drives storage, retention, and whether inline thumbnailing is fine.
  4. Retention policy: keep everything forever, or auto-delete rejected/unlabelled captures after N days? A birdcam will fill any disk you give it. And: does deleting a capture in the UI delete the file, or only hide it?
  5. NAS access protocol: SSH/SFTP available? SMB or NFS only? restic and borg want SFTP or a mounted path — this decides the backup tooling.
  6. Battery chemistry, and do you care about winter operation? Charging below freezing is the crux.

Details worth settling early

  1. UI language: German, English, or both? i18n is cheap on day one and annoying to retrofit. Species names should carry name_de and name_en regardless.
  2. Taxonomy source: GBIF backbone keys as proposed, or IOC / Avibase? And which regional species list should seed the autocomplete?
  3. The "blue" theme — any reference you have in mind (a screenshot, a palette, a site you like), or my choice?
  4. Is 2FA a requirement, or is a strong password on a LAN-only service enough for now?
  5. Beyond species, timestamp and the fields proposed in §3 — anything else you want to record? Weather, feeder type, ring number, whether you were watching?
  6. Your comfort level in C, Python, and TypeScript? This should genuinely influence the A/B/C choice more than the feature lists do — Option B's React frontend is the largest single chunk of unfamiliar work if TypeScript is new.
  7. Can the camera see beyond your own property — a neighbour's garden, a public path? If so there is a GDPR dimension worth one paragraph in the deployment notes.