ESP: first implementation; compiles fine; not tested with MCU
This commit is contained in:
1 parent
5bdcb51bff
commit
6bda641ce8
36 files changed
+6234
No files matched your search
@@ -0,0 +1,4 @@
|
||||
.pio/
|
||||
.vscode/
|
||||
secrets.ini
|
||||
*.bin
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
# 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.
|
||||
|
||||
```json
|
||||
{
|
||||
"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.
|
||||
|
||||
```json
|
||||
{
|
||||
"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.
|
||||
|
||||
```json
|
||||
{
|
||||
"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:
|
||||
|
||||
```json
|
||||
"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.
|
||||
|
||||
```json
|
||||
"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.
|
||||
@@ -0,0 +1,314 @@
|
||||
# poorBird firmware — XIAO ESP32S3 Sense + HLK-LD2410
|
||||
|
||||
ESP-side skeleton.
|
||||
|
||||
**Verified:** builds clean from scratch against pioarduino 53.03.13
|
||||
(Arduino-ESP32 3.1.x / IDF 5.3), no warnings in project sources.
|
||||
1132 KB flash (34 % of a 3.2 MB OTA slot), 60 KB static RAM.
|
||||
|
||||
**Not verified:** none of it has run on hardware. The LD2410 frame offsets are
|
||||
transcribed from the datasheet, the XIAO status-LED pin has moved between board
|
||||
revisions, and no radio, camera or radar code path has executed. Treat the
|
||||
first bring-up as a debugging session, not a smoke test.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
platformio.ini build config; the knobs live in [common]
|
||||
secrets.ini.example copy to secrets.ini (gitignored) before flashing
|
||||
partitions/ 8 MB, dual OTA slots + rollback (SPEC C6)
|
||||
scripts/load_secrets.py turns secrets.ini into -D flags
|
||||
|
||||
include/board_pins.h ALL wiring in one place, every free pin overridable
|
||||
include/app_config.h the full runtime config struct
|
||||
|
||||
src/app_config.cpp NVS load/save, JSON merge from the endpoint, clamps
|
||||
src/power_mgr.cpp the deep-sleep on/off switch and its inhibit locks
|
||||
src/camera_mgr.cpp OV2640 lifecycle + day/night tuning profiles
|
||||
src/frame_ring.cpp PSRAM pre-trigger ring ← the interesting one
|
||||
src/ld2410.cpp radar UART protocol + presence pin
|
||||
src/net_mgr.cpp WiFi with bounded retries, clock from the endpoint
|
||||
src/api_client.cpp REST client: enroll, ingest, heartbeat, status, config, stream
|
||||
src/battery.cpp supply voltage, percentage curves, the OTA gate
|
||||
src/device_stats.cpp daily counters in RTC memory, local-midnight rollover
|
||||
src/nightlight.cpp night window, illuminator, what to do after dark
|
||||
src/ota_mgr.cpp SHA-256 verify, trial boot, automatic rollback
|
||||
src/stream_session.cpp time-boxed MJPEG push
|
||||
src/commands.cpp the WebUI → device command queue
|
||||
src/main.cpp both operating modes
|
||||
```
|
||||
|
||||
`API.md` is the contract for the Pi side.
|
||||
|
||||
## Wiring
|
||||
|
||||
| LD2410 | XIAO | GPIO | Note |
|
||||
|---|---|---|---|
|
||||
| VCC | 5V | — | plain LD2410, no Bluetooth |
|
||||
| GND | GND | — | |
|
||||
| TX | D1 | 2 | ESP receives — **measure this, see below** |
|
||||
| RX | D0 | 1 | ESP transmits; 3.3 V clears the module's input threshold |
|
||||
| OUT | D2 | 3 | active high; RTC-capable, so it doubles as the deep-sleep wake pin — **measure this too** |
|
||||
|
||||
**Measure OUT and TX with a multimeter before connecting them.** The LD2410's
|
||||
logic is supposed to be 3.3 V even on a 5 V supply, but this varies between
|
||||
batches and clones, and the ESP32-S3 is not 5 V tolerant. Wave a hand at the
|
||||
module so OUT asserts, then measure. If either reads ~5 V, drop it with a
|
||||
divider: 10k from the module into the GPIO, 20k from the GPIO to ground. Two
|
||||
minutes now beats discovering a dead pin on a camera you cannot reach.
|
||||
|
||||
**Baud rate needs no decision.** `radarBegin()` probes 256000, 115200, 57600,
|
||||
38400 and 9600 and keeps whichever produces valid frames, so a factory-default
|
||||
module and a reconfigured one both just work — and a factory reset (which
|
||||
returns the module to 256000) does not silently take the trigger offline. Pin
|
||||
it with the `radar_baud` setting if you would rather it not probe.
|
||||
|
||||
Optional, nothing wired by default:
|
||||
|
||||
| Function | Default pin | Note |
|
||||
|---|---|---|
|
||||
| Battery sense | `D3` / GPIO4 | needs an external divider — see the diagram in `include/battery.h` |
|
||||
| Divider enable | — (`-1`) | MOSFET on the divider's low side, so it only draws during a read |
|
||||
| Nightlight | — (`-1`) | PWM; drive a MOSFET, never the LED directly |
|
||||
| Radar power gate | — (`-1`) | only useful for timer-only deep sleep |
|
||||
|
||||
Still free: `D4`/GPIO5 + `D5`/GPIO6 (I²C for a future BME280 or DS3231),
|
||||
`D6`/GPIO43 + `D7`/GPIO44 (UART0 — deliberately left for hardware debug).
|
||||
`D8`–`D10` are the Sense board's microSD; leave them if you want local
|
||||
buffering later.
|
||||
|
||||
Change any of it with a `-D` flag, no source edit:
|
||||
|
||||
```ini
|
||||
build_flags = ${common.build_flags} -DPIN_RADAR_OUT=4 -DRADAR_BAUD=115200
|
||||
```
|
||||
|
||||
## First flash
|
||||
|
||||
```bash
|
||||
cp secrets.ini.example secrets.ini # then edit it
|
||||
pio run -e xiao_s3_sense -t upload
|
||||
pio device monitor
|
||||
```
|
||||
|
||||
The first build downloads ~1 GB of toolchain and takes about 12 minutes;
|
||||
afterwards a clean rebuild is under a minute.
|
||||
|
||||
`platformio.ini` pins pioarduino `53.03.13` because PlatformIO Core 6.1.x
|
||||
cannot load the current `stable` release (it needs Core >= 6.2.0). If you run
|
||||
`pio upgrade` to 6.2.0, you can switch the `platform =` line to the `stable`
|
||||
alias and get Arduino 3.3 / IDF 5.5.
|
||||
|
||||
On the Pi, generate the enrollment secret with `openssl rand -hex 32` and put
|
||||
the same value in both places. On first boot the device trades it for a
|
||||
per-device token, stores that in NVS, and wipes the secret.
|
||||
|
||||
Expected first-boot log:
|
||||
|
||||
```
|
||||
poorBird 0.1.0 (xiao-esp32s3-sense-ld2410)
|
||||
power: boot #1, wake cause power-on, 0s slept so far
|
||||
--- poorBird config ---
|
||||
radar: UART1 @256000 baud (detected) rx=2 tx=1 out=3
|
||||
radar self-test: 1284 bytes, 7 decoded frames, OUT=0
|
||||
wifi: 192.168.1.88 rssi -58 dBm
|
||||
enrolled via stored secret: token + per-device re-enrollment secret stored
|
||||
time: synced, 2026-09-20T14:31:07Z
|
||||
camera ready: sensor PID 0x2640, SVGA (800x600) quality=12 psram_free=6784KB
|
||||
ring: 24 slots x 48KB = 1152KB PSRAM (free 6784KB)
|
||||
awake mode: pre-trigger ring active (24 frames, ~9.6 s of history)
|
||||
```
|
||||
|
||||
`radar: no UART frames at any baud` ⇒ TX and RX are not crossed, the module
|
||||
is not powered, or it is dead. The baud rate is no longer a candidate
|
||||
explanation, since all the plausible rates were tried. The OUT pin path still
|
||||
works in the meantime: set `radar_mode: 0` to trigger on it alone.
|
||||
|
||||
## The two power modes
|
||||
|
||||
One flag, `deep_sleep_enabled`, switchable from the WebUI at runtime.
|
||||
|
||||
| | **awake** (default) | **sleep** |
|
||||
|---|---|---|
|
||||
| Camera | always initialised | off between events |
|
||||
| Pre-trigger frames | **yes**, ~10 s of history | no |
|
||||
| Trigger→first frame | effectively negative | 1–3 s (SPEC C4) |
|
||||
| Command latency | one loop tick | up to `deep_sleep_s` |
|
||||
| Streaming | on demand | only from the next wake |
|
||||
| ESP current | ~80–120 mA | tens of µA asleep |
|
||||
|
||||
Switching it on does not slam the door: the device finishes the current wake
|
||||
(so the ack reaches the Pi) and only then sleeps, giving you
|
||||
`sleep_idle_timeout_s` to change your mind. Switching it off takes effect at
|
||||
the next wake — unavoidable, that is SPEC C1.
|
||||
|
||||
Sleep is blocked outright by refcounted inhibits: an upload in flight, a live
|
||||
stream, an OTA flash, a `wake_and_hold`. `sleep_max_awake_s` is a deadlock
|
||||
escape that overrides all of them **except OTA** — sleeping mid-flash bricks
|
||||
the device.
|
||||
|
||||
### The honest caveat
|
||||
|
||||
The LD2410 draws roughly 80 mA continuously and must stay powered to act as a
|
||||
wake source. So with `sleep_wake_on_radar = true`, the ESP sleeping at 20 µA
|
||||
saves you almost nothing — the radar dominates. Deep sleep is a real power win
|
||||
only if you either:
|
||||
|
||||
- set `sleep_wake_on_radar = false`, wake on the timer alone, and power-gate
|
||||
the radar through a MOSFET on `PIN_RADAR_EN`; or
|
||||
- fit an AM312 PIR on `PIN_AUX_ADC` as the wake source and use the radar only
|
||||
to confirm once awake.
|
||||
|
||||
That is a wiring decision. The switch works either way.
|
||||
|
||||
## Why the ring buffer is the point
|
||||
|
||||
SPEC C4 says the first usable frame lands 1–3 s after the bird arrives, by
|
||||
which time a small bird is gone. That is only true if capture *starts* at the
|
||||
trigger.
|
||||
|
||||
Running on mains, the camera captures continuously into a PSRAM ring. On a
|
||||
trigger the device ships `pre_roll` frames from **before** it plus `post_roll`
|
||||
frames from after. Effective latency goes negative and C4 stops being a
|
||||
problem. Cost: `ring_frames × ~48 KB` of the 8 MB PSRAM — about 1.1 MB at the
|
||||
defaults, for roughly 10 s of history.
|
||||
|
||||
This is the single largest quality difference between the battery design in
|
||||
`SPEC.md` and this one, and it is why the mains decision is worth more than it
|
||||
first looks.
|
||||
|
||||
## Cameras
|
||||
|
||||
The XIAO ESP32S3 **Sense** ships with an OV2640 on its expansion board, and
|
||||
that is what this firmware drives. The ESP32-S3 handles it better than the
|
||||
original ESP32-CAM does, because the S3 has a dedicated LCD_CAM peripheral
|
||||
rather than repurposing I²S.
|
||||
|
||||
Three things worth knowing before you buy or swap anything:
|
||||
|
||||
**The bare XIAO ESP32S3 cannot take a camera.** The DVP pins (GPIO 10–18, 38,
|
||||
39, 40, 47, 48) are not on the 14 castellated pads — they only come out
|
||||
through the board-to-board connector that the Sense expansion board mates
|
||||
with. "XIAO ESP32S3 + a camera module" is not a working combination; you need
|
||||
the Sense.
|
||||
|
||||
**You may receive an OV3660 rather than an OV2640.** Seeed's wiki still says
|
||||
OV2640, but newer units have reportedly shipped with OV3660. The driver
|
||||
detects the sensor over SCCB at init, so the firmware does not care — it logs
|
||||
the PID (`0x2640` / `0x3660` / `0x5640`) and reports it in the status payload.
|
||||
An OV3660 gives you QXGA 2048×1536 instead of the OV2640's UXGA ceiling.
|
||||
|
||||
**The OV5640 is an official drop-in upgrade** (Seeed sells it for this board,
|
||||
with a heat sink). 2592×1944 versus the OV2640's 1600×1200, better low light,
|
||||
and autofocus. Whether it is worth it here:
|
||||
|
||||
- *For* — pixels on target is the real limit when the bird is small in frame.
|
||||
- *Against* — bigger JPEGs mean fewer ring slots and longer uploads, it is
|
||||
slower at full resolution (so a lower ring frame rate and less pre-trigger
|
||||
history), and it runs hot enough to ship with a heat sink. Autofocus is
|
||||
arguably a downside on a fixed-distance feeder, where fixed focus is more
|
||||
predictable and never hunts at the wrong moment.
|
||||
- If you switch, **drop `ring_frames`**. Twenty-four slots at ~400 KB is
|
||||
9.6 MB, more than the 8 MB of PSRAM; the ring degrades gracefully and logs,
|
||||
but you want about 12.
|
||||
|
||||
The frame size is set by name (`"SVGA"`, `"UXGA"`), never by number — see
|
||||
`API.md` for why that matters.
|
||||
|
||||
## Night, and why the default is to sleep through it
|
||||
|
||||
`night_behaviour` decides what happens between `night_start_min` and
|
||||
`night_end_min` (minutes from local midnight; the Pi should push real
|
||||
sunset/sunrise, the 21:00–06:00 defaults are a fallback):
|
||||
|
||||
- **0 `capture`** — keep working, using the `cam_night` tuning profile and the
|
||||
illuminator if one is fitted.
|
||||
- **1 `idle`** — stay awake and reachable, capture nothing.
|
||||
- **2 `sleep`** (default) — deep sleep until morning, **even when
|
||||
`deep_sleep_enabled` is false**. A camera with no illuminator has nothing to
|
||||
do at 03:00 whether it is mains-powered or not. The cost: unreachable until
|
||||
dawn, so a config change made at 23:00 lands in the morning.
|
||||
|
||||
Night sleep never wakes on the radar. The point is to ignore the night, not to
|
||||
photograph every cat that walks past.
|
||||
|
||||
### Read this before buying an illuminator
|
||||
|
||||
The obvious choice is 850 nm or 940 nm IR, because birds barely perceive it and
|
||||
white light at a feeder at night is disruptive. But **the OV2640 module on the
|
||||
XIAO Sense has an IR cut filter bonded over the sensor**, which blocks exactly
|
||||
those wavelengths. An IR LED on an unmodified Sense gives you a black frame.
|
||||
|
||||
In the order I would try them:
|
||||
|
||||
1. Accept no night capture (`night_behaviour: 2`). Most garden birds are
|
||||
diurnal; you lose very little and the whole problem goes away.
|
||||
2. Dim, warm, continuous white light (`nightlight_mode: 2`). Continuous beats a
|
||||
flash per burst — animals habituate to steady light and startle at sudden
|
||||
light — and auto-exposure is already settled when a bird arrives. Still
|
||||
disturbs wildlife.
|
||||
3. Remove the IR filter and use 850 nm. Best images, irreversible, and it
|
||||
wrecks daytime colour unless you fit a switchable filter.
|
||||
|
||||
The firmware supports all three; option 3 needs no code change.
|
||||
|
||||
## Battery sensing
|
||||
|
||||
Off by default: the XIAO does not bring its battery rail out to a pin you can
|
||||
simply read, so this needs an external divider from BAT+ to `PIN_BATTERY_ADC`.
|
||||
The wiring is documented at the top of `include/battery.h`. Until it is wired,
|
||||
readings report `valid: false` — which the endpoint must render as "not
|
||||
measured", never as 0 V.
|
||||
|
||||
Once wired, set `battery_divider_x100` from your *measured* resistor values
|
||||
(not their printed ones) and trim `battery_offset_mv` against a multimeter.
|
||||
Percentage comes from a piecewise curve per chemistry. For LiFePO4 be warned
|
||||
that the curve is nearly flat between 20 % and 90 % — the percentage there is
|
||||
close to meaningless, which is a property of the chemistry, not of the code.
|
||||
|
||||
This also arms SPEC C6's OTA battery gate. One deliberate choice worth
|
||||
knowing: with **no** sensing hardware the gate allows the flash rather than
|
||||
blocking it, on the grounds that refusing every OTA on a mains-powered device
|
||||
because an optional sensor is absent is worse than the risk it guards against.
|
||||
|
||||
## Tuning the radar for birds
|
||||
|
||||
The LD2410 is designed to detect *humans*. A blue tit has a far smaller radar
|
||||
cross-section, and swaying branches and heavy rain both register. Expect to
|
||||
spend an evening on this. Everything below is a config push, not a reflash:
|
||||
|
||||
- `max_distance_cm` — window it tightly to the feeder. The single most
|
||||
effective false-positive filter.
|
||||
- `min_energy` — raise until branches stop triggering, lower until birds start.
|
||||
- `accept_stationary` — a bird sitting on a perch is a stationary target. On
|
||||
for a feeder, off if you only care about arrivals.
|
||||
- `radar_mode` — `0` ignores the UART entirely and trusts the OUT pin. Useful
|
||||
to isolate whether a problem is the protocol decode or the sensor itself.
|
||||
|
||||
If it cannot be made to work, `PIN_AUX_ADC` is free for an AM312 and the
|
||||
trigger logic is one function (`radarIsTrigger`).
|
||||
|
||||
## What is deliberately not here
|
||||
|
||||
- **Local SD buffering.** Uploads that fail are lost rather than queued to the
|
||||
microSD. Worth adding if the WiFi link turns out to be marginal; the pins are
|
||||
free.
|
||||
- **On-device frame differencing** (SPEC Option C). The ring buffer makes this
|
||||
much easier to add later — you already have consecutive frames in PSRAM.
|
||||
- **TLS.** Deliberate, SPEC C2.
|
||||
|
||||
## Open items in the code
|
||||
|
||||
- `ld2410.cpp` frame offsets are from the datasheet, not verified.
|
||||
- Battery percentage curves are generic open-circuit approximations at room
|
||||
temperature. Good enough for a low banner and the OTA gate, not for a
|
||||
runtime estimate.
|
||||
- `nightlight.cpp` allocates an LEDC channel after the camera has taken
|
||||
channel 0 for XCLK. That should route around it, but it is untested.
|
||||
- Daily counters live in RTC memory and reset on power loss, by design. The
|
||||
endpoint's own count is authoritative.
|
||||
- `radarSetGateSensitivity` sends the command but only checks that *something*
|
||||
came back, not that the ACK matches.
|
||||
- `PIN_STATUS_LED` (GPIO21) has moved between XIAO board revisions — verify.
|
||||
- The LD2410's logic level on a 5 V supply is unverified on this hardware.
|
||||
Measure before connecting; see Wiring.
|
||||
@@ -0,0 +1,103 @@
|
||||
// api_client.h — everything the device says to the Pi.
|
||||
//
|
||||
// TRANSPORT DECISION (answers "standard REST API, I guess?")
|
||||
// Yes, REST over plain HTTP with a bearer token (SPEC C2 — TLS stays on the
|
||||
// Pi). One deviation from SPEC §4.1, and it is worth making:
|
||||
//
|
||||
// SPEC says: POST /ingest multipart/form-data: image + JSON meta
|
||||
// we do: POST /ingest Content-Type: image/jpeg, raw body, meta in headers
|
||||
//
|
||||
// Why: multipart means the device assembles a body with boundaries, so the
|
||||
// JPEG gets copied into a second buffer purely to add a wrapper the server
|
||||
// immediately strips. Raw body + headers hands esp_http_client the framebuffer
|
||||
// pointer directly — no copy, no assembly, less heap, and one fewer thing to
|
||||
// get wrong at 3 a.m. It is still an ordinary REST call; `curl --data-binary
|
||||
// @frame.jpg -H 'X-Trigger: radar'` reproduces it exactly.
|
||||
//
|
||||
// The metadata is small and flat (a dozen scalars), which is precisely the
|
||||
// case headers handle well. If it ever grows nested structure, switch that one
|
||||
// endpoint to multipart and keep the rest.
|
||||
//
|
||||
// AUTH DECISION (answers "the token comes from the endpoint, I guess?")
|
||||
// Yes. Two-step, and the long-lived token is never in source or in a build
|
||||
// flag:
|
||||
// 1. A *shared enrollment secret* is compiled in (or typed once). The device
|
||||
// POSTs /enroll with its eFuse-derived UID.
|
||||
// 2. The Pi creates the device row, returns a per-device token, and the
|
||||
// device stores it in NVS and wipes the enrollment secret.
|
||||
// From then on every request carries `Authorization: Bearer <token>`. Rotating
|
||||
// a token in the admin UI just means the next request 401s and the device
|
||||
// re-enrolls. The Pi stores only the hash (SPEC §3 `devices.token_hash`).
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
#include "frame_ring.h"
|
||||
|
||||
// What the endpoint sends back on ingest/heartbeat. SPEC §4.1: the upload
|
||||
// response carries the command queue, so a capture that was going to happen
|
||||
// anyway also delivers pending commands at no extra cost.
|
||||
struct ServerEnvelope {
|
||||
bool ok;
|
||||
int http_status;
|
||||
int64_t server_time_ms; // authoritative clock (SPEC C7)
|
||||
uint32_t config_version; // if it differs from ours, pull config
|
||||
bool has_firmware;
|
||||
char fw_version[24];
|
||||
char fw_url[160];
|
||||
char fw_sha256[65];
|
||||
uint32_t fw_size;
|
||||
// Commands are handled inside the parse callback rather than copied out,
|
||||
// so this struct stays a fixed-size value type.
|
||||
uint8_t command_count;
|
||||
};
|
||||
|
||||
struct CaptureMeta {
|
||||
const char* trigger; // radar | timer | manual | prebuffer | stream_grab
|
||||
const char* burst_id; // groups the frames of one event
|
||||
uint8_t burst_index;
|
||||
uint8_t burst_count;
|
||||
int8_t pre_trigger; // 1 if this frame predates the trigger
|
||||
uint16_t radar_distance_cm;
|
||||
uint8_t radar_energy;
|
||||
uint8_t radar_state;
|
||||
};
|
||||
|
||||
// Called once per command in a response envelope.
|
||||
typedef void (*CommandHandler)(JsonObjectConst cmd);
|
||||
|
||||
void apiBegin();
|
||||
|
||||
// Exchange the enrollment secret for a device token. No-op if already enrolled.
|
||||
// Returns true when g_cfg.device_token is populated and persisted.
|
||||
bool apiEnroll();
|
||||
|
||||
// POST one JPEG. `meta` rides in headers.
|
||||
ServerEnvelope apiIngest(const FrameCopy& frame, const CaptureMeta& meta, CommandHandler on_cmd);
|
||||
|
||||
// POST device conditions; the response carries the same envelope as ingest.
|
||||
// This is the call that drains the command queue, so it is also the one that
|
||||
// must not be made from somewhere the device cannot then act on a command.
|
||||
ServerEnvelope apiHeartbeat(CommandHandler on_cmd);
|
||||
|
||||
// POST the same conditions body to /status, which returns 204 and no command
|
||||
// queue. For pushes where picking up commands would be wrong or wasteful:
|
||||
// immediately before deep sleep (the device is about to become unable to act),
|
||||
// after an upload burst, or on an explicit report_status command.
|
||||
// Returns true on a 2xx.
|
||||
bool apiPostStatus(const char* reason);
|
||||
|
||||
// GET the full device config and merge it into g_cfg. Returns true if changed.
|
||||
bool apiFetchConfig();
|
||||
|
||||
// Report a command's outcome so the WebUI can stop showing it as pending.
|
||||
bool apiAckCommand(uint32_t command_id, const char* status, const char* detail);
|
||||
|
||||
// Open a chunked MJPEG push for a streaming session. See stream_session.cpp.
|
||||
bool apiStreamOpen(const char* session_id, uint8_t mode, uint16_t duration_s);
|
||||
bool apiStreamSendFrame(const uint8_t* jpeg, size_t len, int64_t epoch_ms);
|
||||
void apiStreamClose();
|
||||
|
||||
// True when the last request returned 401 — the caller should re-enroll.
|
||||
bool apiTokenRejected();
|
||||
@@ -0,0 +1,193 @@
|
||||
// app_config.h — the device's entire runtime configuration.
|
||||
//
|
||||
// Three layers, later ones win:
|
||||
// 1. compile-time defaults (platformio.ini -D flags)
|
||||
// 2. NVS, written on first boot and on every accepted config push
|
||||
// 3. `apply_config` command from the endpoint, carrying a config_version
|
||||
//
|
||||
// The endpoint is the source of truth. The device reports the config_version it
|
||||
// is running in every request; the endpoint pushes a new config whenever those
|
||||
// disagree. That keeps SPEC §3.4 ("Device settings pushed via apply_config")
|
||||
// working without a separate settings-fetch round trip.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
enum StreamMode : uint8_t {
|
||||
STREAM_WATCH = 0, // relay to viewers, do not persist
|
||||
STREAM_RECORD = 1, // persist on the Pi, no live viewers
|
||||
STREAM_BOTH = 2,
|
||||
};
|
||||
|
||||
enum RadarMode : uint8_t {
|
||||
RADAR_OUT_PIN_ONLY = 0, // trust the module's presence pin, ignore UART
|
||||
RADAR_UART_ONLY = 1, // decode reports, apply distance/energy windows
|
||||
RADAR_BOTH = 2, // OUT pin arms, UART report confirms (default)
|
||||
};
|
||||
|
||||
enum NightBehaviour : uint8_t {
|
||||
NIGHT_CAPTURE = 0, // keep working, using the night camera profile
|
||||
NIGHT_IDLE = 1, // stay awake and reachable, but capture nothing
|
||||
NIGHT_SLEEP = 2, // deep sleep until morning, even if deep sleep is off
|
||||
};
|
||||
|
||||
enum NightlightMode : uint8_t {
|
||||
NIGHTLIGHT_OFF = 0,
|
||||
NIGHTLIGHT_ON_BURST = 1, // illuminate only while a burst is being captured
|
||||
NIGHTLIGHT_ALWAYS = 2, // on for the whole night; kinder to wildlife
|
||||
};
|
||||
|
||||
enum BatteryChemistry : uint8_t {
|
||||
BATT_NONE = 0, // no cell wired; report voltage only, no percentage
|
||||
BATT_LIION = 1, // Li-ion / LiPo, 4.20 V full
|
||||
BATT_LIFEPO4 = 2, // LiFePO4, 3.65 V full — flat curve, see battery.cpp
|
||||
};
|
||||
|
||||
// OV2640 tuning. Held twice (day and night) so the device can switch profiles
|
||||
// at dusk without a round trip to the endpoint. Ranges are the sensor's own;
|
||||
// see camera_mgr.cpp for what each one is worth on a bird camera.
|
||||
struct CamTuning {
|
||||
int8_t brightness; // -2..2
|
||||
int8_t contrast; // -2..2
|
||||
int8_t saturation; // -2..2
|
||||
int8_t sharpness; // -2..2 (OV2640 support is patchy)
|
||||
int8_t ae_level; // -2..2 exposure bias
|
||||
uint8_t special_effect; // 0 none 1 negative 2 grayscale 3 red 4 green 5 blue 6 sepia
|
||||
uint8_t wb_mode; // 0 auto 1 sunny 2 cloudy 3 office 4 home
|
||||
uint8_t gainceiling; // 0=2x 1=4x 2=8x 3=16x 4=32x 5=64x 6=128x
|
||||
uint8_t agc_gain; // 0..30, only used when gain_ctrl = 0
|
||||
uint16_t aec_value; // 0..1200, only used when exposure_ctrl = 0
|
||||
bool whitebal;
|
||||
bool awb_gain;
|
||||
bool exposure_ctrl; // false = manual, use aec_value
|
||||
bool aec2; // DSP-assisted auto exposure
|
||||
bool gain_ctrl; // false = manual, use agc_gain
|
||||
bool bpc; // black pixel correction
|
||||
bool wpc; // white pixel correction
|
||||
bool raw_gma;
|
||||
bool lenc; // lens shading correction
|
||||
bool dcw; // downsize/crop enable
|
||||
bool colorbar; // test pattern — bring-up only
|
||||
};
|
||||
|
||||
struct AppConfig {
|
||||
// --- identity & endpoint ---------------------------------------------
|
||||
char device_name[32];
|
||||
char wifi_ssid[33];
|
||||
char wifi_pass[64];
|
||||
char api_host[64]; // Pi's IP. Use a DHCP reservation, not mDNS.
|
||||
uint16_t api_port;
|
||||
char api_base[24]; // "/api/v1"
|
||||
char device_token[65]; // issued by the endpoint at enrollment
|
||||
// The secret used to (re-)enroll. Starts as the shared bootstrap secret
|
||||
// from secrets.ini and is replaced, at first enrollment, by a per-device
|
||||
// one issued by the endpoint. Deliberately NOT wiped: the device must be
|
||||
// able to recover from a token rotation on its own, because reaching it
|
||||
// over USB is not an option once it is mounted. See api_client.h.
|
||||
char enroll_secret[65];
|
||||
|
||||
// --- time (SPEC C7: the endpoint is the time server) -------------------
|
||||
char ntp_host[64]; // empty => use api_host
|
||||
char tz[48]; // POSIX TZ string
|
||||
|
||||
// --- camera ------------------------------------------------------------
|
||||
uint8_t frame_size; // framesize_t
|
||||
uint8_t jpeg_quality; // 4..40, lower is better
|
||||
bool vflip;
|
||||
bool hmirror;
|
||||
CamTuning cam_day;
|
||||
CamTuning cam_night; // applied automatically between dusk and dawn
|
||||
|
||||
// --- capture / trigger ---------------------------------------------------
|
||||
uint8_t ring_frames; // PSRAM history depth
|
||||
uint8_t pre_roll; // frames sent from before the trigger
|
||||
uint8_t post_roll; // frames sent after
|
||||
uint16_t post_roll_gap_ms; // spacing between post-roll frames
|
||||
uint16_t cooldown_s; // minimum gap between two trigger events
|
||||
uint16_t idle_period_ms; // ring refresh period when nothing is happening
|
||||
|
||||
// --- radar ---------------------------------------------------------------
|
||||
uint8_t radar_mode; // RadarMode
|
||||
bool accept_stationary; // a motionless bird still counts
|
||||
uint16_t min_distance_cm;
|
||||
uint16_t max_distance_cm;
|
||||
uint8_t min_energy; // 0..100, per-report energy floor
|
||||
uint32_t radar_baud; // 0 = autodetect (recommended)
|
||||
|
||||
// --- live stream (SPEC C9 — plumbing built, off by default) --------------
|
||||
bool stream_enabled;
|
||||
uint8_t stream_frame_size; // usually lower than stills
|
||||
uint8_t stream_jpeg_quality;
|
||||
uint16_t stream_duration_s; // hard cap; the device stops itself
|
||||
uint8_t stream_fps;
|
||||
uint8_t stream_mode; // StreamMode
|
||||
|
||||
// Streaming and sleeping are mutually exclusive: a sleeping device cannot
|
||||
// be told to start a stream (SPEC C1). With this set, enabling streaming
|
||||
// keeps the device awake and reachable so `stream_start` arrives promptly.
|
||||
// Clear it to let the device sleep anyway and accept the wake latency.
|
||||
bool stream_blocks_sleep;
|
||||
|
||||
// --- night ---------------------------------------------------------------
|
||||
// The window is minutes from local midnight. The endpoint knows the site's
|
||||
// latitude, so the intended use is for the Pi to push real sunset/sunrise
|
||||
// daily; the fixed defaults are only a fallback.
|
||||
uint16_t night_start_min; // default 21:00
|
||||
uint16_t night_end_min; // default 06:00
|
||||
uint8_t night_behaviour; // NightBehaviour
|
||||
uint8_t nightlight_mode; // NightlightMode
|
||||
uint8_t nightlight_brightness; // 0..255 PWM duty
|
||||
|
||||
// --- battery / supply -----------------------------------------------------
|
||||
uint8_t battery_chemistry; // BatteryChemistry
|
||||
uint16_t battery_divider_x100; // divider ratio x100, e.g. 200 = 2.00:1
|
||||
int16_t battery_offset_mv; // calibration trim, added after scaling
|
||||
uint8_t battery_min_pct_ota; // SPEC C6: refuse to flash below this
|
||||
uint8_t battery_warn_pct; // surfaced to the WebUI as a low alarm
|
||||
|
||||
// --- ops -----------------------------------------------------------------
|
||||
uint16_t heartbeat_interval_s;
|
||||
uint16_t status_interval_s; // POST /status cadence; 0 = only on events
|
||||
bool ota_enabled;
|
||||
|
||||
// --- power (see power_mgr.h for what each mode gives up) ------------------
|
||||
bool deep_sleep_enabled; // the master on/off switch
|
||||
uint16_t deep_sleep_s; // timer wake interval while asleep
|
||||
bool sleep_wake_on_radar; // also wake on the LD2410 OUT pin
|
||||
uint16_t sleep_idle_timeout_s; // stay awake this long after the last event
|
||||
uint16_t sleep_max_awake_s; // hard cap: sleep even if something is stuck
|
||||
|
||||
uint32_t config_version;
|
||||
};
|
||||
|
||||
extern AppConfig g_cfg;
|
||||
|
||||
// Load from NVS, filling anything missing from the compile-time defaults.
|
||||
void configLoad();
|
||||
|
||||
// Persist the current g_cfg to NVS. Returns false if the write failed.
|
||||
bool configSave();
|
||||
|
||||
// Merge a config document pushed by the endpoint into g_cfg. Only keys present
|
||||
// in `doc` are touched, so the endpoint can send partial updates. Returns true
|
||||
// if anything actually changed (caller decides whether a reboot is needed).
|
||||
bool configApplyJson(JsonObjectConst doc);
|
||||
|
||||
// True when a change needs the camera re-initialised rather than just applied.
|
||||
bool configNeedsCameraRestart(const AppConfig& before, const AppConfig& after);
|
||||
|
||||
// Stable per-device identifier derived from the eFuse MAC. Survives reflashing,
|
||||
// which is what makes it usable as the enrollment key.
|
||||
const char* deviceUid();
|
||||
|
||||
// The shared bootstrap secret compiled in from secrets.ini. Kept reachable as
|
||||
// a last-resort fallback: if the per-device re-enrollment secret in NVS is
|
||||
// ever rejected, the device can still get back in with this one rather than
|
||||
// needing a USB cable.
|
||||
const char* configBootstrapSecret();
|
||||
|
||||
// Base URL without trailing slash, e.g. "http://192.168.1.50:8080/api/v1".
|
||||
String apiBaseUrl();
|
||||
|
||||
void configDump();
|
||||
@@ -0,0 +1,47 @@
|
||||
// battery.h — supply / battery voltage sensing.
|
||||
//
|
||||
// WIRING (nothing is wired by default; reads report invalid until it is)
|
||||
// The XIAO ESP32S3 does not bring the battery rail out to an ADC pin you can
|
||||
// simply read — the documented approaches involve soldering, and the divider
|
||||
// differs between board revisions. So this driver assumes an *external*
|
||||
// divider you add yourself:
|
||||
//
|
||||
// BAT+ ──[ R1 ]──┬──[ R2 ]── GND
|
||||
// └── PIN_BATTERY_ADC (default D3 / GPIO4)
|
||||
//
|
||||
// Two 1 MΩ resistors give a 2.00:1 ratio and ~2 µA of continuous drain, which
|
||||
// is negligible on mains and tolerable on battery. If you care about the last
|
||||
// microamp, gate the low side with a MOSFET on PIN_BATTERY_EN — SPEC §9 is
|
||||
// right that an always-connected divider is a permanent load.
|
||||
//
|
||||
// Set `battery_divider_x100` to your actual ratio: measure the real resistors
|
||||
// rather than trusting their printed value, then trim with
|
||||
// `battery_offset_mv` against a multimeter. The ESP32 ADC is not linear and
|
||||
// `analogReadMilliVolts()` only corrects for the part of that Espressif
|
||||
// characterised at the factory.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
struct BatteryReading {
|
||||
bool valid; // false when no divider is configured or the read failed
|
||||
uint16_t mv; // battery terminal voltage in millivolts
|
||||
uint8_t pct; // 0..100, 0 when chemistry is BATT_NONE
|
||||
uint16_t raw_mv; // at the pin, before the divider ratio is applied
|
||||
};
|
||||
|
||||
void batteryBegin();
|
||||
|
||||
// Averaged, calibrated read. Powers the divider for the measurement if
|
||||
// PIN_BATTERY_EN is wired, then turns it off again.
|
||||
BatteryReading batteryRead();
|
||||
|
||||
// Last reading without touching the ADC. Cheap; use this in status payloads
|
||||
// that are built more often than the voltage can meaningfully change.
|
||||
BatteryReading batteryLast();
|
||||
|
||||
// Refresh the cached reading. Called on a timer from the main loop.
|
||||
void batteryPoll();
|
||||
|
||||
// SPEC C6 gate, registered with otaSetBatteryCheck().
|
||||
bool batteryAboveOtaThreshold(uint8_t min_pct);
|
||||
@@ -0,0 +1,131 @@
|
||||
// board_pins.h — single place where physical wiring is declared.
|
||||
//
|
||||
// Hardware is not in hand yet, so every free-pin assignment here is a default
|
||||
// that can be overridden with a -D build flag without touching source. The
|
||||
// camera pins are fixed by the XIAO ESP32S3 Sense expansion board and are not
|
||||
// overridable; they are listed so the wiring is documented in one place.
|
||||
#pragma once
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// XIAO ESP32S3 Sense — OV2640 on the expansion board. Fixed by the PCB.
|
||||
// ---------------------------------------------------------------------------
|
||||
#define CAM_PIN_PWDN -1
|
||||
#define CAM_PIN_RESET -1
|
||||
#define CAM_PIN_XCLK 10
|
||||
#define CAM_PIN_SIOD 40 // SCCB SDA
|
||||
#define CAM_PIN_SIOC 39 // SCCB SCL
|
||||
#define CAM_PIN_D7 48
|
||||
#define CAM_PIN_D6 11
|
||||
#define CAM_PIN_D5 12
|
||||
#define CAM_PIN_D4 14
|
||||
#define CAM_PIN_D3 16
|
||||
#define CAM_PIN_D2 18
|
||||
#define CAM_PIN_D1 17
|
||||
#define CAM_PIN_D0 15
|
||||
#define CAM_PIN_VSYNC 38
|
||||
#define CAM_PIN_HREF 47
|
||||
#define CAM_PIN_PCLK 13
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// HLK-LD2410 24 GHz radar
|
||||
//
|
||||
// Wiring (module -> XIAO):
|
||||
// VCC -> 5V (plain LD2410, no Bluetooth)
|
||||
// GND -> GND
|
||||
// TX -> D1 / GPIO2 (ESP RX)
|
||||
// RX -> D0 / GPIO1 (ESP TX)
|
||||
// OUT -> D2 / GPIO3 (presence, active HIGH; RTC-capable so it can also
|
||||
// serve as a deep-sleep wake source later)
|
||||
//
|
||||
// MEASURE THE LOGIC LEVELS BEFORE CONNECTING. The LD2410's logic is supposed
|
||||
// to be 3.3 V even when VCC is 5 V (it regulates internally), but this varies
|
||||
// between batches and clones, and the ESP32-S3 is not 5 V tolerant. A 5 V OUT
|
||||
// into GPIO3 damages the pin, and on a camera you cannot physically reach
|
||||
// that is an expensive way to find out.
|
||||
//
|
||||
// Two minutes with a multimeter on OUT and TX (wave a hand in front of the
|
||||
// module so OUT asserts) settles it. If either reads ~5 V, drop it with a
|
||||
// divider -- 10k from the module into the GPIO, 20k from the GPIO to GND
|
||||
// gives 3.3 V from 5 V. The ESP's TX into the module's RX needs nothing:
|
||||
// 3.3 V comfortably clears the module's input threshold.
|
||||
//
|
||||
// Baud rate is autodetected (see radarBegin), so a module at the factory
|
||||
// 256000 and one reconfigured to 115200 both just work, and a factory reset
|
||||
// does not take the trigger offline.
|
||||
//
|
||||
// Deliberately NOT on D6/D7 (GPIO43/44): those are UART0, which the ROM
|
||||
// bootloader spews boot logs onto at every reset. Harmless for the radar, but
|
||||
// it costs you the one easy hardware debug port. Keep 43/44 free.
|
||||
// ---------------------------------------------------------------------------
|
||||
#ifndef PIN_RADAR_TX
|
||||
#define PIN_RADAR_TX 1 // D0 — ESP transmits, goes to LD2410 RX
|
||||
#endif
|
||||
#ifndef PIN_RADAR_RX
|
||||
#define PIN_RADAR_RX 2 // D1 — ESP receives, comes from LD2410 TX
|
||||
#endif
|
||||
#ifndef PIN_RADAR_OUT
|
||||
#define PIN_RADAR_OUT 3 // D2 — presence output
|
||||
#endif
|
||||
#ifndef RADAR_UART_NUM
|
||||
#define RADAR_UART_NUM 1 // UART1 via the GPIO matrix
|
||||
#endif
|
||||
#ifndef RADAR_BAUD
|
||||
#define RADAR_BAUD 256000 // LD2410 factory default
|
||||
#endif
|
||||
|
||||
// Optional high-side MOSFET gating the radar's supply. -1 = permanently powered.
|
||||
// Only worth wiring if you run deep sleep with sleep_wake_on_radar = false:
|
||||
// the LD2410 draws ~80 mA continuously, which dwarfs anything the ESP saves by
|
||||
// sleeping. See the note at the top of power_mgr.h.
|
||||
#ifndef PIN_RADAR_EN
|
||||
#define PIN_RADAR_EN -1
|
||||
#endif
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spare I/O — reserved, nothing wired yet.
|
||||
// ---------------------------------------------------------------------------
|
||||
#ifndef PIN_AUX_ADC
|
||||
#define PIN_AUX_ADC 4 // D3 / A3 — spare ADC, or a PIR fallback
|
||||
#endif
|
||||
#ifndef PIN_I2C_SDA
|
||||
#define PIN_I2C_SDA 5 // D4 — future BME280 / DS3231
|
||||
#endif
|
||||
#ifndef PIN_I2C_SCL
|
||||
#define PIN_I2C_SCL 6 // D5
|
||||
#endif
|
||||
|
||||
// Battery / supply sensing. Defaults to the spare ADC pin above. The XIAO
|
||||
// does not expose its battery rail on a readable pin, so this needs an
|
||||
// external divider — see the wiring diagram at the top of battery.h.
|
||||
// Set to -1 to disable; voltage then reports as invalid rather than as zero.
|
||||
#ifndef PIN_BATTERY_ADC
|
||||
#define PIN_BATTERY_ADC PIN_AUX_ADC
|
||||
#endif
|
||||
|
||||
// Optional MOSFET on the divider's low side, so it only draws current during
|
||||
// a measurement (SPEC §9). -1 = divider permanently connected.
|
||||
#ifndef PIN_BATTERY_EN
|
||||
#define PIN_BATTERY_EN -1
|
||||
#endif
|
||||
|
||||
// Nightlight / illuminator, PWM driven. -1 = not fitted.
|
||||
// Drive a MOSFET or a constant-current module, never the LED directly: an
|
||||
// ESP32 pin is good for ~20 mA short-term and an illuminator worth having
|
||||
// draws far more. Read the warning at the top of nightlight.h before choosing
|
||||
// between IR and white.
|
||||
#ifndef PIN_NIGHTLIGHT
|
||||
#define PIN_NIGHTLIGHT -1
|
||||
#endif
|
||||
|
||||
// D8/D9/D10 (GPIO7/8/9) are the Sense board's microSD (SD_MMC 1-bit:
|
||||
// CLK=7, D0=8, CMD=9). Leave them alone if you ever want local buffering.
|
||||
|
||||
// Onboard user LED. Active LOW on the XIAO ESP32S3.
|
||||
// NOTE: verify against your board revision before trusting it — Seeed has
|
||||
// moved this pin between revisions.
|
||||
#ifndef PIN_STATUS_LED
|
||||
#define PIN_STATUS_LED 21
|
||||
#endif
|
||||
#ifndef STATUS_LED_ACTIVE_LOW
|
||||
#define STATUS_LED_ACTIVE_LOW 1
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
// camera_mgr.h — OV2640 lifecycle.
|
||||
//
|
||||
// Unlike the battery design in SPEC §4.3, the camera stays initialised for the
|
||||
// life of the boot. That removes the 300-600 ms sensor init and auto-exposure
|
||||
// settle from the trigger path entirely (SPEC C4) and is what makes the
|
||||
// pre-trigger ring possible.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <esp_camera.h>
|
||||
|
||||
bool cameraBegin();
|
||||
void cameraEnd();
|
||||
bool cameraRestart(); // after a frame_size change
|
||||
|
||||
// Push the current g_cfg (quality, flip, mirror) plus the active tuning
|
||||
// profile onto a running sensor. Frame size is deliberately excluded — see
|
||||
// configNeedsCameraRestart().
|
||||
void cameraApplyConfig();
|
||||
|
||||
// Apply the day or night tuning profile. Called on dusk/dawn transitions and
|
||||
// whenever the endpoint pushes new tuning.
|
||||
void cameraApplyTuning(bool night);
|
||||
|
||||
// Which profile is currently loaded.
|
||||
bool cameraNightProfileActive();
|
||||
|
||||
// --- frame sizes ------------------------------------------------------------
|
||||
// Resolutions are configured BY NAME ("SVGA", "UXGA"), not by the numeric
|
||||
// framesize_t index, and these two functions are the only place the mapping
|
||||
// lives. The reason is not cosmetic: esp32-camera has inserted entries into
|
||||
// framesize_t between releases — FRAMESIZE_128X128 and FRAMESIZE_320X320 were
|
||||
// added mid-enum — so a hardcoded index silently means a different resolution
|
||||
// after a driver update. The tables below are built from the enum symbols, so
|
||||
// they stay correct by construction.
|
||||
//
|
||||
// Numeric values are still accepted from the endpoint for compatibility, but
|
||||
// names are what the settings UI should send.
|
||||
uint8_t framesizeFromName(const char* name, uint8_t fallback);
|
||||
const char* framesizeName(uint8_t fs);
|
||||
void framesizeDims(uint8_t fs, uint16_t* w, uint16_t* h);
|
||||
|
||||
// Temporarily switch resolution for a streaming session, then put it back.
|
||||
bool cameraSetFrameSize(uint8_t framesize);
|
||||
|
||||
// Grab one JPEG. Returns nullptr on failure. Caller must esp_camera_fb_return().
|
||||
camera_fb_t* cameraGrab();
|
||||
|
||||
// Throw away the first frames after init so auto-exposure has settled before
|
||||
// anything is uploaded (SPEC C4).
|
||||
void cameraDiscardFrames(uint8_t n);
|
||||
|
||||
bool cameraReady();
|
||||
@@ -0,0 +1,22 @@
|
||||
// commands.h — the WebUI -> device channel (SPEC C1).
|
||||
//
|
||||
// The device is never contacted directly. The WebUI writes a row into
|
||||
// `device_commands`; the endpoint attaches pending rows to the next
|
||||
// ingest/heartbeat response; this module executes them and acks.
|
||||
//
|
||||
// Deferred execution: some commands must not run inside the HTTP response
|
||||
// callback (OTA reboots, streaming blocks for a minute). Those are queued and
|
||||
// run from the main loop, which is also where sleep decisions are made.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
// Pass this to apiIngest/apiHeartbeat. Parses and either executes immediately
|
||||
// or defers. Cheap commands ack from here; deferred ones ack on completion.
|
||||
void commandOnReceived(JsonObjectConst cmd);
|
||||
|
||||
// Run anything that was deferred. Call once per main-loop tick.
|
||||
void commandRunDeferred();
|
||||
|
||||
bool commandHasPending();
|
||||
@@ -0,0 +1,42 @@
|
||||
// device_stats.h — the counters reported in the conditions payload.
|
||||
//
|
||||
// Kept in RTC slow memory, so they survive deep sleep. They do NOT survive a
|
||||
// power cycle, which is deliberate: the endpoint already has the authoritative
|
||||
// count of what arrived, and a device-side counter that claimed to be durable
|
||||
// would just be a second source of truth to disagree with the first. Treat
|
||||
// these as "what this device believes it did today" and reconcile against the
|
||||
// database, not the other way round.
|
||||
//
|
||||
// "Today" is local-midnight to local-midnight, using the TZ pushed from the
|
||||
// endpoint. Rollover needs a synced clock; before the first sync the counters
|
||||
// accumulate under day 0 and roll over once when time arrives.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
struct DeviceStats {
|
||||
uint16_t captured_today; // frames handed to the uploader
|
||||
uint16_t delivered_today; // frames the endpoint accepted (2xx)
|
||||
uint16_t failed_today; // upload attempts that did not get a 2xx
|
||||
uint16_t events_today; // trigger events, not frames
|
||||
uint32_t day_index; // days since epoch, local — the rollover key
|
||||
|
||||
uint16_t captured_boot; // since this boot, for spotting a reset
|
||||
uint16_t delivered_boot;
|
||||
};
|
||||
|
||||
void statsBegin();
|
||||
|
||||
// Roll the daily counters over if the local date has changed. Cheap; call
|
||||
// from the main loop and before building any status payload.
|
||||
void statsRollover();
|
||||
|
||||
void statsCountEvent();
|
||||
void statsCountCaptured(uint16_t frames);
|
||||
void statsCountDelivered(uint16_t frames);
|
||||
void statsCountFailed(uint16_t frames);
|
||||
|
||||
DeviceStats statsGet();
|
||||
|
||||
// Ticks since the device last woke, in ms — "ticks since last sleep".
|
||||
uint32_t statsAwakeMs();
|
||||
@@ -0,0 +1,52 @@
|
||||
// frame_ring.h — pre-trigger history in PSRAM.
|
||||
//
|
||||
// THE POINT OF THIS FILE
|
||||
// SPEC C4 says the first usable frame lands 1-3 s after the bird arrives, by
|
||||
// which time a small bird is gone. That is only true if capture *starts* at the
|
||||
// trigger. With mains power we can instead capture continuously into a ring and,
|
||||
// on a trigger, ship the frames from *before* it. Effective latency goes
|
||||
// negative and C4 stops being a problem.
|
||||
//
|
||||
// Cost: ring_frames * ~45 KB of the 8 MB PSRAM. At depth 24 that is ~1 MB for
|
||||
// roughly 10 s of history at the default 400 ms cadence.
|
||||
//
|
||||
// Ownership: the ring owns its buffers and recycles them in place. Anything
|
||||
// handed to the uploader is a *copy*, so a slow network cannot stall capture
|
||||
// and there is no refcounting to get wrong.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
struct RingFrame {
|
||||
uint8_t* data; // PSRAM, owned by the ring
|
||||
size_t len;
|
||||
size_t cap; // allocated size, >= len
|
||||
uint32_t seq; // monotonic, 0 = never filled
|
||||
uint32_t at_ms; // millis() at capture
|
||||
int64_t at_epoch; // wall-clock ms, 0 if time not yet synced
|
||||
};
|
||||
|
||||
// A frame copied out for upload. Caller owns `data` and must free() it.
|
||||
struct FrameCopy {
|
||||
uint8_t* data;
|
||||
size_t len;
|
||||
uint32_t seq;
|
||||
uint32_t at_ms;
|
||||
int64_t at_epoch;
|
||||
};
|
||||
|
||||
bool ringBegin(uint8_t depth);
|
||||
void ringEnd();
|
||||
|
||||
// Store a frame. Copies into the ring's own PSRAM buffer, growing it if the
|
||||
// JPEG is larger than the slot currently holds.
|
||||
bool ringPush(const uint8_t* data, size_t len, int64_t epoch_ms);
|
||||
|
||||
// Copy out the newest `n` frames, oldest first. Returns how many were written
|
||||
// into `out` (may be fewer than n if the ring has not filled yet).
|
||||
// Every returned FrameCopy.data must be free()d by the caller.
|
||||
size_t ringTakeNewest(size_t n, FrameCopy* out, size_t out_cap);
|
||||
|
||||
uint32_t ringSeq(); // sequence of the most recent frame
|
||||
size_t ringCount(); // frames currently held
|
||||
size_t ringBytesUsed();
|
||||
@@ -0,0 +1,84 @@
|
||||
// ld2410.h — HLK-LD2410 24 GHz presence radar.
|
||||
//
|
||||
// The module streams a report frame a few times a second on UART (256000 8N1 by
|
||||
// factory default) and simultaneously drives an active-high OUT pin. We use
|
||||
// both: the pin is a zero-latency "something is there", the UART report carries
|
||||
// the distance and energy needed to reject swaying branches and passing people.
|
||||
//
|
||||
// Frame formats (HLK datasheet):
|
||||
// report F4 F3 F2 F1 | len(2,LE) | payload | F8 F7 F6 F5
|
||||
// command FD FC FB FA | len(2,LE) | payload | 04 03 02 01
|
||||
//
|
||||
// Basic report payload (type 0x02):
|
||||
// [0] 0x02 type [1] 0xAA head
|
||||
// [2] target state: 0=none 1=moving 2=stationary 3=both
|
||||
// [3..4] moving distance cm (LE) [5] moving energy 0..100
|
||||
// [6..7] stationary distance cm (LE) [8] stationary energy 0..100
|
||||
// [9..10] detection distance cm (LE)
|
||||
// [11] 0x55 tail [12] 0x00 check
|
||||
//
|
||||
// These offsets are transcribed from the datasheet, not verified against real
|
||||
// hardware. Run `radarSelfTest()` once the module is wired and check the log
|
||||
// before trusting the parsed values.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
enum RadarTarget : uint8_t {
|
||||
TARGET_NONE = 0,
|
||||
TARGET_MOVING = 1,
|
||||
TARGET_STATIONARY = 2,
|
||||
TARGET_BOTH = 3,
|
||||
};
|
||||
|
||||
struct RadarReading {
|
||||
bool valid; // a well-formed frame was decoded
|
||||
uint8_t target; // RadarTarget
|
||||
uint16_t moving_cm;
|
||||
uint8_t moving_energy; // 0..100
|
||||
uint16_t stationary_cm;
|
||||
uint8_t stationary_energy; // 0..100
|
||||
uint16_t detect_cm;
|
||||
bool out_pin; // raw presence pin, independent of UART
|
||||
uint32_t at_ms; // millis() when decoded
|
||||
};
|
||||
|
||||
// Bring up UART1 on the configured pins and set the OUT pin as an input.
|
||||
//
|
||||
// Probes for the module's baud rate rather than assuming one: the LD2410
|
||||
// ships at 256000 and can be reconfigured to 115200 and others, and a factory
|
||||
// reset puts it back. Autodetecting means neither event takes the trigger
|
||||
// offline on a device you cannot physically reach. Pin it with
|
||||
// `g_cfg.radar_baud` to skip the probe.
|
||||
//
|
||||
// Returns false if no baud produced a valid frame. That is not fatal — the
|
||||
// OUT pin path (radar_mode = RADAR_OUT_PIN_ONLY) needs no UART at all.
|
||||
bool radarBegin();
|
||||
|
||||
// The baud actually in use, or 0 if nothing was decoded.
|
||||
uint32_t radarBaud();
|
||||
|
||||
// Pump the UART. Call often (the radar task does, every few ms). Returns true
|
||||
// when a new report frame was decoded since the last call.
|
||||
bool radarPoll();
|
||||
|
||||
// Most recent decoded report, plus a live read of the OUT pin.
|
||||
RadarReading radarLast();
|
||||
|
||||
// Apply the configured distance window, energy floor and stationary policy.
|
||||
// This is the single place that decides "is this worth waking the camera for",
|
||||
// so tuning it in the field is one config push, not a firmware change.
|
||||
bool radarIsTrigger(const RadarReading& r);
|
||||
|
||||
// Log raw bytes for a few seconds so you can confirm baud rate and framing
|
||||
// when the hardware arrives. Blocking; bring-up only.
|
||||
void radarSelfTest(uint32_t duration_ms = 5000);
|
||||
|
||||
// Enter/leave the module's configuration mode. Needed before any parameter
|
||||
// write; the module stops reporting while in config mode.
|
||||
bool radarEnterConfig();
|
||||
bool radarExitConfig();
|
||||
|
||||
// Per-gate sensitivity. gate 0..8 (~0.75 m each), values 0..100.
|
||||
// Only call between radarEnterConfig()/radarExitConfig().
|
||||
bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary);
|
||||
@@ -0,0 +1,40 @@
|
||||
// net_mgr.h — WiFi association and clock.
|
||||
//
|
||||
// TIME (SPEC C7, and "timeserver is on endpoint")
|
||||
// Two sources, in order of preference:
|
||||
// 1. SNTP against the Pi. Cheap, standard, works before any HTTP call.
|
||||
// 2. The `server_time` field every ingest/heartbeat response carries. This
|
||||
// is the fallback that matters: if SNTP is blocked or the Pi is not
|
||||
// running an NTP daemon after all, the device still converges on the
|
||||
// endpoint's clock without extra configuration.
|
||||
// Either way `received_at` on the Pi stays authoritative for ordering. The
|
||||
// device timestamp is a hint, and it is explicitly 0 when unsynced rather than
|
||||
// silently 1970.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
bool netBegin();
|
||||
|
||||
// Associate, with bounded retries and backoff. SPEC §4.3: never loop forever
|
||||
// on a WiFi outage. Returns false after `max_attempts` failures; the caller
|
||||
// decides whether that means sleep or retry later.
|
||||
bool netConnect(uint8_t max_attempts = 3);
|
||||
|
||||
bool netIsConnected();
|
||||
void netDisconnect();
|
||||
|
||||
// Start SNTP against ntp_host (or api_host if unset) and wait up to
|
||||
// `timeout_ms` for the first sync.
|
||||
bool netSyncTime(uint32_t timeout_ms = 5000);
|
||||
|
||||
// Accept the endpoint's clock from a response envelope. Only steps the RTC if
|
||||
// we are unsynced or off by more than 2 s, so normal jitter does not cause a
|
||||
// timestamp discontinuity mid-burst.
|
||||
void netAdoptServerTime(int64_t server_ms);
|
||||
|
||||
bool netTimeValid();
|
||||
int64_t netEpochMs(); // 0 when not yet synced — never a fake 1970 value
|
||||
|
||||
// "2026-09-20T14:31:07Z" into `out`. Empty string when unsynced.
|
||||
void netIsoTime(char* out, size_t cap);
|
||||
@@ -0,0 +1,54 @@
|
||||
// nightlight.h — illuminator control and what the device does after dark.
|
||||
//
|
||||
// A HARDWARE WARNING WORTH READING BEFORE YOU BUY ANYTHING
|
||||
// The obvious choice for a wildlife camera is an infrared illuminator (850 nm
|
||||
// or 940 nm), because birds barely perceive it and white light at a feeder at
|
||||
// night is disruptive. But the OV2640 module on the XIAO Sense ships with an
|
||||
// **IR cut filter bonded over the sensor**, which blocks exactly those
|
||||
// wavelengths. An IR LED on an unmodified Sense produces a black frame.
|
||||
//
|
||||
// So, three options, in the order I would try them:
|
||||
// 1. Accept no night capture. Set night_behaviour = NIGHT_SLEEP. Most garden
|
||||
// birds are diurnal; you lose very little and save the whole problem.
|
||||
// 2. Warm, dim, continuous white light (NIGHTLIGHT_ALWAYS at low duty).
|
||||
// Continuous is markedly better than a flash per burst: animals habituate
|
||||
// to steady light and startle at sudden light. Still disturbs wildlife.
|
||||
// 3. Remove the IR filter and use 850 nm. Best images, irreversible, and it
|
||||
// wrecks daytime colour rendition unless you fit a switchable filter.
|
||||
//
|
||||
// The firmware supports all three. Option 2 is what NIGHTLIGHT_ON_BURST and
|
||||
// NIGHTLIGHT_ALWAYS drive; option 3 needs no code change at all.
|
||||
//
|
||||
// NIGHT WINDOW
|
||||
// `night_start_min` / `night_end_min` are minutes from local midnight. The Pi
|
||||
// knows the site latitude, so the intended use is for it to push real
|
||||
// sunset/sunrise daily via apply_config. The defaults (21:00-06:00) are a
|
||||
// fallback for before that exists.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
void nightBegin();
|
||||
|
||||
// Is the current local time inside the configured night window?
|
||||
// Always false while the clock is unsynced — better to capture pointless dark
|
||||
// frames than to sleep through a day because the device thinks it is 03:00.
|
||||
bool nightIsNight();
|
||||
|
||||
// Call every loop tick. Handles dusk/dawn transitions: swaps the camera
|
||||
// profile, and drives the illuminator for NIGHTLIGHT_ALWAYS.
|
||||
void nightTick();
|
||||
|
||||
// Bracket a capture burst. No-ops unless mode is NIGHTLIGHT_ON_BURST and it
|
||||
// is actually night; includes the settle delay the sensor needs to adapt.
|
||||
void nightIlluminateBurstBegin();
|
||||
void nightIlluminateBurstEnd();
|
||||
|
||||
bool nightlightIsOn();
|
||||
|
||||
// Seconds until night_end_min, for NIGHT_SLEEP. 0 if it is not night.
|
||||
uint32_t nightSecondsUntilMorning();
|
||||
|
||||
// Should the capture pipeline be running right now? False at night under
|
||||
// NIGHT_IDLE and NIGHT_SLEEP.
|
||||
bool nightCaptureAllowed();
|
||||
@@ -0,0 +1,53 @@
|
||||
// ota_mgr.h — OTA with SHA-256 verification and trial-boot rollback (SPEC C6).
|
||||
//
|
||||
// The rules from the spec, implemented here:
|
||||
// - dual OTA slots exist from the first flash (partitions CSV)
|
||||
// - verify SHA-256 of the downloaded image before activating the slot
|
||||
// - boot the new image ONCE in a trial state
|
||||
// - if the trial image cannot check in with the endpoint, roll back
|
||||
// automatically on the next reset
|
||||
// - never sleep mid-flash (INHIBIT_OTA)
|
||||
//
|
||||
// The battery gate from SPEC C6 is kept as a hook (`otaBatteryOkFn`) but has
|
||||
// no default sensor: this build is mains-powered and the XIAO's battery-sense
|
||||
// divider is not wired. Register a callback if that changes.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
struct OtaTarget {
|
||||
char version[24];
|
||||
char url[160]; // absolute, or a path relative to the API base
|
||||
char sha256[65]; // lowercase hex
|
||||
uint32_t size;
|
||||
};
|
||||
|
||||
void otaBegin();
|
||||
|
||||
// True when this boot is the first run of a freshly flashed image and has not
|
||||
// yet been confirmed. Until otaMarkValid() is called, a reset rolls back.
|
||||
bool otaPendingVerify();
|
||||
|
||||
// Call once the device has proven the new image works — we use "a heartbeat
|
||||
// was accepted by the endpoint", which exercises WiFi, HTTP, auth and config
|
||||
// in one go. Anything less and a firmware that boots but cannot talk would be
|
||||
// marked good.
|
||||
void otaMarkValid();
|
||||
|
||||
// Give up on the trial image and reboot into the previous slot.
|
||||
void otaRollback(const char* reason);
|
||||
|
||||
// Is `target.version` different from what we are running?
|
||||
bool otaIsNewer(const OtaTarget& target);
|
||||
|
||||
// Download, verify, activate, reboot. Blocks for the duration. Returns only on
|
||||
// failure — on success the device restarts into the new slot.
|
||||
// Holds INHIBIT_OTA for the whole operation.
|
||||
bool otaApply(const OtaTarget& target);
|
||||
|
||||
// Optional battery gate (SPEC C6: refuse to flash below a threshold).
|
||||
typedef bool (*OtaBatteryOkFn)(uint8_t min_pct);
|
||||
void otaSetBatteryCheck(OtaBatteryOkFn fn, uint8_t min_pct);
|
||||
|
||||
const char* otaRunningVersion();
|
||||
const char* otaRunningPartition();
|
||||
@@ -0,0 +1,125 @@
|
||||
// power_mgr.h — the deep-sleep on/off switch and everything it interferes with.
|
||||
//
|
||||
// TWO MODES, ONE FLAG (`g_cfg.deep_sleep_enabled`, pushable from the WebUI)
|
||||
//
|
||||
// AWAKE (default, mains powered)
|
||||
// Camera stays initialised, the PSRAM ring holds ~10 s of pre-trigger
|
||||
// history, commands execute within a loop tick, streaming works on demand.
|
||||
// This is the mode that makes good bird photos.
|
||||
//
|
||||
// SLEEP (battery / solar)
|
||||
// Wake on the LD2410 OUT pin (EXT1) or the timer, capture a post-trigger
|
||||
// burst, upload, drain the command queue, sleep again.
|
||||
// You give up, unavoidably:
|
||||
// - the pre-trigger ring: the camera is off, so there is no history.
|
||||
// Back to SPEC C4's 1-3 s latency; expect to miss fast arrivals.
|
||||
// - on-demand streaming: a stream_start command is only seen at the next
|
||||
// wake. The device then holds itself awake for the session and sleeps
|
||||
// after (see powerInhibit below).
|
||||
// - command latency: worst case equals deep_sleep_s (SPEC C1).
|
||||
//
|
||||
// HONEST NOTE ON WHAT DEEP SLEEP ACTUALLY SAVES HERE
|
||||
// The XIAO ESP32S3 sleeps at tens of µA, but the LD2410 draws roughly 80 mA
|
||||
// continuously and must stay powered to act as a wake source. So with
|
||||
// sleep_wake_on_radar = true, system current is dominated by the radar and the
|
||||
// ESP sleeping buys you very little. Deep sleep is only a real power win if you
|
||||
// either (a) set sleep_wake_on_radar = false and wake on the timer alone, with
|
||||
// the radar power-gated via PIN_RADAR_EN, or (b) fit a low-quiescent PIR such
|
||||
// as the AM312 on PIN_AUX_ADC as the wake source and use the radar only for
|
||||
// confirmation once awake. The switch is implemented either way; this is a
|
||||
// wiring decision, not a firmware one.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
enum WakeCause : uint8_t {
|
||||
WAKE_POWER_ON = 0, // cold boot, or reset
|
||||
WAKE_RADAR = 1, // EXT1 on the LD2410 OUT pin
|
||||
WAKE_TIMER = 2,
|
||||
WAKE_OTHER = 3,
|
||||
};
|
||||
|
||||
// Reasons the device must not sleep right now. Refcounted, so nested holders
|
||||
// (a stream inside a wake_and_hold, say) cannot cut each other short.
|
||||
enum SleepInhibit : uint8_t {
|
||||
INHIBIT_BOOT = 0, // released once the first heartbeat succeeds
|
||||
INHIBIT_UPLOAD = 1,
|
||||
INHIBIT_STREAM = 2, // the "stream interferes with sleep" case
|
||||
INHIBIT_OTA = 3, // sleeping mid-flash bricks the device (SPEC C6)
|
||||
INHIBIT_HOLD = 4, // wake_and_hold command
|
||||
INHIBIT_COUNT
|
||||
};
|
||||
|
||||
// Reads the wake cause and restores the counters kept in RTC memory.
|
||||
// Call first in setup(), before anything else looks at boot state.
|
||||
void powerBegin();
|
||||
|
||||
WakeCause powerWakeCause();
|
||||
const char* powerWakeCauseName();
|
||||
uint32_t powerBootCount(); // survives deep sleep, resets on power loss
|
||||
uint32_t powerLastSleepSeconds(); // how long the most recent sleep lasted
|
||||
uint32_t powerTotalSleepSeconds(); // cumulative since power-on
|
||||
|
||||
// Is sleeping permitted at all right now, ignoring the idle timer?
|
||||
//
|
||||
// This is where streaming and sleeping are reconciled. A sleeping device
|
||||
// cannot be told to start a stream (SPEC C1), so with `stream_blocks_sleep`
|
||||
// set — the default — merely *enabling* streaming keeps the device awake and
|
||||
// reachable, whether or not a session is running. Clear that flag to let it
|
||||
// sleep anyway and accept that `stream_start` waits for the next wake.
|
||||
//
|
||||
// Returns false, with a reason, when: deep sleep is switched off, streaming
|
||||
// is enabled and blocks sleep, or an inhibit is held.
|
||||
bool powerSleepAllowed();
|
||||
const char* powerSleepBlockedReason();
|
||||
|
||||
// Sleep inhibits. Always pair them; prefer the RAII guard below.
|
||||
void powerInhibit(SleepInhibit reason);
|
||||
void powerRelease(SleepInhibit reason);
|
||||
bool powerIsInhibited();
|
||||
const char* powerInhibitSummary(); // for logs and heartbeats
|
||||
|
||||
struct SleepGuard {
|
||||
SleepInhibit r;
|
||||
explicit SleepGuard(SleepInhibit reason) : r(reason) { powerInhibit(r); }
|
||||
~SleepGuard() { powerRelease(r); }
|
||||
};
|
||||
|
||||
// Mark that something worth staying awake for just happened. Resets the idle
|
||||
// timer, so a busy feeder keeps the device up instead of thrashing sleep/wake.
|
||||
void powerNoteActivity();
|
||||
|
||||
// Hold awake for at least `seconds` (the wake_and_hold command).
|
||||
void powerHoldAwake(uint32_t seconds);
|
||||
|
||||
// Would the next powerMaybeSleep() actually sleep? Lets the caller do the
|
||||
// things that must happen before the radio goes off — a final status push,
|
||||
// say — without doing them on every loop tick.
|
||||
bool powerWouldSleepNow();
|
||||
|
||||
// Called every loop tick. Sleeps if, and only if:
|
||||
// deep_sleep_enabled && no inhibit && idle longer than sleep_idle_timeout_s
|
||||
// Returns false if it decided to stay awake; does not return if it slept.
|
||||
bool powerMaybeSleep();
|
||||
|
||||
// Sleep now regardless of the idle timer, but still never while inhibited.
|
||||
// `seconds` == 0 uses g_cfg.deep_sleep_s. Used by the `sleep_now` command and
|
||||
// by the "every failure path ends in sleep" rule of SPEC §4.3.
|
||||
void powerSleepNow(uint32_t seconds = 0);
|
||||
|
||||
// Sleep through the night (NIGHT_SLEEP). Unlike powerSleepNow() this works
|
||||
// even when deep_sleep_enabled is false, because "sleep at night" is a
|
||||
// separate decision from "sleep between events" — a mains-powered camera
|
||||
// still has no reason to be awake at 03:00 with no illuminator fitted.
|
||||
// Never wakes on the radar: the point is to ignore the night, not to
|
||||
// photograph every cat that walks past. No-op if it is not night.
|
||||
void powerSleepUntilMorning();
|
||||
|
||||
// True while the device is running in SLEEP mode. Other subsystems consult
|
||||
// this to decide whether the ring buffer is worth maintaining.
|
||||
bool powerSleepModeActive();
|
||||
|
||||
// Applies a change to deep_sleep_enabled that arrived from the endpoint.
|
||||
// Turning sleep ON never takes effect instantly: the device first finishes the
|
||||
// current wake so the ack for the config command still reaches the Pi.
|
||||
void powerOnConfigChanged(bool was_enabled);
|
||||
@@ -0,0 +1,40 @@
|
||||
// stream_session.h — time-boxed MJPEG push (SPEC C9).
|
||||
//
|
||||
// WHAT IS BUILT
|
||||
// The full path: a `stream_start` command opens a chunked POST to the Pi, the
|
||||
// device pushes JPEGs at the configured rate and resolution, and the session
|
||||
// ends itself at the duration cap. Mode (watch / record / both) rides in a
|
||||
// header; what the Pi does with the bytes is the Pi's decision, so the device
|
||||
// never needs to change when you add recording or a public relay.
|
||||
//
|
||||
// WHAT IS NOT BUILT
|
||||
// Anything outward-facing. Per SPEC C3 the ESP32 never serves a stream and is
|
||||
// never reachable from outside the LAN; relaying to a browser or to a public
|
||||
// domain is the Pi's job (MediaMTX, or plain MJPEG passthrough).
|
||||
//
|
||||
// INTERACTION WITH DEEP SLEEP
|
||||
// A session holds INHIBIT_STREAM, so the device cannot sleep underneath it.
|
||||
// In SLEEP mode a stream_start command is only seen at the next wake; the
|
||||
// device then serves the session and sleeps once it ends. That latency is
|
||||
// inherent (SPEC C1), not a gap in the implementation.
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
bool streamActive();
|
||||
|
||||
// Start a session. `session_id` comes from the endpoint so both sides agree on
|
||||
// a name for it. Overrides are optional: 0 means "use the configured value".
|
||||
bool streamStart(const char* session_id,
|
||||
uint8_t mode_override = 0xFF,
|
||||
uint8_t framesize_override = 0,
|
||||
uint16_t duration_override = 0);
|
||||
|
||||
// Pump one frame if it is time. Call from the main loop; cheap when idle.
|
||||
// Ends the session automatically at the duration cap.
|
||||
void streamTick();
|
||||
|
||||
void streamStop(const char* reason);
|
||||
|
||||
uint32_t streamFramesSent();
|
||||
uint32_t streamSecondsLeft();
|
||||
@@ -0,0 +1,13 @@
|
||||
# poorBird partition table — 8 MB flash, dual OTA slots + rollback (SPEC C6)
|
||||
#
|
||||
# Two app slots of 3.1 MB each. This MUST be right on the very first flash:
|
||||
# retrofitting OTA onto a device that is already mounted outdoors means taking
|
||||
# it down and reflashing over USB.
|
||||
#
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
nvs, data, nvs, 0x9000, 0x5000,
|
||||
otadata, data, ota, 0xE000, 0x2000,
|
||||
app0, app, ota_0, 0x10000, 0x330000,
|
||||
app1, app, ota_1, 0x340000, 0x330000,
|
||||
spiffs, data, spiffs, 0x670000, 0x180000,
|
||||
coredump, data, coredump, 0x7F0000, 0x10000,
|
||||
|
@@ -0,0 +1,78 @@
|
||||
; poorBird - ESP32-S3 camera node
|
||||
; Board: Seeed Studio XIAO ESP32S3 Sense (ESP32-S3R8, 8 MB flash, 8 MB PSRAM, OV2640)
|
||||
;
|
||||
; PLATFORM NOTE
|
||||
; The official `espressif32` platform in the PlatformIO registry lags well behind
|
||||
; Arduino-ESP32 3.x / ESP-IDF 5.x and has poor ESP32-S3 support. The community fork
|
||||
; `pioarduino` is what current S3 work uses.
|
||||
;
|
||||
; The pin below (53.03.13 = Arduino core 3.1.x / IDF 5.3) is chosen to match
|
||||
; PlatformIO Core 6.1.x. The `stable` release alias now requires Core >= 6.2.0;
|
||||
; if you upgrade Core, you can switch to:
|
||||
; https://github.com/pioarduino/platform-espressif32/releases/download/stable/platform-espressif32.zip
|
||||
|
||||
[platformio]
|
||||
default_envs = xiao_s3_sense
|
||||
|
||||
; ---------------------------------------------------------------------------
|
||||
; Everything you are likely to edit lives in [common]. Secrets belong in
|
||||
; secrets.ini (gitignored) - see secrets.ini.example.
|
||||
; ---------------------------------------------------------------------------
|
||||
[common]
|
||||
fw_version = 0.1.0
|
||||
|
||||
build_flags =
|
||||
-DFW_VERSION=\"${common.fw_version}\"
|
||||
-DHW_REVISION=\"xiao-esp32s3-sense-ld2410\"
|
||||
-DCORE_DEBUG_LEVEL=3
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
||||
-DARDUINO_USB_MODE=1
|
||||
-DBOARD_HAS_PSRAM
|
||||
; --- camera defaults (runtime-overridable from the endpoint) ----------
|
||||
; Use the enum SYMBOLS, never the numbers: esp32-camera has inserted
|
||||
; entries into framesize_t between releases, so a literal index silently
|
||||
; changes resolution after a driver update.
|
||||
-DCFG_FRAME_SIZE=FRAMESIZE_SVGA ; 800x600 stills
|
||||
-DCFG_STREAM_FRAME_SIZE=FRAMESIZE_VGA ; 640x480 while streaming
|
||||
-DCFG_JPEG_QUALITY=12 ; 4..40, lower = better = bigger
|
||||
; --- pre-trigger ring buffer (the reason mains power is worth it) -----
|
||||
-DCFG_RING_FRAMES=24 ; PSRAM history depth
|
||||
-DCFG_PRE_ROLL=4 ; frames sent from *before* the trigger
|
||||
-DCFG_POST_ROLL=6 ; frames sent after the trigger
|
||||
; --- ops --------------------------------------------------------------
|
||||
-DCFG_HEARTBEAT_S=300
|
||||
-DCFG_COOLDOWN_S=5
|
||||
|
||||
; ---------------------------------------------------------------------------
|
||||
[env:xiao_s3_sense]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.13/platform-espressif32.zip
|
||||
board = seeed_xiao_esp32s3
|
||||
framework = arduino
|
||||
|
||||
board_build.partitions = partitions/poorbird_8mb_ota.csv
|
||||
board_build.flash_mode = qio
|
||||
board_upload.flash_size = 8MB
|
||||
|
||||
; PSRAM is mandatory: the frame ring and the camera framebuffers both live there.
|
||||
board_build.arduino.memory_type = qio_opi
|
||||
|
||||
monitor_speed = 115200
|
||||
monitor_filters = esp32_exception_decoder, time
|
||||
|
||||
lib_deps =
|
||||
bblanchon/ArduinoJson @ ^7.2.0
|
||||
|
||||
build_flags =
|
||||
${common.build_flags}
|
||||
|
||||
extra_scripts = pre:scripts/load_secrets.py
|
||||
|
||||
; ---------------------------------------------------------------------------
|
||||
; Same firmware, verbose logging - for bring-up on the bench.
|
||||
[env:xiao_s3_sense_debug]
|
||||
extends = env:xiao_s3_sense
|
||||
build_type = debug
|
||||
build_flags =
|
||||
${common.build_flags}
|
||||
-DCORE_DEBUG_LEVEL=5
|
||||
-DPB_VERBOSE_RADAR=1
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Inject secrets.ini into the build as -D flags.
|
||||
|
||||
Keeps WiFi credentials and the enrollment secret out of git and out of
|
||||
platformio.ini. Copy secrets.ini.example to secrets.ini and fill it in; the
|
||||
build works without the file, it just produces an unconfigured device that
|
||||
cannot associate.
|
||||
"""
|
||||
|
||||
import configparser
|
||||
import os
|
||||
|
||||
Import("env") # noqa: F821 (provided by SCons/PlatformIO)
|
||||
|
||||
SECRETS = os.path.join(env.subst("$PROJECT_DIR"), "secrets.ini") # noqa: F821
|
||||
|
||||
# key in secrets.ini -> build flag. Strings are quoted, numbers are not.
|
||||
STRING_KEYS = {
|
||||
"wifi_ssid": "CFG_WIFI_SSID",
|
||||
"wifi_pass": "CFG_WIFI_PASS",
|
||||
"api_host": "CFG_API_HOST",
|
||||
"enroll_secret": "CFG_ENROLL_SECRET",
|
||||
"tz": "CFG_TZ",
|
||||
}
|
||||
NUMERIC_KEYS = {
|
||||
"api_port": "CFG_API_PORT",
|
||||
"deep_sleep": "CFG_DEEP_SLEEP",
|
||||
}
|
||||
|
||||
if not os.path.isfile(SECRETS):
|
||||
print("load_secrets: no secrets.ini found — building with defaults.")
|
||||
print(" copy secrets.ini.example to secrets.ini before flashing.")
|
||||
else:
|
||||
parser = configparser.ConfigParser()
|
||||
parser.read(SECRETS)
|
||||
if not parser.has_section("secrets"):
|
||||
raise SystemExit("load_secrets: secrets.ini has no [secrets] section")
|
||||
|
||||
flags = []
|
||||
for key, macro in STRING_KEYS.items():
|
||||
if parser.has_option("secrets", key):
|
||||
value = parser.get("secrets", key)
|
||||
flags.append(f'-D{macro}=\\"{value}\\"')
|
||||
for key, macro in NUMERIC_KEYS.items():
|
||||
if parser.has_option("secrets", key):
|
||||
flags.append(f"-D{macro}={parser.get('secrets', key)}")
|
||||
|
||||
env.Append(CPPDEFINES=[]) # noqa: F821
|
||||
env.Append(BUILD_FLAGS=flags) # noqa: F821
|
||||
|
||||
# Do not print the values themselves.
|
||||
print(f"load_secrets: applied {len(flags)} flag(s) from secrets.ini")
|
||||
@@ -0,0 +1,32 @@
|
||||
; Copy to secrets.ini (which is gitignored) and fill in.
|
||||
;
|
||||
; Only three of these really matter for a first flash: the WiFi credentials,
|
||||
; the Pi's address, and the enrollment secret. Everything else the device
|
||||
; learns from the endpoint after it enrolls.
|
||||
|
||||
[secrets]
|
||||
wifi_ssid = YourNetwork
|
||||
wifi_pass = YourPassword
|
||||
|
||||
; The endpoint — a Pi, a thin client, a NUC, a VM; the firmware does not care.
|
||||
; Use a DHCP reservation and hardcode the address: mDNS on an ESP32 is one
|
||||
; more thing that can fail silently at 4 a.m. (SPEC §9).
|
||||
api_host = 192.168.1.50
|
||||
api_port = 8080
|
||||
|
||||
; Bootstrap provisioning secret, shared with the endpoint. The device trades
|
||||
; it for a bearer token plus a per-device re-enrollment secret on first boot,
|
||||
; and keeps the latter so a token rotation heals itself without a USB cable.
|
||||
; Generate with: openssl rand -hex 32
|
||||
;
|
||||
; It stays compiled into the image as a last-resort recovery path, so do not
|
||||
; rotate it server-side without also shipping new firmware.
|
||||
enroll_secret = replace-me
|
||||
|
||||
; POSIX TZ. Central Europe with DST.
|
||||
tz = CET-1CEST,M3.5.0,M10.5.0/3
|
||||
|
||||
; 0 = stay awake (mains, pre-trigger ring, streaming works)
|
||||
; 1 = deep sleep between events (battery; see power_mgr.h for the trade-offs)
|
||||
; This is only the *initial* value — the endpoint can flip it at runtime.
|
||||
deep_sleep = 0
|
||||
@@ -0,0 +1,583 @@
|
||||
#include "api_client.h"
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <esp_http_client.h>
|
||||
|
||||
#include "app_config.h"
|
||||
#include "battery.h"
|
||||
#include "camera_mgr.h"
|
||||
#include "device_stats.h"
|
||||
#include "ld2410.h"
|
||||
#include "net_mgr.h"
|
||||
#include "nightlight.h"
|
||||
#include "power_mgr.h"
|
||||
#include "stream_session.h"
|
||||
|
||||
static bool s_token_rejected = false;
|
||||
static esp_http_client_handle_t s_stream = nullptr;
|
||||
|
||||
// One response buffer, reused. 4 KB comfortably holds an envelope with a
|
||||
// handful of queued commands; anything larger is a server-side bug.
|
||||
static const size_t kRespCap = 4096;
|
||||
static char s_resp[kRespCap];
|
||||
|
||||
void apiBegin() { s_token_rejected = false; }
|
||||
bool apiTokenRejected() { return s_token_rejected; }
|
||||
|
||||
static String url(const char* path) { return apiBaseUrl() + path; }
|
||||
|
||||
static void setAuth(esp_http_client_handle_t c) {
|
||||
char bearer[80];
|
||||
snprintf(bearer, sizeof(bearer), "Bearer %s", g_cfg.device_token);
|
||||
esp_http_client_set_header(c, "Authorization", bearer);
|
||||
}
|
||||
|
||||
// Headers present on every device request, so the Pi can spot a device that
|
||||
// is behind on config or firmware without the device having to ask.
|
||||
static void setCommonHeaders(esp_http_client_handle_t c) {
|
||||
char buf[24];
|
||||
esp_http_client_set_header(c, "X-Device-Uid", deviceUid());
|
||||
esp_http_client_set_header(c, "X-Fw-Version", FW_VERSION);
|
||||
esp_http_client_set_header(c, "X-Hw-Revision", HW_REVISION);
|
||||
snprintf(buf, sizeof(buf), "%u", (unsigned)g_cfg.config_version);
|
||||
esp_http_client_set_header(c, "X-Config-Version", buf);
|
||||
snprintf(buf, sizeof(buf), "%d", WiFi.RSSI());
|
||||
esp_http_client_set_header(c, "X-Rssi", buf);
|
||||
}
|
||||
|
||||
// Read the body into s_resp. Returns bytes read, or -1.
|
||||
static int readBody(esp_http_client_handle_t c) {
|
||||
int len = esp_http_client_read_response(c, s_resp, kRespCap - 1);
|
||||
if (len < 0) return -1;
|
||||
s_resp[len] = '\0';
|
||||
return len;
|
||||
}
|
||||
|
||||
// Shared response handling: pull the envelope fields out and fan the command
|
||||
// array out to the handler. Used identically by ingest and heartbeat, which is
|
||||
// the whole reason the two endpoints return the same shape (SPEC §4.1).
|
||||
static void parseEnvelope(ServerEnvelope& env, int body_len, CommandHandler on_cmd) {
|
||||
if (body_len <= 0) return;
|
||||
|
||||
JsonDocument doc;
|
||||
DeserializationError err = deserializeJson(doc, s_resp, body_len);
|
||||
if (err) {
|
||||
log_w("response is not JSON: %s", err.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
env.server_time_ms = doc["server_time"] | (int64_t)0;
|
||||
env.config_version = doc["config_version"] | (uint32_t)0;
|
||||
|
||||
JsonObjectConst fw = doc["firmware"];
|
||||
if (!fw.isNull() && fw["version"].is<const char*>()) {
|
||||
env.has_firmware = true;
|
||||
strncpy(env.fw_version, fw["version"] | "", sizeof(env.fw_version) - 1);
|
||||
strncpy(env.fw_url, fw["url"] | "", sizeof(env.fw_url) - 1);
|
||||
strncpy(env.fw_sha256, fw["sha256"] | "", sizeof(env.fw_sha256) - 1);
|
||||
env.fw_size = fw["size"] | (uint32_t)0;
|
||||
}
|
||||
|
||||
JsonArrayConst cmds = doc["commands"];
|
||||
if (!cmds.isNull()) {
|
||||
for (JsonObjectConst cmd : cmds) {
|
||||
env.command_count++;
|
||||
if (on_cmd) on_cmd(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Enrollment
|
||||
// ---------------------------------------------------------------------------
|
||||
// One enrollment attempt with a specific secret.
|
||||
static bool enrollWith(const char* secret, const char* which) {
|
||||
if (!secret || !secret[0]) return false;
|
||||
|
||||
JsonDocument body;
|
||||
body["device_uid"] = deviceUid();
|
||||
body["device_name"] = g_cfg.device_name;
|
||||
body["hw_revision"] = HW_REVISION;
|
||||
body["fw_version"] = FW_VERSION;
|
||||
body["mac"] = WiFi.macAddress();
|
||||
|
||||
String payload;
|
||||
serializeJson(body, payload);
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url("/enroll");
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_POST;
|
||||
cfg.timeout_ms = 8000;
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
||||
esp_http_client_set_header(c, "X-Enroll-Secret", secret);
|
||||
setCommonHeaders(c);
|
||||
|
||||
bool ok = false;
|
||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
||||
esp_http_client_fetch_headers(c);
|
||||
int status = esp_http_client_get_status_code(c);
|
||||
int len = readBody(c);
|
||||
|
||||
if (status == 200 || status == 201) {
|
||||
JsonDocument doc;
|
||||
if (!deserializeJson(doc, s_resp, len > 0 ? len : 0)) {
|
||||
const char* tok = doc["token"] | "";
|
||||
if (strlen(tok) > 0) {
|
||||
strncpy(g_cfg.device_token, tok, sizeof(g_cfg.device_token) - 1);
|
||||
g_cfg.device_token[sizeof(g_cfg.device_token) - 1] = '\0';
|
||||
|
||||
// Upgrade the shared bootstrap secret to a per-device one
|
||||
// if the endpoint offers it. That keeps re-enrollment
|
||||
// self-service without leaving a credential on the device
|
||||
// that could enroll *other* identities.
|
||||
const char* re = doc["reenroll_secret"] | "";
|
||||
if (strlen(re) > 0) {
|
||||
strncpy(g_cfg.enroll_secret, re, sizeof(g_cfg.enroll_secret) - 1);
|
||||
g_cfg.enroll_secret[sizeof(g_cfg.enroll_secret) - 1] = '\0';
|
||||
log_i("enrolled via %s: token + per-device re-enrollment secret stored", which);
|
||||
} else {
|
||||
// Endpoint does not implement it. Keep the secret we
|
||||
// used rather than wiping it — a device that cannot
|
||||
// re-enroll after a token rotation is a device that
|
||||
// needs a ladder.
|
||||
strncpy(g_cfg.enroll_secret, secret, sizeof(g_cfg.enroll_secret) - 1);
|
||||
g_cfg.enroll_secret[sizeof(g_cfg.enroll_secret) - 1] = '\0';
|
||||
log_i("enrolled via %s: token stored (endpoint sent no re-enrollment secret)", which);
|
||||
}
|
||||
|
||||
configSave();
|
||||
s_token_rejected = false;
|
||||
ok = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log_w("enroll via %s rejected: HTTP %d", which, status);
|
||||
}
|
||||
} else {
|
||||
log_e("enroll: cannot reach %s", u.c_str());
|
||||
}
|
||||
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool apiEnroll() {
|
||||
if (g_cfg.device_token[0]) return true;
|
||||
|
||||
// Stored secret first: after the first enrollment this is the per-device
|
||||
// one, so a token rotation in the admin UI heals itself on the next
|
||||
// request with no physical access.
|
||||
if (enrollWith(g_cfg.enroll_secret, "stored secret")) return true;
|
||||
|
||||
// Last resort: the shared bootstrap secret compiled into the image. This
|
||||
// is the escape hatch for a device whose stored secret has been
|
||||
// invalidated — rotating the shared secret server-side without also
|
||||
// reflashing is what would strand it, so don't do that.
|
||||
const char* boot = configBootstrapSecret();
|
||||
if (boot[0] && strcmp(boot, g_cfg.enroll_secret) != 0) {
|
||||
log_w("enroll: stored secret failed, trying the compiled-in bootstrap secret");
|
||||
if (enrollWith(boot, "bootstrap secret")) return true;
|
||||
}
|
||||
|
||||
if (!g_cfg.enroll_secret[0] && !boot[0]) {
|
||||
log_e("not enrolled and no secret available — set enroll_secret in secrets.ini");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ingest — raw JPEG body, metadata in headers
|
||||
// ---------------------------------------------------------------------------
|
||||
ServerEnvelope apiIngest(const FrameCopy& frame, const CaptureMeta& meta, CommandHandler on_cmd) {
|
||||
ServerEnvelope env = {};
|
||||
if (!frame.data || frame.len == 0) return env;
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url("/ingest");
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_POST;
|
||||
cfg.timeout_ms = 15000; // a 60 KB JPEG over marginal WiFi is not instant
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
esp_http_client_set_header(c, "Content-Type", "image/jpeg");
|
||||
setAuth(c);
|
||||
setCommonHeaders(c);
|
||||
|
||||
char b[32];
|
||||
esp_http_client_set_header(c, "X-Trigger", meta.trigger);
|
||||
esp_http_client_set_header(c, "X-Burst-Id", meta.burst_id);
|
||||
snprintf(b, sizeof(b), "%u", meta.burst_index); esp_http_client_set_header(c, "X-Burst-Index", b);
|
||||
snprintf(b, sizeof(b), "%u", meta.burst_count); esp_http_client_set_header(c, "X-Burst-Count", b);
|
||||
snprintf(b, sizeof(b), "%d", meta.pre_trigger); esp_http_client_set_header(c, "X-Pre-Trigger", b);
|
||||
snprintf(b, sizeof(b), "%lld", (long long)frame.at_epoch);
|
||||
esp_http_client_set_header(c, "X-Captured-At", b); // ms since epoch, UTC, 0 if unsynced
|
||||
snprintf(b, sizeof(b), "%u", (unsigned)frame.seq); esp_http_client_set_header(c, "X-Frame-Seq", b);
|
||||
snprintf(b, sizeof(b), "%u", meta.radar_distance_cm); esp_http_client_set_header(c, "X-Radar-Distance-Cm", b);
|
||||
snprintf(b, sizeof(b), "%u", meta.radar_energy); esp_http_client_set_header(c, "X-Radar-Energy", b);
|
||||
snprintf(b, sizeof(b), "%u", meta.radar_state); esp_http_client_set_header(c, "X-Radar-State", b);
|
||||
|
||||
if (esp_http_client_open(c, frame.len) == ESP_OK) {
|
||||
int written = esp_http_client_write(c, (const char*)frame.data, frame.len);
|
||||
if (written == (int)frame.len) {
|
||||
esp_http_client_fetch_headers(c);
|
||||
env.http_status = esp_http_client_get_status_code(c);
|
||||
int len = readBody(c);
|
||||
|
||||
if (env.http_status == 401) {
|
||||
s_token_rejected = true;
|
||||
log_w("ingest: 401, token rotated or revoked");
|
||||
} else if (env.http_status >= 200 && env.http_status < 300) {
|
||||
env.ok = true;
|
||||
parseEnvelope(env, len, on_cmd);
|
||||
} else {
|
||||
log_w("ingest: HTTP %d", env.http_status);
|
||||
}
|
||||
} else {
|
||||
log_w("ingest: short write %d of %u", written, (unsigned)frame.len);
|
||||
}
|
||||
} else {
|
||||
log_w("ingest: connect failed");
|
||||
}
|
||||
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
return env;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Device conditions
|
||||
//
|
||||
// One body, two endpoints: /heartbeat (returns the command envelope) and
|
||||
// /status (returns 204, no commands). Built in one place so the two can never
|
||||
// drift apart and the endpoint only has to parse one shape.
|
||||
// ---------------------------------------------------------------------------
|
||||
static void buildConditions(JsonDocument& body, const char* reason) {
|
||||
statsRollover();
|
||||
const DeviceStats st = statsGet();
|
||||
const BatteryReading bt = batteryLast();
|
||||
const RadarReading rd = radarLast();
|
||||
|
||||
body["reason"] = reason;
|
||||
body["fw_version"] = FW_VERSION;
|
||||
body["hw_revision"] = HW_REVISION;
|
||||
body["config_version"] = g_cfg.config_version;
|
||||
|
||||
// --- uptime and sleep ---------------------------------------------------
|
||||
JsonObject p = body["power"].to<JsonObject>();
|
||||
p["uptime_ms"] = (uint32_t)millis();
|
||||
p["awake_ms"] = statsAwakeMs(); // ticks since the last sleep
|
||||
p["boot_count"] = powerBootCount();
|
||||
p["wake_cause"] = powerWakeCauseName();
|
||||
p["last_sleep_s"] = powerLastSleepSeconds();
|
||||
p["total_sleep_s"] = powerTotalSleepSeconds();
|
||||
p["sleep_enabled"] = g_cfg.deep_sleep_enabled;
|
||||
p["sleep_allowed"] = powerSleepAllowed();
|
||||
p["inhibits"] = powerInhibitSummary();
|
||||
|
||||
// --- battery ------------------------------------------------------------
|
||||
// `valid: false` means no divider is wired. The endpoint should render
|
||||
// that as "not measured", never as 0 V — a low-battery alarm that fires
|
||||
// because a sensor is absent is worse than no alarm.
|
||||
JsonObject b = body["battery"].to<JsonObject>();
|
||||
b["valid"] = bt.valid;
|
||||
b["mv"] = bt.mv;
|
||||
b["pct"] = bt.pct;
|
||||
b["raw_mv"] = bt.raw_mv;
|
||||
b["chemistry"] = g_cfg.battery_chemistry;
|
||||
b["low"] = bt.valid && g_cfg.battery_chemistry != BATT_NONE &&
|
||||
bt.pct < g_cfg.battery_warn_pct;
|
||||
|
||||
// --- counters -----------------------------------------------------------
|
||||
// Reset on power cycle, not on reboot-from-sleep. The endpoint's own count
|
||||
// is authoritative; these are the device's view, useful mainly as a
|
||||
// delivery-gap detector (captured_today >> delivered_today = upload trouble).
|
||||
JsonObject c = body["counters"].to<JsonObject>();
|
||||
c["captured_today"] = st.captured_today;
|
||||
c["delivered_today"] = st.delivered_today;
|
||||
c["failed_today"] = st.failed_today;
|
||||
c["events_today"] = st.events_today;
|
||||
c["day_index"] = st.day_index;
|
||||
c["captured_boot"] = st.captured_boot;
|
||||
c["delivered_boot"] = st.delivered_boot;
|
||||
|
||||
// --- camera / night -----------------------------------------------------
|
||||
uint16_t cw = 0, ch = 0;
|
||||
framesizeDims(g_cfg.frame_size, &cw, &ch);
|
||||
JsonObject cam = body["camera"].to<JsonObject>();
|
||||
cam["frame_size"] = framesizeName(g_cfg.frame_size); // name, not index
|
||||
cam["frame_size_id"] = g_cfg.frame_size;
|
||||
cam["width"] = cw;
|
||||
cam["height"] = ch;
|
||||
cam["jpeg_quality"] = g_cfg.jpeg_quality;
|
||||
cam["profile"] = cameraNightProfileActive() ? "night" : "day";
|
||||
cam["ready"] = cameraReady();
|
||||
// Sensor PID identifies what is actually fitted: 0x2640 OV2640,
|
||||
// 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have shipped with
|
||||
// OV3660 rather than OV2640, so do not assume.
|
||||
sensor_t* sens = esp_camera_sensor_get();
|
||||
cam["sensor_pid"] = sens ? sens->id.PID : 0;
|
||||
|
||||
JsonObject n = body["night"].to<JsonObject>();
|
||||
n["is_night"] = nightIsNight();
|
||||
n["nightlight_on"] = nightlightIsOn();
|
||||
n["behaviour"] = g_cfg.night_behaviour;
|
||||
n["capture_allowed"] = nightCaptureAllowed();
|
||||
|
||||
// --- stream -------------------------------------------------------------
|
||||
JsonObject s = body["stream"].to<JsonObject>();
|
||||
s["enabled"] = g_cfg.stream_enabled;
|
||||
s["active"] = streamActive();
|
||||
s["frames_sent"] = streamFramesSent();
|
||||
s["seconds_left"] = streamSecondsLeft();
|
||||
|
||||
// --- radar --------------------------------------------------------------
|
||||
JsonObject r = body["radar"].to<JsonObject>();
|
||||
r["baud"] = radarBaud(); // 0 = no frames decoded at any baud
|
||||
r["uart_ok"] = rd.valid;
|
||||
r["out_pin"] = rd.out_pin;
|
||||
r["state"] = rd.target;
|
||||
r["moving_cm"] = rd.moving_cm;
|
||||
r["moving_energy"] = rd.moving_energy;
|
||||
r["stationary_cm"] = rd.stationary_cm;
|
||||
r["stationary_energy"] = rd.stationary_energy;
|
||||
|
||||
// --- network / memory ---------------------------------------------------
|
||||
JsonObject sys = body["system"].to<JsonObject>();
|
||||
sys["rssi"] = WiFi.RSSI();
|
||||
sys["ip"] = WiFi.localIP().toString();
|
||||
sys["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||
sys["free_psram"] = (uint32_t)ESP.getFreePsram();
|
||||
sys["ring_depth"] = (uint32_t)ringCount();
|
||||
sys["ring_bytes"] = (uint32_t)ringBytesUsed();
|
||||
|
||||
char iso[32];
|
||||
netIsoTime(iso, sizeof(iso));
|
||||
body["time_synced"] = netTimeValid();
|
||||
body["device_time"] = iso; // empty string when unsynced
|
||||
}
|
||||
|
||||
bool apiPostStatus(const char* reason) {
|
||||
JsonDocument body;
|
||||
buildConditions(body, reason);
|
||||
|
||||
String payload;
|
||||
serializeJson(body, payload);
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url("/status");
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_POST;
|
||||
cfg.timeout_ms = 6000;
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
||||
setAuth(c);
|
||||
setCommonHeaders(c);
|
||||
|
||||
bool ok = false;
|
||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
||||
esp_http_client_fetch_headers(c);
|
||||
int st = esp_http_client_get_status_code(c);
|
||||
readBody(c);
|
||||
if (st == 401) s_token_rejected = true;
|
||||
ok = (st >= 200 && st < 300);
|
||||
if (!ok) log_w("status: HTTP %d", st);
|
||||
} else {
|
||||
log_w("status: connect failed");
|
||||
}
|
||||
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
return ok;
|
||||
}
|
||||
|
||||
ServerEnvelope apiHeartbeat(CommandHandler on_cmd) {
|
||||
ServerEnvelope env = {};
|
||||
|
||||
JsonDocument body;
|
||||
buildConditions(body, "heartbeat");
|
||||
|
||||
String payload;
|
||||
serializeJson(body, payload);
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url("/heartbeat");
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_POST;
|
||||
cfg.timeout_ms = 8000;
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
||||
setAuth(c);
|
||||
setCommonHeaders(c);
|
||||
|
||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
||||
esp_http_client_fetch_headers(c);
|
||||
env.http_status = esp_http_client_get_status_code(c);
|
||||
int len = readBody(c);
|
||||
|
||||
if (env.http_status == 401) {
|
||||
s_token_rejected = true;
|
||||
} else if (env.http_status >= 200 && env.http_status < 300) {
|
||||
env.ok = true;
|
||||
parseEnvelope(env, len, on_cmd);
|
||||
}
|
||||
}
|
||||
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
return env;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
bool apiFetchConfig() {
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url("/config");
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_GET;
|
||||
cfg.timeout_ms = 8000;
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
setAuth(c);
|
||||
setCommonHeaders(c);
|
||||
|
||||
bool changed = false;
|
||||
if (esp_http_client_open(c, 0) == ESP_OK) {
|
||||
esp_http_client_fetch_headers(c);
|
||||
int status = esp_http_client_get_status_code(c);
|
||||
int len = readBody(c);
|
||||
if (status == 401) s_token_rejected = true;
|
||||
if (status >= 200 && status < 300 && len > 0) {
|
||||
JsonDocument doc;
|
||||
if (!deserializeJson(doc, s_resp, len)) {
|
||||
changed = configApplyJson(doc.as<JsonObjectConst>());
|
||||
if (changed) {
|
||||
configSave();
|
||||
log_i("config updated to version %u", g_cfg.config_version);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
return changed;
|
||||
}
|
||||
|
||||
bool apiAckCommand(uint32_t command_id, const char* status, const char* detail) {
|
||||
JsonDocument body;
|
||||
body["status"] = status;
|
||||
body["detail"] = detail ? detail : "";
|
||||
|
||||
String payload;
|
||||
serializeJson(body, payload);
|
||||
|
||||
char path[64];
|
||||
snprintf(path, sizeof(path), "/commands/%u/ack", (unsigned)command_id);
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url(path);
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_POST;
|
||||
cfg.timeout_ms = 6000;
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
esp_http_client_set_header(c, "Content-Type", "application/json");
|
||||
setAuth(c);
|
||||
setCommonHeaders(c);
|
||||
|
||||
bool ok = false;
|
||||
if (esp_http_client_open(c, payload.length()) == ESP_OK) {
|
||||
esp_http_client_write(c, payload.c_str(), payload.length());
|
||||
esp_http_client_fetch_headers(c);
|
||||
int st = esp_http_client_get_status_code(c);
|
||||
readBody(c);
|
||||
ok = (st >= 200 && st < 300);
|
||||
}
|
||||
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stream push — chunked multipart/x-mixed-replace, device -> Pi.
|
||||
//
|
||||
// The device pushes and the Pi relays (SPEC C3: the ESP32 is never reachable
|
||||
// from outside the LAN, and here not even from outside the Pi). The Pi decides
|
||||
// per X-Stream-Mode whether to relay to viewers, write to disk, or both.
|
||||
// ---------------------------------------------------------------------------
|
||||
static const char* kBoundary = "poorbirdframe";
|
||||
|
||||
bool apiStreamOpen(const char* session_id, uint8_t mode, uint16_t duration_s) {
|
||||
if (s_stream) apiStreamClose();
|
||||
|
||||
char path[96];
|
||||
snprintf(path, sizeof(path), "/stream/%s", session_id);
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
String u = url(path);
|
||||
cfg.url = u.c_str();
|
||||
cfg.method = HTTP_METHOD_POST;
|
||||
cfg.timeout_ms = 10000;
|
||||
|
||||
s_stream = esp_http_client_init(&cfg);
|
||||
esp_http_client_set_header(s_stream, "Content-Type",
|
||||
"multipart/x-mixed-replace; boundary=" "poorbirdframe");
|
||||
setAuth(s_stream);
|
||||
setCommonHeaders(s_stream);
|
||||
|
||||
const char* mode_s = (mode == 1) ? "record" : (mode == 2) ? "both" : "watch";
|
||||
esp_http_client_set_header(s_stream, "X-Stream-Mode", mode_s);
|
||||
|
||||
char b[16];
|
||||
snprintf(b, sizeof(b), "%u", duration_s);
|
||||
esp_http_client_set_header(s_stream, "X-Duration-S", b);
|
||||
|
||||
// -1 == chunked transfer encoding: we do not know the total length.
|
||||
if (esp_http_client_open(s_stream, -1) != ESP_OK) {
|
||||
log_e("stream: cannot open %s", u.c_str());
|
||||
esp_http_client_cleanup(s_stream);
|
||||
s_stream = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
log_i("stream %s open, mode=%s, cap %us", session_id, mode_s, duration_s);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool apiStreamSendFrame(const uint8_t* jpeg, size_t len, int64_t epoch_ms) {
|
||||
if (!s_stream || !jpeg || len == 0) return false;
|
||||
|
||||
char head[192];
|
||||
int hl = snprintf(head, sizeof(head),
|
||||
"\r\n--%s\r\n"
|
||||
"Content-Type: image/jpeg\r\n"
|
||||
"Content-Length: %u\r\n"
|
||||
"X-Timestamp: %lld\r\n\r\n",
|
||||
kBoundary, (unsigned)len, (long long)epoch_ms);
|
||||
|
||||
if (esp_http_client_write(s_stream, head, hl) != hl) return false;
|
||||
return esp_http_client_write(s_stream, (const char*)jpeg, len) == (int)len;
|
||||
}
|
||||
|
||||
void apiStreamClose() {
|
||||
if (!s_stream) return;
|
||||
char tail[64];
|
||||
int tl = snprintf(tail, sizeof(tail), "\r\n--%s--\r\n", kBoundary);
|
||||
esp_http_client_write(s_stream, tail, tl);
|
||||
|
||||
esp_http_client_fetch_headers(s_stream);
|
||||
int st = esp_http_client_get_status_code(s_stream);
|
||||
esp_http_client_close(s_stream);
|
||||
esp_http_client_cleanup(s_stream);
|
||||
s_stream = nullptr;
|
||||
log_i("stream closed, HTTP %d", st);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
#include "app_config.h"
|
||||
|
||||
#include <Preferences.h>
|
||||
#include <esp_camera.h>
|
||||
#include <esp_mac.h>
|
||||
|
||||
#include "board_pins.h"
|
||||
#include "camera_mgr.h"
|
||||
|
||||
AppConfig g_cfg;
|
||||
|
||||
static Preferences s_nvs;
|
||||
static const char* kNamespace = "poorbird";
|
||||
static char s_uid[13] = {0};
|
||||
|
||||
// Compile-time fallbacks. Anything secret comes in via secrets.ini, never here.
|
||||
#ifndef CFG_WIFI_SSID
|
||||
#define CFG_WIFI_SSID ""
|
||||
#endif
|
||||
#ifndef CFG_WIFI_PASS
|
||||
#define CFG_WIFI_PASS ""
|
||||
#endif
|
||||
#ifndef CFG_API_HOST
|
||||
#define CFG_API_HOST "192.168.1.50"
|
||||
#endif
|
||||
#ifndef CFG_API_PORT
|
||||
#define CFG_API_PORT 8080
|
||||
#endif
|
||||
#ifndef CFG_ENROLL_SECRET
|
||||
#define CFG_ENROLL_SECRET ""
|
||||
#endif
|
||||
#ifndef CFG_TZ
|
||||
#define CFG_TZ "CET-1CEST,M3.5.0,M10.5.0/3"
|
||||
#endif
|
||||
#ifndef CFG_DEEP_SLEEP
|
||||
#define CFG_DEEP_SLEEP 0
|
||||
#endif
|
||||
|
||||
static void setStr(char* dst, size_t cap, const char* src) {
|
||||
strncpy(dst, src ? src : "", cap - 1);
|
||||
dst[cap - 1] = '\0';
|
||||
}
|
||||
|
||||
static void loadDefaults(AppConfig& c) {
|
||||
memset(&c, 0, sizeof(c));
|
||||
|
||||
setStr(c.device_name, sizeof(c.device_name), "poorbird-cam-1");
|
||||
setStr(c.wifi_ssid, sizeof(c.wifi_ssid), CFG_WIFI_SSID);
|
||||
setStr(c.wifi_pass, sizeof(c.wifi_pass), CFG_WIFI_PASS);
|
||||
setStr(c.api_host, sizeof(c.api_host), CFG_API_HOST);
|
||||
c.api_port = CFG_API_PORT;
|
||||
setStr(c.api_base, sizeof(c.api_base), "/api/v1");
|
||||
setStr(c.device_token, sizeof(c.device_token), "");
|
||||
setStr(c.enroll_secret, sizeof(c.enroll_secret), CFG_ENROLL_SECRET);
|
||||
|
||||
setStr(c.ntp_host, sizeof(c.ntp_host), ""); // empty => api_host
|
||||
setStr(c.tz, sizeof(c.tz), CFG_TZ);
|
||||
|
||||
c.frame_size = CFG_FRAME_SIZE;
|
||||
c.jpeg_quality = CFG_JPEG_QUALITY;
|
||||
c.vflip = false;
|
||||
c.hmirror = false;
|
||||
|
||||
// Day: everything automatic, exposure biased up for birds backlit against
|
||||
// sky, gain capped at 4x so the sensor prefers a short shutter over a
|
||||
// noisy one. Motion blur is the enemy, not noise.
|
||||
c.cam_day.brightness = 0;
|
||||
c.cam_day.contrast = 1;
|
||||
c.cam_day.saturation = 0;
|
||||
c.cam_day.sharpness = 0;
|
||||
c.cam_day.ae_level = 1;
|
||||
c.cam_day.special_effect = 0;
|
||||
c.cam_day.wb_mode = 0; // auto
|
||||
c.cam_day.gainceiling = 1; // 4x
|
||||
c.cam_day.agc_gain = 0;
|
||||
c.cam_day.aec_value = 300;
|
||||
c.cam_day.whitebal = true;
|
||||
c.cam_day.awb_gain = true;
|
||||
c.cam_day.exposure_ctrl = true;
|
||||
c.cam_day.aec2 = true;
|
||||
c.cam_day.gain_ctrl = true;
|
||||
c.cam_day.bpc = true;
|
||||
c.cam_day.wpc = true;
|
||||
c.cam_day.raw_gma = true;
|
||||
c.cam_day.lenc = true;
|
||||
c.cam_day.dcw = true;
|
||||
c.cam_day.colorbar = false;
|
||||
|
||||
// Night: the trade reverses. A noisy identifiable bird beats a clean black
|
||||
// rectangle, so the gain ceiling goes up and saturation comes down
|
||||
// (colour under artificial light is wrong anyway).
|
||||
c.cam_night = c.cam_day;
|
||||
c.cam_night.brightness = 1;
|
||||
c.cam_night.contrast = 0;
|
||||
c.cam_night.saturation = -1;
|
||||
c.cam_night.ae_level = 2;
|
||||
c.cam_night.gainceiling = 4; // 32x
|
||||
|
||||
c.ring_frames = CFG_RING_FRAMES;
|
||||
c.pre_roll = CFG_PRE_ROLL;
|
||||
c.post_roll = CFG_POST_ROLL;
|
||||
c.post_roll_gap_ms = 250;
|
||||
c.cooldown_s = CFG_COOLDOWN_S;
|
||||
c.idle_period_ms = 400; // ~2.5 fps into the ring; ~10 s of history at depth 24
|
||||
|
||||
c.radar_mode = RADAR_BOTH;
|
||||
c.accept_stationary = true;
|
||||
c.min_distance_cm = 20;
|
||||
c.max_distance_cm = 300; // a feeder at 1-3 m; widen after field testing
|
||||
c.min_energy = 20;
|
||||
c.radar_baud = 0; // autodetect
|
||||
|
||||
c.stream_enabled = false;
|
||||
c.stream_frame_size = CFG_STREAM_FRAME_SIZE;
|
||||
c.stream_jpeg_quality = 15;
|
||||
c.stream_duration_s = 60; // SPEC C9: always time-boxed
|
||||
c.stream_fps = 10;
|
||||
c.stream_mode = STREAM_WATCH;
|
||||
c.stream_blocks_sleep = true;
|
||||
|
||||
c.night_start_min = 21 * 60; // 21:00, overridden by pushed sunset
|
||||
c.night_end_min = 6 * 60; // 06:00
|
||||
c.night_behaviour = NIGHT_SLEEP; // most garden birds are diurnal
|
||||
c.nightlight_mode = NIGHTLIGHT_OFF;
|
||||
c.nightlight_brightness = 128;
|
||||
|
||||
c.battery_chemistry = BATT_NONE; // mains by default; no cell wired
|
||||
c.battery_divider_x100 = 200; // two equal resistors
|
||||
c.battery_offset_mv = 0;
|
||||
c.battery_min_pct_ota = 50; // SPEC C6
|
||||
c.battery_warn_pct = 20;
|
||||
|
||||
c.heartbeat_interval_s = CFG_HEARTBEAT_S;
|
||||
c.status_interval_s = 900;
|
||||
c.ota_enabled = true;
|
||||
|
||||
c.deep_sleep_enabled = CFG_DEEP_SLEEP; // 0 = mains powered, stay awake
|
||||
c.deep_sleep_s = 300;
|
||||
c.sleep_wake_on_radar = true;
|
||||
c.sleep_idle_timeout_s = 20;
|
||||
c.sleep_max_awake_s = 300;
|
||||
|
||||
c.config_version = 0;
|
||||
}
|
||||
|
||||
void configLoad() {
|
||||
loadDefaults(g_cfg);
|
||||
|
||||
if (!s_nvs.begin(kNamespace, /*readOnly=*/true)) {
|
||||
log_w("no NVS namespace yet, running on compile-time defaults");
|
||||
return;
|
||||
}
|
||||
|
||||
// Stored as one blob. The size check means a struct change during
|
||||
// development degrades to "fall back to defaults" instead of reading
|
||||
// garbage into half the fields.
|
||||
size_t stored = s_nvs.getBytesLength("cfg");
|
||||
if (stored == sizeof(AppConfig)) {
|
||||
AppConfig tmp;
|
||||
s_nvs.getBytes("cfg", &tmp, sizeof(tmp));
|
||||
g_cfg = tmp;
|
||||
log_i("config loaded from NVS (version %u)", g_cfg.config_version);
|
||||
} else if (stored > 0) {
|
||||
log_w("NVS config is %u bytes, expected %u — layout changed, using defaults",
|
||||
(unsigned)stored, (unsigned)sizeof(AppConfig));
|
||||
}
|
||||
s_nvs.end();
|
||||
|
||||
// Credentials are stored outside the blob so that a struct layout change
|
||||
// during development never costs you the enrollment — which, on a device
|
||||
// you cannot reach over USB, would mean a ladder.
|
||||
if (s_nvs.begin(kNamespace, true)) {
|
||||
String tok = s_nvs.getString("token", "");
|
||||
if (tok.length()) setStr(g_cfg.device_token, sizeof(g_cfg.device_token), tok.c_str());
|
||||
|
||||
String sec = s_nvs.getString("enroll", "");
|
||||
if (sec.length()) setStr(g_cfg.enroll_secret, sizeof(g_cfg.enroll_secret), sec.c_str());
|
||||
s_nvs.end();
|
||||
}
|
||||
}
|
||||
|
||||
bool configSave() {
|
||||
if (!s_nvs.begin(kNamespace, /*readOnly=*/false)) {
|
||||
log_e("NVS open for write failed");
|
||||
return false;
|
||||
}
|
||||
bool ok = s_nvs.putBytes("cfg", &g_cfg, sizeof(g_cfg)) == sizeof(g_cfg);
|
||||
ok &= s_nvs.putString("token", g_cfg.device_token) >= 0;
|
||||
ok &= s_nvs.putString("enroll", g_cfg.enroll_secret) >= 0;
|
||||
s_nvs.end();
|
||||
if (!ok) log_e("NVS write failed");
|
||||
return ok;
|
||||
}
|
||||
|
||||
// --- JSON merge -------------------------------------------------------------
|
||||
// Helpers keep configApplyJson readable and make "only touch keys that are
|
||||
// present" the default behaviour rather than something each field repeats.
|
||||
|
||||
#define MERGE_NUM(field, key) \
|
||||
if (!doc[key].isNull()) { \
|
||||
auto v = doc[key].as<decltype(g_cfg.field)>();\
|
||||
if (v != g_cfg.field) { g_cfg.field = v; changed = true; } \
|
||||
}
|
||||
|
||||
#define MERGE_BOOL(field, key) \
|
||||
if (!doc[key].isNull()) { \
|
||||
bool v = doc[key].as<bool>(); \
|
||||
if (v != g_cfg.field) { g_cfg.field = v; changed = true; } \
|
||||
}
|
||||
|
||||
#define MERGE_STR(field, key) \
|
||||
if (!doc[key].isNull()) { \
|
||||
const char* v = doc[key].as<const char*>(); \
|
||||
if (v && strcmp(v, g_cfg.field) != 0) { \
|
||||
setStr(g_cfg.field, sizeof(g_cfg.field), v); \
|
||||
changed = true; \
|
||||
} \
|
||||
}
|
||||
|
||||
// A frame size may arrive as a name ("SVGA") or as a raw framesize_t index.
|
||||
// Names are the supported form; the numeric path exists so an older endpoint
|
||||
// keeps working, and because a number is unambiguous once you know the
|
||||
// driver version.
|
||||
static bool mergeFrameSize(uint8_t& field, JsonVariantConst v) {
|
||||
if (v.isNull()) return false;
|
||||
|
||||
uint8_t next = field;
|
||||
if (v.is<const char*>()) {
|
||||
next = framesizeFromName(v.as<const char*>(), field);
|
||||
} else if (v.is<unsigned int>() || v.is<int>()) {
|
||||
int n = v.as<int>();
|
||||
if (n < 0 || n >= FRAMESIZE_INVALID) {
|
||||
log_w("config: frame size index %d out of range, ignoring", n);
|
||||
return false;
|
||||
}
|
||||
next = (uint8_t)n;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (next == field) return false;
|
||||
field = next;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Camera tuning arrives as a nested object ("cam_day" / "cam_night") so the
|
||||
// two profiles stay visually distinct in the endpoint's settings UI.
|
||||
static bool mergeTuning(CamTuning& t, JsonObjectConst d) {
|
||||
if (d.isNull()) return false;
|
||||
bool changed = false;
|
||||
|
||||
#define T_NUM(field, key) \
|
||||
if (!d[key].isNull()) { \
|
||||
auto v = d[key].as<decltype(t.field)>(); \
|
||||
if (v != t.field) { t.field = v; changed = true; } \
|
||||
}
|
||||
#define T_BOOL(field, key) \
|
||||
if (!d[key].isNull()) { \
|
||||
bool v = d[key].as<bool>(); \
|
||||
if (v != t.field) { t.field = v; changed = true; } \
|
||||
}
|
||||
|
||||
T_NUM(brightness, "brightness");
|
||||
T_NUM(contrast, "contrast");
|
||||
T_NUM(saturation, "saturation");
|
||||
T_NUM(sharpness, "sharpness");
|
||||
T_NUM(ae_level, "ae_level");
|
||||
T_NUM(special_effect, "special_effect");
|
||||
T_NUM(wb_mode, "wb_mode");
|
||||
T_NUM(gainceiling, "gainceiling");
|
||||
T_NUM(agc_gain, "agc_gain");
|
||||
T_NUM(aec_value, "aec_value");
|
||||
T_BOOL(whitebal, "whitebal");
|
||||
T_BOOL(awb_gain, "awb_gain");
|
||||
T_BOOL(exposure_ctrl, "exposure_ctrl");
|
||||
T_BOOL(aec2, "aec2");
|
||||
T_BOOL(gain_ctrl, "gain_ctrl");
|
||||
T_BOOL(bpc, "bpc");
|
||||
T_BOOL(wpc, "wpc");
|
||||
T_BOOL(raw_gma, "raw_gma");
|
||||
T_BOOL(lenc, "lenc");
|
||||
T_BOOL(dcw, "dcw");
|
||||
T_BOOL(colorbar, "colorbar");
|
||||
|
||||
#undef T_NUM
|
||||
#undef T_BOOL
|
||||
|
||||
// Sensor ranges. Out-of-range values are rejected silently by the driver,
|
||||
// which makes a typo in the settings UI look like the device ignored it.
|
||||
if (t.brightness < -2) t.brightness = -2; if (t.brightness > 2) t.brightness = 2;
|
||||
if (t.contrast < -2) t.contrast = -2; if (t.contrast > 2) t.contrast = 2;
|
||||
if (t.saturation < -2) t.saturation = -2; if (t.saturation > 2) t.saturation = 2;
|
||||
if (t.sharpness < -2) t.sharpness = -2; if (t.sharpness > 2) t.sharpness = 2;
|
||||
if (t.ae_level < -2) t.ae_level = -2; if (t.ae_level > 2) t.ae_level = 2;
|
||||
if (t.special_effect > 6) t.special_effect = 0;
|
||||
if (t.wb_mode > 4) t.wb_mode = 0;
|
||||
if (t.gainceiling > 6) t.gainceiling = 6;
|
||||
if (t.agc_gain > 30) t.agc_gain = 30;
|
||||
if (t.aec_value > 1200) t.aec_value = 1200;
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
bool configApplyJson(JsonObjectConst doc) {
|
||||
bool changed = false;
|
||||
|
||||
MERGE_STR(device_name, "device_name");
|
||||
MERGE_STR(api_host, "api_host");
|
||||
MERGE_NUM(api_port, "api_port");
|
||||
MERGE_STR(ntp_host, "ntp_host");
|
||||
MERGE_STR(tz, "tz");
|
||||
|
||||
// Frame sizes accept "SVGA" or a raw index. Names are preferred and are
|
||||
// what the settings UI should send — see framesizeFromName().
|
||||
changed |= mergeFrameSize(g_cfg.frame_size, doc["frame_size"]);
|
||||
changed |= mergeFrameSize(g_cfg.stream_frame_size, doc["stream_frame_size"]);
|
||||
|
||||
MERGE_NUM(jpeg_quality, "jpeg_quality");
|
||||
MERGE_BOOL(vflip, "vflip");
|
||||
MERGE_BOOL(hmirror, "hmirror");
|
||||
|
||||
changed |= mergeTuning(g_cfg.cam_day, doc["cam_day"]);
|
||||
changed |= mergeTuning(g_cfg.cam_night, doc["cam_night"]);
|
||||
|
||||
MERGE_NUM(ring_frames, "ring_frames");
|
||||
MERGE_NUM(pre_roll, "pre_roll");
|
||||
MERGE_NUM(post_roll, "post_roll");
|
||||
MERGE_NUM(post_roll_gap_ms, "post_roll_gap_ms");
|
||||
MERGE_NUM(cooldown_s, "cooldown_s");
|
||||
MERGE_NUM(idle_period_ms, "idle_period_ms");
|
||||
|
||||
MERGE_NUM(radar_mode, "radar_mode");
|
||||
MERGE_BOOL(accept_stationary,"accept_stationary");
|
||||
MERGE_NUM(min_distance_cm, "min_distance_cm");
|
||||
MERGE_NUM(max_distance_cm, "max_distance_cm");
|
||||
MERGE_NUM(min_energy, "min_energy");
|
||||
MERGE_NUM(radar_baud, "radar_baud");
|
||||
|
||||
MERGE_BOOL(stream_enabled, "stream_enabled");
|
||||
MERGE_NUM(stream_frame_size, "stream_frame_size");
|
||||
MERGE_NUM(stream_jpeg_quality, "stream_jpeg_quality");
|
||||
MERGE_NUM(stream_duration_s, "stream_duration_s");
|
||||
MERGE_NUM(stream_fps, "stream_fps");
|
||||
MERGE_NUM(stream_mode, "stream_mode");
|
||||
MERGE_BOOL(stream_blocks_sleep,"stream_blocks_sleep");
|
||||
|
||||
MERGE_NUM(night_start_min, "night_start_min");
|
||||
MERGE_NUM(night_end_min, "night_end_min");
|
||||
MERGE_NUM(night_behaviour, "night_behaviour");
|
||||
MERGE_NUM(nightlight_mode, "nightlight_mode");
|
||||
MERGE_NUM(nightlight_brightness, "nightlight_brightness");
|
||||
|
||||
MERGE_NUM(battery_chemistry, "battery_chemistry");
|
||||
MERGE_NUM(battery_divider_x100, "battery_divider_x100");
|
||||
MERGE_NUM(battery_offset_mv, "battery_offset_mv");
|
||||
MERGE_NUM(battery_min_pct_ota, "battery_min_pct_ota");
|
||||
MERGE_NUM(battery_warn_pct, "battery_warn_pct");
|
||||
|
||||
MERGE_NUM(heartbeat_interval_s, "heartbeat_interval_s");
|
||||
MERGE_NUM(status_interval_s, "status_interval_s");
|
||||
MERGE_BOOL(ota_enabled, "ota_enabled");
|
||||
|
||||
MERGE_BOOL(deep_sleep_enabled, "deep_sleep_enabled");
|
||||
MERGE_NUM(deep_sleep_s, "deep_sleep_s");
|
||||
MERGE_BOOL(sleep_wake_on_radar, "sleep_wake_on_radar");
|
||||
MERGE_NUM(sleep_idle_timeout_s, "sleep_idle_timeout_s");
|
||||
MERGE_NUM(sleep_max_awake_s, "sleep_max_awake_s");
|
||||
|
||||
// Clamp the things that brick the device or the battery if the endpoint
|
||||
// sends nonsense. The device is the last line of defence here, because a
|
||||
// bad config push reaches a box that is mounted outdoors.
|
||||
if (g_cfg.jpeg_quality < 4) g_cfg.jpeg_quality = 4;
|
||||
if (g_cfg.jpeg_quality > 40) g_cfg.jpeg_quality = 40;
|
||||
if (g_cfg.ring_frames < 2) g_cfg.ring_frames = 2;
|
||||
if (g_cfg.ring_frames > 60) g_cfg.ring_frames = 60;
|
||||
if (g_cfg.pre_roll >= g_cfg.ring_frames) g_cfg.pre_roll = g_cfg.ring_frames - 1;
|
||||
if (g_cfg.stream_duration_s > 600) g_cfg.stream_duration_s = 600; // C9 hard cap
|
||||
if (g_cfg.stream_fps < 1) g_cfg.stream_fps = 1;
|
||||
if (g_cfg.stream_fps > 25) g_cfg.stream_fps = 25;
|
||||
if (g_cfg.heartbeat_interval_s < 30) g_cfg.heartbeat_interval_s = 30;
|
||||
if (g_cfg.idle_period_ms < 100) g_cfg.idle_period_ms = 100;
|
||||
|
||||
// Sleep floors. A device that sleeps too eagerly can become unreachable
|
||||
// before it has drained the command queue that would turn sleep back off.
|
||||
if (g_cfg.deep_sleep_s < 30) g_cfg.deep_sleep_s = 30;
|
||||
if (g_cfg.deep_sleep_s > 3600) g_cfg.deep_sleep_s = 3600;
|
||||
if (g_cfg.sleep_idle_timeout_s < 10) g_cfg.sleep_idle_timeout_s = 10;
|
||||
if (g_cfg.sleep_max_awake_s < g_cfg.sleep_idle_timeout_s)
|
||||
g_cfg.sleep_max_awake_s = g_cfg.sleep_idle_timeout_s;
|
||||
|
||||
if (g_cfg.night_start_min > 1439) g_cfg.night_start_min = 1439;
|
||||
if (g_cfg.night_end_min > 1439) g_cfg.night_end_min = 1439;
|
||||
if (g_cfg.night_behaviour > NIGHT_SLEEP) g_cfg.night_behaviour = NIGHT_CAPTURE;
|
||||
if (g_cfg.nightlight_mode > NIGHTLIGHT_ALWAYS) g_cfg.nightlight_mode = NIGHTLIGHT_OFF;
|
||||
|
||||
if (g_cfg.battery_chemistry > BATT_LIFEPO4) g_cfg.battery_chemistry = BATT_NONE;
|
||||
// A zero divider would report the pin voltage as the battery voltage and
|
||||
// silently trip the OTA gate at the worst possible moment.
|
||||
if (g_cfg.battery_divider_x100 < 100) g_cfg.battery_divider_x100 = 100;
|
||||
if (g_cfg.battery_divider_x100 > 2000) g_cfg.battery_divider_x100 = 2000;
|
||||
if (g_cfg.battery_min_pct_ota > 95) g_cfg.battery_min_pct_ota = 95;
|
||||
|
||||
// config_version last, so it only advances if the payload was processed.
|
||||
if (!doc["config_version"].isNull()) {
|
||||
uint32_t v = doc["config_version"].as<uint32_t>();
|
||||
if (v != g_cfg.config_version) { g_cfg.config_version = v; changed = true; }
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
#undef MERGE_NUM
|
||||
#undef MERGE_BOOL
|
||||
#undef MERGE_STR
|
||||
|
||||
bool configNeedsCameraRestart(const AppConfig& a, const AppConfig& b) {
|
||||
// Frame size changes the framebuffer allocation, so it cannot be applied
|
||||
// to a running sensor without tearing the driver down.
|
||||
return a.frame_size != b.frame_size;
|
||||
}
|
||||
|
||||
const char* configBootstrapSecret() { return CFG_ENROLL_SECRET; }
|
||||
|
||||
const char* deviceUid() {
|
||||
if (s_uid[0]) return s_uid;
|
||||
uint8_t mac[6] = {0};
|
||||
esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
||||
snprintf(s_uid, sizeof(s_uid), "%02x%02x%02x%02x%02x%02x",
|
||||
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
return s_uid;
|
||||
}
|
||||
|
||||
String apiBaseUrl() {
|
||||
String u = "http://";
|
||||
u += g_cfg.api_host;
|
||||
u += ":";
|
||||
u += String(g_cfg.api_port);
|
||||
u += g_cfg.api_base;
|
||||
return u;
|
||||
}
|
||||
|
||||
void configDump() {
|
||||
log_i("--- poorBird config ------------------------------");
|
||||
log_i(" uid %s name %s", deviceUid(), g_cfg.device_name);
|
||||
log_i(" fw %s cfg_version %u", FW_VERSION, g_cfg.config_version);
|
||||
log_i(" endpoint %s", apiBaseUrl().c_str());
|
||||
log_i(" enrolled %s", g_cfg.device_token[0] ? "yes" : "NO");
|
||||
uint16_t cw = 0, ch = 0, sw = 0, sh = 0;
|
||||
framesizeDims(g_cfg.frame_size, &cw, &ch);
|
||||
framesizeDims(g_cfg.stream_frame_size, &sw, &sh);
|
||||
log_i(" camera %s (%ux%u) quality=%u | stream %s (%ux%u)",
|
||||
framesizeName(g_cfg.frame_size), cw, ch, g_cfg.jpeg_quality,
|
||||
framesizeName(g_cfg.stream_frame_size), sw, sh);
|
||||
log_i(" ring depth=%u pre=%u post=%u period=%ums",
|
||||
g_cfg.ring_frames, g_cfg.pre_roll, g_cfg.post_roll, g_cfg.idle_period_ms);
|
||||
log_i(" radar mode=%u window=%u..%ucm energy>=%u stationary=%d",
|
||||
g_cfg.radar_mode, g_cfg.min_distance_cm, g_cfg.max_distance_cm,
|
||||
g_cfg.min_energy, g_cfg.accept_stationary);
|
||||
log_i(" stream enabled=%d mode=%u %us @%ufps size=%u",
|
||||
g_cfg.stream_enabled, g_cfg.stream_mode, g_cfg.stream_duration_s,
|
||||
g_cfg.stream_fps, g_cfg.stream_frame_size);
|
||||
log_i(" night %02u:%02u-%02u:%02u behaviour=%u light=%u/%u",
|
||||
g_cfg.night_start_min / 60, g_cfg.night_start_min % 60,
|
||||
g_cfg.night_end_min / 60, g_cfg.night_end_min % 60,
|
||||
g_cfg.night_behaviour, g_cfg.nightlight_mode, g_cfg.nightlight_brightness);
|
||||
log_i(" battery chem=%u divider=%.2f:1 trim=%dmV ota_min=%u%%",
|
||||
g_cfg.battery_chemistry, g_cfg.battery_divider_x100 / 100.0f,
|
||||
g_cfg.battery_offset_mv, g_cfg.battery_min_pct_ota);
|
||||
log_i(" heartbeat %us status %us ota=%d",
|
||||
g_cfg.heartbeat_interval_s, g_cfg.status_interval_s, g_cfg.ota_enabled);
|
||||
log_i(" power deep_sleep=%s wake_on_radar=%d every=%us idle=%us max_awake=%us",
|
||||
g_cfg.deep_sleep_enabled ? "ON" : "off", g_cfg.sleep_wake_on_radar,
|
||||
g_cfg.deep_sleep_s, g_cfg.sleep_idle_timeout_s, g_cfg.sleep_max_awake_s);
|
||||
log_i("--------------------------------------------------");
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
#include "battery.h"
|
||||
|
||||
#include "app_config.h"
|
||||
#include "board_pins.h"
|
||||
|
||||
static BatteryReading s_last = {};
|
||||
|
||||
// Discharge curves, millivolts at 100/90/…/0 %. Both are open-circuit
|
||||
// approximations at moderate load and room temperature; they are good enough
|
||||
// to drive a "low battery" banner and the OTA gate, and not good enough to
|
||||
// promise a runtime estimate.
|
||||
static const uint16_t kLiIon[11] = {
|
||||
4200, 4060, 3980, 3920, 3870, 3820, 3790, 3700, 3620, 3500, 3300
|
||||
};
|
||||
// LiFePO4 sits on a plateau near 3.2 V for most of its discharge. Percentage
|
||||
// from voltage is genuinely unreliable here — treat anything between 20 % and
|
||||
// 90 % as "somewhere in the middle" (SPEC §9 suggests this chemistry).
|
||||
static const uint16_t kLiFePO4[11] = {
|
||||
3650, 3350, 3320, 3300, 3280, 3260, 3240, 3220, 3200, 3100, 2800
|
||||
};
|
||||
|
||||
static uint8_t pctFromCurve(const uint16_t* curve, uint16_t mv) {
|
||||
if (mv >= curve[0]) return 100;
|
||||
if (mv <= curve[10]) return 0;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (mv <= curve[i] && mv > curve[i + 1]) {
|
||||
const uint16_t hi = curve[i], lo = curve[i + 1];
|
||||
const int top = 100 - i * 10;
|
||||
return (uint8_t)(top - (10 * (hi - mv)) / (hi - lo));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void batteryBegin() {
|
||||
#if PIN_BATTERY_ADC >= 0
|
||||
analogSetPinAttenuation(PIN_BATTERY_ADC, ADC_11db); // full ~0-3.1 V range
|
||||
#if PIN_BATTERY_EN >= 0
|
||||
pinMode(PIN_BATTERY_EN, OUTPUT);
|
||||
digitalWrite(PIN_BATTERY_EN, LOW); // divider off by default
|
||||
#endif
|
||||
log_i("battery: sensing on GPIO%d, divider %.2f:1",
|
||||
PIN_BATTERY_ADC, g_cfg.battery_divider_x100 / 100.0f);
|
||||
batteryPoll();
|
||||
#else
|
||||
log_i("battery: no sense pin configured, voltage will report as invalid");
|
||||
#endif
|
||||
}
|
||||
|
||||
BatteryReading batteryRead() {
|
||||
BatteryReading r = {};
|
||||
|
||||
#if PIN_BATTERY_ADC < 0
|
||||
return r; // not wired; valid stays false
|
||||
#else
|
||||
if (g_cfg.battery_divider_x100 == 0) return r;
|
||||
|
||||
#if PIN_BATTERY_EN >= 0
|
||||
digitalWrite(PIN_BATTERY_EN, HIGH);
|
||||
delayMicroseconds(200); // let the divider settle
|
||||
#endif
|
||||
|
||||
// Average several samples: a single ESP32 ADC read is noisy enough to move
|
||||
// the reported percentage by a point or two between calls.
|
||||
uint32_t acc = 0;
|
||||
const uint8_t samples = 16;
|
||||
for (uint8_t i = 0; i < samples; i++) acc += analogReadMilliVolts(PIN_BATTERY_ADC);
|
||||
|
||||
#if PIN_BATTERY_EN >= 0
|
||||
digitalWrite(PIN_BATTERY_EN, LOW);
|
||||
#endif
|
||||
|
||||
r.raw_mv = (uint16_t)(acc / samples);
|
||||
|
||||
int32_t mv = (int32_t)r.raw_mv * g_cfg.battery_divider_x100 / 100;
|
||||
mv += g_cfg.battery_offset_mv;
|
||||
if (mv < 0) mv = 0;
|
||||
r.mv = (uint16_t)mv;
|
||||
r.valid = true;
|
||||
|
||||
switch (g_cfg.battery_chemistry) {
|
||||
case BATT_LIION: r.pct = pctFromCurve(kLiIon, r.mv); break;
|
||||
case BATT_LIFEPO4: r.pct = pctFromCurve(kLiFePO4, r.mv); break;
|
||||
default: r.pct = 0; break; // BATT_NONE: voltage only
|
||||
}
|
||||
return r;
|
||||
#endif
|
||||
}
|
||||
|
||||
void batteryPoll() {
|
||||
BatteryReading r = batteryRead();
|
||||
if (r.valid) s_last = r;
|
||||
}
|
||||
|
||||
BatteryReading batteryLast() { return s_last; }
|
||||
|
||||
bool batteryAboveOtaThreshold(uint8_t min_pct) {
|
||||
BatteryReading r = batteryRead();
|
||||
|
||||
// No sensing hardware, or no chemistry configured, means we cannot judge.
|
||||
// Allow the flash: this build is mains-powered by default, and refusing
|
||||
// every OTA because an optional sensor is absent would be worse than the
|
||||
// risk it guards against. Wire the divider if you want the gate to bite.
|
||||
if (!r.valid || g_cfg.battery_chemistry == BATT_NONE) {
|
||||
log_w("battery: no reading, OTA battery gate not enforced");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (r.pct < min_pct) {
|
||||
log_w("battery: %u%% (%umV) is below the %u%% OTA threshold",
|
||||
r.pct, r.mv, min_pct);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
#include "camera_mgr.h"
|
||||
|
||||
#include <strings.h> // strcasecmp
|
||||
|
||||
#include "app_config.h"
|
||||
#include "board_pins.h"
|
||||
|
||||
static bool s_ready = false;
|
||||
|
||||
// Built from the enum symbols rather than literal indices, so this table
|
||||
// cannot drift when esp32-camera renumbers framesize_t.
|
||||
struct FsName { framesize_t fs; const char* name; };
|
||||
static const FsName kFsNames[] = {
|
||||
{FRAMESIZE_96X96, "96X96"}, {FRAMESIZE_QQVGA, "QQVGA"},
|
||||
{FRAMESIZE_128X128, "128X128"}, {FRAMESIZE_QCIF, "QCIF"},
|
||||
{FRAMESIZE_HQVGA, "HQVGA"}, {FRAMESIZE_240X240, "240X240"},
|
||||
{FRAMESIZE_QVGA, "QVGA"}, {FRAMESIZE_320X320, "320X320"},
|
||||
{FRAMESIZE_CIF, "CIF"}, {FRAMESIZE_HVGA, "HVGA"},
|
||||
{FRAMESIZE_VGA, "VGA"}, {FRAMESIZE_SVGA, "SVGA"},
|
||||
{FRAMESIZE_XGA, "XGA"}, {FRAMESIZE_HD, "HD"},
|
||||
{FRAMESIZE_SXGA, "SXGA"}, {FRAMESIZE_UXGA, "UXGA"},
|
||||
{FRAMESIZE_FHD, "FHD"}, {FRAMESIZE_QXGA, "QXGA"},
|
||||
{FRAMESIZE_QHD, "QHD"}, {FRAMESIZE_WQXGA, "WQXGA"},
|
||||
{FRAMESIZE_QSXGA, "QSXGA"}, {FRAMESIZE_5MP, "5MP"},
|
||||
};
|
||||
|
||||
uint8_t framesizeFromName(const char* name, uint8_t fallback) {
|
||||
if (!name || !name[0]) return fallback;
|
||||
for (const FsName& e : kFsNames) {
|
||||
if (strcasecmp(name, e.name) == 0) return (uint8_t)e.fs;
|
||||
}
|
||||
log_w("camera: unknown frame size '%s', keeping %s", name, framesizeName(fallback));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const char* framesizeName(uint8_t fs) {
|
||||
for (const FsName& e : kFsNames) {
|
||||
if ((uint8_t)e.fs == fs) return e.name;
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
void framesizeDims(uint8_t fs, uint16_t* w, uint16_t* h) {
|
||||
if (w) *w = 0;
|
||||
if (h) *h = 0;
|
||||
if (fs >= FRAMESIZE_INVALID) return;
|
||||
// resolution[] is the driver's own table, so these always match reality.
|
||||
if (w) *w = resolution[fs].width;
|
||||
if (h) *h = resolution[fs].height;
|
||||
}
|
||||
|
||||
static camera_config_t buildConfig() {
|
||||
camera_config_t c = {};
|
||||
c.ledc_channel = LEDC_CHANNEL_0;
|
||||
c.ledc_timer = LEDC_TIMER_0;
|
||||
c.pin_d0 = CAM_PIN_D0;
|
||||
c.pin_d1 = CAM_PIN_D1;
|
||||
c.pin_d2 = CAM_PIN_D2;
|
||||
c.pin_d3 = CAM_PIN_D3;
|
||||
c.pin_d4 = CAM_PIN_D4;
|
||||
c.pin_d5 = CAM_PIN_D5;
|
||||
c.pin_d6 = CAM_PIN_D6;
|
||||
c.pin_d7 = CAM_PIN_D7;
|
||||
c.pin_xclk = CAM_PIN_XCLK;
|
||||
c.pin_pclk = CAM_PIN_PCLK;
|
||||
c.pin_vsync = CAM_PIN_VSYNC;
|
||||
c.pin_href = CAM_PIN_HREF;
|
||||
c.pin_sccb_sda = CAM_PIN_SIOD;
|
||||
c.pin_sccb_scl = CAM_PIN_SIOC;
|
||||
c.pin_pwdn = CAM_PIN_PWDN;
|
||||
c.pin_reset = CAM_PIN_RESET;
|
||||
c.xclk_freq_hz = 20000000;
|
||||
c.pixel_format = PIXFORMAT_JPEG;
|
||||
c.frame_size = (framesize_t)g_cfg.frame_size;
|
||||
c.jpeg_quality = g_cfg.jpeg_quality;
|
||||
|
||||
// Two framebuffers in PSRAM with CAM_GRAB_LATEST: the driver keeps
|
||||
// capturing while we are busy copying the previous frame into the ring,
|
||||
// and a grab always returns the newest frame rather than a queued stale
|
||||
// one. On a trigger, "newest" is what you want.
|
||||
c.fb_location = CAMERA_FB_IN_PSRAM;
|
||||
c.fb_count = 2;
|
||||
c.grab_mode = CAMERA_GRAB_LATEST;
|
||||
return c;
|
||||
}
|
||||
|
||||
bool cameraBegin() {
|
||||
if (s_ready) return true;
|
||||
|
||||
if (!psramFound()) {
|
||||
// Without PSRAM there is no ring buffer and no SVGA framebuffer.
|
||||
// Fail loudly rather than silently running a crippled node.
|
||||
log_e("PSRAM not found — check board_build.arduino.memory_type=qio_opi");
|
||||
return false;
|
||||
}
|
||||
|
||||
camera_config_t c = buildConfig();
|
||||
esp_err_t err = esp_camera_init(&c);
|
||||
if (err != ESP_OK) {
|
||||
log_e("esp_camera_init failed: 0x%x", err);
|
||||
return false;
|
||||
}
|
||||
|
||||
s_ready = true;
|
||||
cameraApplyConfig();
|
||||
cameraDiscardFrames(3);
|
||||
|
||||
uint16_t w = 0, h = 0;
|
||||
framesizeDims(g_cfg.frame_size, &w, &h);
|
||||
sensor_t* s = esp_camera_sensor_get();
|
||||
log_i("camera ready: sensor PID 0x%04x, %s (%ux%u) quality=%u psram_free=%uKB",
|
||||
s ? s->id.PID : 0, framesizeName(g_cfg.frame_size), w, h,
|
||||
g_cfg.jpeg_quality,
|
||||
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
|
||||
return true;
|
||||
}
|
||||
|
||||
void cameraEnd() {
|
||||
if (!s_ready) return;
|
||||
esp_camera_deinit();
|
||||
s_ready = false;
|
||||
}
|
||||
|
||||
bool cameraRestart() {
|
||||
cameraEnd();
|
||||
delay(50);
|
||||
return cameraBegin();
|
||||
}
|
||||
|
||||
static bool s_night_profile = false;
|
||||
|
||||
bool cameraNightProfileActive() { return s_night_profile; }
|
||||
|
||||
// Everything the OV2640 exposes that is worth touching on a bird camera.
|
||||
// Notes on the ones that actually matter here:
|
||||
//
|
||||
// gainceiling The single most important setting for small fast birds.
|
||||
// High gain lets the sensor pick a shorter exposure in poor
|
||||
// light, but amplifies noise; low gain forces a longer
|
||||
// exposure and smears a moving bird into a streak. 4x by day
|
||||
// is a good compromise; the night profile raises it because a
|
||||
// noisy photo beats a black one.
|
||||
// exposure_ctrl Leave auto by day. Set false + aec_value to force a fixed
|
||||
// short shutter if you find motion blur is the limiting
|
||||
// factor at your feeder — that is the tuning lever.
|
||||
// ae_level Exposure bias. Birds are usually backlit against bright sky,
|
||||
// which fools metering into underexposing the bird; +1 helps.
|
||||
// lenc Lens shading correction. On, unless you are stitching.
|
||||
// colorbar Test pattern. Set true to prove the data path works before
|
||||
// you have optics or light.
|
||||
void cameraApplyTuning(bool night) {
|
||||
sensor_t* s = esp_camera_sensor_get();
|
||||
if (!s) return;
|
||||
|
||||
const CamTuning& t = night ? g_cfg.cam_night : g_cfg.cam_day;
|
||||
s_night_profile = night;
|
||||
|
||||
s->set_brightness(s, t.brightness);
|
||||
s->set_contrast(s, t.contrast);
|
||||
s->set_saturation(s, t.saturation);
|
||||
s->set_sharpness(s, t.sharpness);
|
||||
s->set_special_effect(s, t.special_effect);
|
||||
|
||||
s->set_whitebal(s, t.whitebal ? 1 : 0);
|
||||
s->set_awb_gain(s, t.awb_gain ? 1 : 0);
|
||||
s->set_wb_mode(s, t.wb_mode);
|
||||
|
||||
s->set_exposure_ctrl(s, t.exposure_ctrl ? 1 : 0);
|
||||
s->set_aec2(s, t.aec2 ? 1 : 0);
|
||||
s->set_ae_level(s, t.ae_level);
|
||||
if (!t.exposure_ctrl) s->set_aec_value(s, t.aec_value);
|
||||
|
||||
s->set_gain_ctrl(s, t.gain_ctrl ? 1 : 0);
|
||||
if (!t.gain_ctrl) s->set_agc_gain(s, t.agc_gain);
|
||||
s->set_gainceiling(s, (gainceiling_t)t.gainceiling);
|
||||
|
||||
s->set_bpc(s, t.bpc ? 1 : 0);
|
||||
s->set_wpc(s, t.wpc ? 1 : 0);
|
||||
s->set_raw_gma(s, t.raw_gma ? 1 : 0);
|
||||
s->set_lenc(s, t.lenc ? 1 : 0);
|
||||
s->set_dcw(s, t.dcw ? 1 : 0);
|
||||
s->set_colorbar(s, t.colorbar ? 1 : 0);
|
||||
|
||||
// The sensor needs a couple of frames to act on an exposure change.
|
||||
cameraDiscardFrames(2);
|
||||
|
||||
log_i("camera: %s profile applied (gainceiling=%u ae_level=%d aec=%s)",
|
||||
night ? "night" : "day", t.gainceiling, t.ae_level,
|
||||
t.exposure_ctrl ? "auto" : "manual");
|
||||
}
|
||||
|
||||
void cameraApplyConfig() {
|
||||
sensor_t* s = esp_camera_sensor_get();
|
||||
if (!s) return;
|
||||
s->set_quality(s, g_cfg.jpeg_quality);
|
||||
s->set_vflip(s, g_cfg.vflip ? 1 : 0);
|
||||
s->set_hmirror(s, g_cfg.hmirror ? 1 : 0);
|
||||
cameraApplyTuning(s_night_profile);
|
||||
}
|
||||
|
||||
bool cameraSetFrameSize(uint8_t framesize) {
|
||||
sensor_t* s = esp_camera_sensor_get();
|
||||
if (!s) return false;
|
||||
|
||||
// set_framesize refuses anything above the sensor's own maximum, which is
|
||||
// how an OV2640 (max UXGA) tells you it cannot do the QXGA an OV5640
|
||||
// would manage. Report it rather than silently keeping the old size.
|
||||
if (s->set_framesize(s, (framesize_t)framesize) != 0) {
|
||||
log_w("camera: sensor rejected frame size %s — above its maximum?",
|
||||
framesizeName(framesize));
|
||||
return false;
|
||||
}
|
||||
cameraDiscardFrames(2);
|
||||
return true;
|
||||
}
|
||||
|
||||
camera_fb_t* cameraGrab() {
|
||||
if (!s_ready) return nullptr;
|
||||
camera_fb_t* fb = esp_camera_fb_get();
|
||||
if (!fb) log_w("camera grab failed");
|
||||
return fb;
|
||||
}
|
||||
|
||||
void cameraDiscardFrames(uint8_t n) {
|
||||
for (uint8_t i = 0; i < n; i++) {
|
||||
camera_fb_t* fb = esp_camera_fb_get();
|
||||
if (fb) esp_camera_fb_return(fb);
|
||||
}
|
||||
}
|
||||
|
||||
bool cameraReady() { return s_ready; }
|
||||
@@ -0,0 +1,200 @@
|
||||
#include "commands.h"
|
||||
|
||||
#include "api_client.h"
|
||||
#include "app_config.h"
|
||||
#include "camera_mgr.h"
|
||||
#include "ota_mgr.h"
|
||||
#include "power_mgr.h"
|
||||
#include "stream_session.h"
|
||||
|
||||
// main.cpp owns the capture pipeline; this is how a command reaches it.
|
||||
extern void requestManualCapture();
|
||||
|
||||
// A deferred command, kept as a fixed-size record so the queue needs no heap.
|
||||
struct Deferred {
|
||||
bool used;
|
||||
uint32_t id;
|
||||
char type[20];
|
||||
char s_arg[64]; // session id, or firmware url
|
||||
char s_arg2[65]; // sha256
|
||||
uint32_t n_arg; // seconds, size
|
||||
uint8_t u_arg[3]; // mode, framesize, spare
|
||||
};
|
||||
|
||||
static const size_t kQueueDepth = 4;
|
||||
static Deferred s_queue[kQueueDepth] = {};
|
||||
|
||||
static bool enqueue(const Deferred& d) {
|
||||
for (size_t i = 0; i < kQueueDepth; i++) {
|
||||
if (!s_queue[i].used) { s_queue[i] = d; s_queue[i].used = true; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void commandOnReceived(JsonObjectConst cmd) {
|
||||
const uint32_t id = cmd["id"] | (uint32_t)0;
|
||||
const char* type = cmd["type"] | "";
|
||||
JsonObjectConst p = cmd["payload"];
|
||||
|
||||
log_i("cmd #%u: %s", (unsigned)id, type);
|
||||
powerNoteActivity();
|
||||
|
||||
// --- immediate, cheap ---------------------------------------------------
|
||||
|
||||
if (strcmp(type, "apply_config") == 0) {
|
||||
const bool was_sleeping = g_cfg.deep_sleep_enabled;
|
||||
const AppConfig before = g_cfg;
|
||||
|
||||
bool changed = false;
|
||||
if (!p.isNull()) {
|
||||
changed = configApplyJson(p);
|
||||
} else {
|
||||
// No inline payload: the endpoint wants us to pull the full doc.
|
||||
changed = apiFetchConfig();
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
configSave();
|
||||
cameraApplyConfig();
|
||||
powerOnConfigChanged(was_sleeping);
|
||||
if (configNeedsCameraRestart(before, g_cfg)) {
|
||||
log_i("cmd: frame size changed, restarting camera");
|
||||
cameraRestart();
|
||||
}
|
||||
}
|
||||
apiAckCommand(id, "done", changed ? "config applied" : "no change");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "capture_now") == 0) {
|
||||
requestManualCapture();
|
||||
apiAckCommand(id, "done", "capture queued");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "report_status") == 0) {
|
||||
// Deferred: we are currently inside the heartbeat's response handler,
|
||||
// and opening a second connection from here would nest HTTP clients.
|
||||
Deferred d = {};
|
||||
d.id = id;
|
||||
strncpy(d.type, "report_status", sizeof(d.type) - 1);
|
||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "wake_and_hold") == 0) {
|
||||
uint32_t secs = p["seconds"] | (uint32_t)60;
|
||||
if (secs > 900) secs = 900; // bounded, per SPEC §4.3
|
||||
powerHoldAwake(secs);
|
||||
apiAckCommand(id, "done", "holding awake");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "sleep_now") == 0) {
|
||||
// Deferred: we want the ack to reach the Pi before the radio goes off.
|
||||
Deferred d = {};
|
||||
d.id = id;
|
||||
d.n_arg = p["seconds"] | (uint32_t)0;
|
||||
strncpy(d.type, "sleep_now", sizeof(d.type) - 1);
|
||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "stream_stop") == 0) {
|
||||
streamStop("stopped by command");
|
||||
apiAckCommand(id, "done", "stream stopped");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "reboot") == 0) {
|
||||
apiAckCommand(id, "done", "rebooting");
|
||||
delay(200);
|
||||
ESP.restart();
|
||||
return;
|
||||
}
|
||||
|
||||
// --- deferred: these block, so they run from the main loop ---------------
|
||||
|
||||
if (strcmp(type, "stream_start") == 0) {
|
||||
Deferred d = {};
|
||||
d.id = id;
|
||||
strncpy(d.type, "stream_start", sizeof(d.type) - 1);
|
||||
strncpy(d.s_arg, p["session_id"] | "", sizeof(d.s_arg) - 1);
|
||||
d.n_arg = p["duration_s"] | (uint32_t)0;
|
||||
d.u_arg[0] = p["mode"] | (uint8_t)0xFF;
|
||||
d.u_arg[1] = p["frame_size"] | (uint8_t)0;
|
||||
if (!d.s_arg[0]) { apiAckCommand(id, "rejected", "no session_id"); return; }
|
||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(type, "ota_update") == 0) {
|
||||
Deferred d = {};
|
||||
d.id = id;
|
||||
strncpy(d.type, "ota_update", sizeof(d.type) - 1);
|
||||
strncpy(d.s_arg, p["url"] | "", sizeof(d.s_arg) - 1);
|
||||
strncpy(d.s_arg2, p["sha256"] | "", sizeof(d.s_arg2) - 1);
|
||||
d.n_arg = p["size"] | (uint32_t)0;
|
||||
// The version lands in s_arg's tail via the firmware envelope instead;
|
||||
// an ota_update command without a url means "use the target from the
|
||||
// envelope", which main.cpp already tracks.
|
||||
if (!enqueue(d)) apiAckCommand(id, "failed", "command queue full");
|
||||
return;
|
||||
}
|
||||
|
||||
log_w("cmd #%u: unknown type '%s'", (unsigned)id, type);
|
||||
apiAckCommand(id, "rejected", "unknown command type");
|
||||
}
|
||||
|
||||
// The firmware target from the most recent response envelope, so an
|
||||
// `ota_update` command with no explicit url still knows what to fetch.
|
||||
extern OtaTarget g_fw_target;
|
||||
|
||||
void commandRunDeferred() {
|
||||
for (size_t i = 0; i < kQueueDepth; i++) {
|
||||
if (!s_queue[i].used) continue;
|
||||
|
||||
Deferred d = s_queue[i];
|
||||
s_queue[i].used = false; // clear first: a reboot must not replay it
|
||||
|
||||
if (strcmp(d.type, "stream_start") == 0) {
|
||||
bool ok = streamStart(d.s_arg, d.u_arg[0], d.u_arg[1], (uint16_t)d.n_arg);
|
||||
apiAckCommand(d.id, ok ? "done" : "failed",
|
||||
ok ? "streaming" : "could not start stream");
|
||||
|
||||
} else if (strcmp(d.type, "ota_update") == 0) {
|
||||
OtaTarget t = g_fw_target;
|
||||
if (d.s_arg[0]) strncpy(t.url, d.s_arg, sizeof(t.url) - 1);
|
||||
if (d.s_arg2[0]) strncpy(t.sha256, d.s_arg2, sizeof(t.sha256) - 1);
|
||||
if (d.n_arg) t.size = d.n_arg;
|
||||
|
||||
if (!t.url[0]) {
|
||||
apiAckCommand(d.id, "rejected", "no firmware url");
|
||||
continue;
|
||||
}
|
||||
// Ack before flashing: otaApply() reboots on success and would
|
||||
// never get the chance to report it.
|
||||
apiAckCommand(d.id, "done", "flashing");
|
||||
if (!otaApply(t)) {
|
||||
apiAckCommand(d.id, "failed", "ota failed, still on old image");
|
||||
}
|
||||
|
||||
} else if (strcmp(d.type, "report_status") == 0) {
|
||||
bool ok = apiPostStatus("on_request");
|
||||
apiAckCommand(d.id, ok ? "done" : "failed", ok ? "status posted" : "status post failed");
|
||||
|
||||
} else if (strcmp(d.type, "sleep_now") == 0) {
|
||||
apiAckCommand(d.id, "done", "sleeping");
|
||||
powerSleepNow(d.n_arg);
|
||||
// Returns only if sleep is switched off or OTA is in flight.
|
||||
apiAckCommand(d.id, "rejected", "deep sleep is off");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool commandHasPending() {
|
||||
for (size_t i = 0; i < kQueueDepth; i++) {
|
||||
if (s_queue[i].used) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#include "device_stats.h"
|
||||
|
||||
#include <time.h>
|
||||
|
||||
#include "net_mgr.h"
|
||||
|
||||
// RTC slow memory: survives deep sleep, lost on power cycle.
|
||||
RTC_DATA_ATTR static uint16_t s_captured_today = 0;
|
||||
RTC_DATA_ATTR static uint16_t s_delivered_today = 0;
|
||||
RTC_DATA_ATTR static uint16_t s_failed_today = 0;
|
||||
RTC_DATA_ATTR static uint16_t s_events_today = 0;
|
||||
RTC_DATA_ATTR static uint32_t s_day_index = 0;
|
||||
|
||||
static uint16_t s_captured_boot = 0;
|
||||
static uint16_t s_delivered_boot = 0;
|
||||
static uint32_t s_wake_ms = 0;
|
||||
|
||||
// Days since epoch in *local* time. localtime_r honours the TZ set by
|
||||
// net_mgr, so this rolls over at local midnight rather than at UTC midnight —
|
||||
// which matters in CEST, where UTC midnight is 02:00 the next morning.
|
||||
static uint32_t localDayIndex() {
|
||||
const int64_t ms = netEpochMs();
|
||||
if (ms == 0) return 0; // unsynced: everything is "day 0"
|
||||
|
||||
time_t t = (time_t)(ms / 1000);
|
||||
struct tm lt;
|
||||
localtime_r(&t, <);
|
||||
|
||||
// mktime of local midnight, divided into days. Simpler than date maths and
|
||||
// correct across DST, because mktime resolves the offset for that date.
|
||||
struct tm midnight = lt;
|
||||
midnight.tm_hour = 0;
|
||||
midnight.tm_min = 0;
|
||||
midnight.tm_sec = 0;
|
||||
time_t m = mktime(&midnight);
|
||||
return (uint32_t)(m / 86400);
|
||||
}
|
||||
|
||||
void statsBegin() {
|
||||
s_wake_ms = millis();
|
||||
s_captured_boot = 0;
|
||||
s_delivered_boot = 0;
|
||||
statsRollover();
|
||||
}
|
||||
|
||||
void statsRollover() {
|
||||
const uint32_t today = localDayIndex();
|
||||
if (today == 0) return; // clock not yet trustworthy
|
||||
|
||||
if (today != s_day_index) {
|
||||
if (s_day_index != 0) {
|
||||
log_i("stats: new day, resetting counters (was %u captured, %u delivered)",
|
||||
s_captured_today, s_delivered_today);
|
||||
}
|
||||
s_day_index = today;
|
||||
s_captured_today = 0;
|
||||
s_delivered_today = 0;
|
||||
s_failed_today = 0;
|
||||
s_events_today = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void statsCountEvent() { statsRollover(); s_events_today++; }
|
||||
|
||||
void statsCountCaptured(uint16_t frames) {
|
||||
statsRollover();
|
||||
s_captured_today += frames;
|
||||
s_captured_boot += frames;
|
||||
}
|
||||
|
||||
void statsCountDelivered(uint16_t frames) {
|
||||
statsRollover();
|
||||
s_delivered_today += frames;
|
||||
s_delivered_boot += frames;
|
||||
}
|
||||
|
||||
void statsCountFailed(uint16_t frames) {
|
||||
statsRollover();
|
||||
s_failed_today += frames;
|
||||
}
|
||||
|
||||
DeviceStats statsGet() {
|
||||
DeviceStats s = {};
|
||||
s.captured_today = s_captured_today;
|
||||
s.delivered_today = s_delivered_today;
|
||||
s.failed_today = s_failed_today;
|
||||
s.events_today = s_events_today;
|
||||
s.day_index = s_day_index;
|
||||
s.captured_boot = s_captured_boot;
|
||||
s.delivered_boot = s_delivered_boot;
|
||||
return s;
|
||||
}
|
||||
|
||||
uint32_t statsAwakeMs() { return millis() - s_wake_ms; }
|
||||
@@ -0,0 +1,140 @@
|
||||
#include "frame_ring.h"
|
||||
|
||||
#include <esp_heap_caps.h>
|
||||
|
||||
static RingFrame* s_ring = nullptr;
|
||||
static size_t s_depth = 0;
|
||||
static size_t s_head = 0; // next slot to write
|
||||
static size_t s_count = 0;
|
||||
static uint32_t s_seq = 0;
|
||||
static SemaphoreHandle_t s_mtx = nullptr;
|
||||
|
||||
// Slots start at a plausible SVGA JPEG size and grow if a frame does not fit.
|
||||
// Growing costs one realloc; shrinking is never worth the churn.
|
||||
static const size_t kInitialSlotBytes = 48 * 1024;
|
||||
|
||||
bool ringBegin(uint8_t depth) {
|
||||
ringEnd();
|
||||
if (depth == 0) return false;
|
||||
|
||||
s_mtx = xSemaphoreCreateMutex();
|
||||
if (!s_mtx) return false;
|
||||
|
||||
s_ring = (RingFrame*)heap_caps_calloc(depth, sizeof(RingFrame), MALLOC_CAP_SPIRAM);
|
||||
if (!s_ring) {
|
||||
log_e("ring: cannot allocate slot table in PSRAM");
|
||||
vSemaphoreDelete(s_mtx);
|
||||
s_mtx = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < depth; i++) {
|
||||
s_ring[i].data = (uint8_t*)heap_caps_malloc(kInitialSlotBytes, MALLOC_CAP_SPIRAM);
|
||||
if (!s_ring[i].data) {
|
||||
log_e("ring: PSRAM exhausted at slot %u of %u", (unsigned)i, depth);
|
||||
// Run with the slots we got rather than failing outright — a
|
||||
// shallower ring is still far better than none.
|
||||
depth = i;
|
||||
break;
|
||||
}
|
||||
s_ring[i].cap = kInitialSlotBytes;
|
||||
}
|
||||
if (depth == 0) { ringEnd(); return false; }
|
||||
|
||||
s_depth = depth;
|
||||
s_head = s_count = 0;
|
||||
s_seq = 0;
|
||||
log_i("ring: %u slots x %uKB = %uKB PSRAM (free %uKB)",
|
||||
(unsigned)s_depth, (unsigned)(kInitialSlotBytes / 1024),
|
||||
(unsigned)(s_depth * kInitialSlotBytes / 1024),
|
||||
(unsigned)(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024));
|
||||
return true;
|
||||
}
|
||||
|
||||
void ringEnd() {
|
||||
if (s_mtx) xSemaphoreTake(s_mtx, portMAX_DELAY);
|
||||
if (s_ring) {
|
||||
for (size_t i = 0; i < s_depth; i++) free(s_ring[i].data);
|
||||
free(s_ring);
|
||||
s_ring = nullptr;
|
||||
}
|
||||
s_depth = s_head = s_count = 0;
|
||||
s_seq = 0;
|
||||
if (s_mtx) {
|
||||
xSemaphoreGive(s_mtx);
|
||||
vSemaphoreDelete(s_mtx);
|
||||
s_mtx = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool ringPush(const uint8_t* data, size_t len, int64_t epoch_ms) {
|
||||
if (!s_ring || !data || len == 0) return false;
|
||||
if (xSemaphoreTake(s_mtx, pdMS_TO_TICKS(100)) != pdTRUE) return false;
|
||||
|
||||
RingFrame& f = s_ring[s_head];
|
||||
|
||||
if (len > f.cap) {
|
||||
uint8_t* bigger = (uint8_t*)heap_caps_realloc(f.data, len, MALLOC_CAP_SPIRAM);
|
||||
if (!bigger) {
|
||||
xSemaphoreGive(s_mtx);
|
||||
log_w("ring: cannot grow slot to %u bytes, dropping frame", (unsigned)len);
|
||||
return false;
|
||||
}
|
||||
f.data = bigger;
|
||||
f.cap = len;
|
||||
}
|
||||
|
||||
memcpy(f.data, data, len);
|
||||
f.len = len;
|
||||
f.at_ms = millis();
|
||||
f.at_epoch = epoch_ms;
|
||||
f.seq = ++s_seq;
|
||||
|
||||
s_head = (s_head + 1) % s_depth;
|
||||
if (s_count < s_depth) s_count++;
|
||||
|
||||
xSemaphoreGive(s_mtx);
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t ringTakeNewest(size_t n, FrameCopy* out, size_t out_cap) {
|
||||
if (!s_ring || !out || out_cap == 0) return 0;
|
||||
if (xSemaphoreTake(s_mtx, pdMS_TO_TICKS(500)) != pdTRUE) return 0;
|
||||
|
||||
if (n > s_count) n = s_count;
|
||||
if (n > out_cap) n = out_cap;
|
||||
|
||||
size_t written = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
// Walk oldest-of-the-newest-n forward to newest.
|
||||
size_t back = n - i; // 1 == newest
|
||||
size_t idx = (s_head + s_depth - back) % s_depth;
|
||||
RingFrame& f = s_ring[idx];
|
||||
if (f.seq == 0 || f.len == 0) continue;
|
||||
|
||||
// Copies live in PSRAM. A ten-frame event is ~450 KB, which would
|
||||
// exhaust internal RAM and starve the WiFi stack exactly when it is
|
||||
// about to do the most work.
|
||||
uint8_t* buf = (uint8_t*)heap_caps_malloc(f.len, MALLOC_CAP_SPIRAM);
|
||||
if (!buf) {
|
||||
log_w("ring: out of memory copying frame for upload");
|
||||
break;
|
||||
}
|
||||
memcpy(buf, f.data, f.len);
|
||||
|
||||
out[written++] = FrameCopy{buf, f.len, f.seq, f.at_ms, f.at_epoch};
|
||||
}
|
||||
|
||||
xSemaphoreGive(s_mtx);
|
||||
return written;
|
||||
}
|
||||
|
||||
uint32_t ringSeq() { return s_seq; }
|
||||
size_t ringCount() { return s_count; }
|
||||
|
||||
size_t ringBytesUsed() {
|
||||
if (!s_ring) return 0;
|
||||
size_t total = 0;
|
||||
for (size_t i = 0; i < s_depth; i++) total += s_ring[i].cap;
|
||||
return total;
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
#include "ld2410.h"
|
||||
|
||||
#include <HardwareSerial.h>
|
||||
|
||||
#include "app_config.h"
|
||||
#include "board_pins.h"
|
||||
|
||||
static HardwareSerial s_uart(RADAR_UART_NUM);
|
||||
static RadarReading s_last = {};
|
||||
|
||||
// Incremental frame assembler. The radar streams continuously and we share the
|
||||
// core with the camera, so parsing has to tolerate being called late and
|
||||
// finding several frames queued in the driver buffer.
|
||||
static uint8_t s_buf[64];
|
||||
static size_t s_len = 0;
|
||||
static bool s_sync = false;
|
||||
|
||||
static const uint8_t kReportHead[4] = {0xF4, 0xF3, 0xF2, 0xF1};
|
||||
static const uint8_t kReportTail[4] = {0xF8, 0xF7, 0xF6, 0xF5};
|
||||
static const uint8_t kCmdHead[4] = {0xFD, 0xFC, 0xFB, 0xFA};
|
||||
static const uint8_t kCmdTail[4] = {0x04, 0x03, 0x02, 0x01};
|
||||
|
||||
static inline uint16_t rd16(const uint8_t* p) {
|
||||
return (uint16_t)p[0] | ((uint16_t)p[1] << 8);
|
||||
}
|
||||
|
||||
// Baud rates to probe, most likely first. The LD2410 leaves the factory at
|
||||
// 256000; 115200 is the usual choice when someone has reconfigured it.
|
||||
static const uint32_t kBaudCandidates[] = {256000, 115200, 57600, 38400, 9600};
|
||||
static uint32_t s_baud = 0;
|
||||
|
||||
uint32_t radarBaud() { return s_baud; }
|
||||
|
||||
// Open at `baud` and listen for a well-formed report frame.
|
||||
static bool tryBaud(uint32_t baud, uint32_t listen_ms) {
|
||||
s_uart.end();
|
||||
delay(20);
|
||||
s_uart.setRxBufferSize(512); // must precede begin()
|
||||
s_uart.begin(baud, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX);
|
||||
|
||||
s_len = 0;
|
||||
s_sync = false;
|
||||
memset(&s_last, 0, sizeof(s_last));
|
||||
|
||||
const uint32_t end = millis() + listen_ms;
|
||||
while ((int32_t)(end - millis()) > 0) {
|
||||
if (radarPoll()) return true; // decoded a real frame: right baud
|
||||
delay(5);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool radarBegin() {
|
||||
pinMode(PIN_RADAR_OUT, INPUT);
|
||||
|
||||
// Autodetect rather than hardcode. The module reports a few times a
|
||||
// second, so a wrong baud is obvious within a second — and detecting it
|
||||
// means a factory reset (which returns the module to 256000) does not
|
||||
// silently take the camera's trigger offline on a device you cannot
|
||||
// easily reach. Pin it with `radar_baud` if you would rather it not probe.
|
||||
if (g_cfg.radar_baud != 0) {
|
||||
if (tryBaud(g_cfg.radar_baud, 1500)) {
|
||||
s_baud = g_cfg.radar_baud;
|
||||
log_i("radar: UART%d @%u baud (pinned) rx=%d tx=%d out=%d",
|
||||
RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT);
|
||||
return true;
|
||||
}
|
||||
log_w("radar: no frames at the pinned %u baud, falling back to autodetect",
|
||||
(unsigned)g_cfg.radar_baud);
|
||||
}
|
||||
|
||||
for (uint32_t cand : kBaudCandidates) {
|
||||
if (tryBaud(cand, 900)) {
|
||||
s_baud = cand;
|
||||
log_i("radar: UART%d @%u baud (detected) rx=%d tx=%d out=%d",
|
||||
RADAR_UART_NUM, (unsigned)s_baud, PIN_RADAR_RX, PIN_RADAR_TX, PIN_RADAR_OUT);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing decoded. Leave the port open at the default so radarSelfTest()
|
||||
// can still dump raw bytes, and so the OUT pin path keeps working —
|
||||
// RADAR_OUT_PIN_ONLY mode does not need the UART at all.
|
||||
s_baud = 0;
|
||||
s_uart.end();
|
||||
delay(20);
|
||||
s_uart.setRxBufferSize(512);
|
||||
s_uart.begin(RADAR_BAUD, SERIAL_8N1, PIN_RADAR_RX, PIN_RADAR_TX);
|
||||
log_w("radar: no UART frames at any baud — check TX/RX are crossed. "
|
||||
"The OUT pin still works; radar_mode=0 uses it alone.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Decode a complete report payload (header and tail already stripped).
|
||||
static bool decodeReport(const uint8_t* p, size_t n) {
|
||||
// Basic report: 13 payload bytes. Engineering mode reports are longer and
|
||||
// start the same way, so we accept anything >= 13 and read the common head.
|
||||
if (n < 13) return false;
|
||||
if (p[0] != 0x02 || p[1] != 0xAA) return false;
|
||||
|
||||
RadarReading r = {};
|
||||
r.valid = true;
|
||||
r.target = p[2];
|
||||
r.moving_cm = rd16(&p[3]);
|
||||
r.moving_energy = p[5];
|
||||
r.stationary_cm = rd16(&p[6]);
|
||||
r.stationary_energy = p[8];
|
||||
r.detect_cm = rd16(&p[9]);
|
||||
r.at_ms = millis();
|
||||
r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
|
||||
s_last = r;
|
||||
|
||||
#ifdef PB_VERBOSE_RADAR
|
||||
log_d("radar: state=%u mov=%ucm/%u stat=%ucm/%u det=%ucm out=%d",
|
||||
r.target, r.moving_cm, r.moving_energy,
|
||||
r.stationary_cm, r.stationary_energy, r.detect_cm, r.out_pin);
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
bool radarPoll() {
|
||||
bool got = false;
|
||||
|
||||
while (s_uart.available()) {
|
||||
uint8_t b = (uint8_t)s_uart.read();
|
||||
|
||||
if (!s_sync) {
|
||||
// Slide a 4-byte window until it matches either header.
|
||||
if (s_len < 4) {
|
||||
s_buf[s_len++] = b;
|
||||
} else {
|
||||
memmove(s_buf, s_buf + 1, 3);
|
||||
s_buf[3] = b;
|
||||
}
|
||||
if (s_len == 4 &&
|
||||
(memcmp(s_buf, kReportHead, 4) == 0 || memcmp(s_buf, kCmdHead, 4) == 0)) {
|
||||
s_sync = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (s_len >= sizeof(s_buf)) { // runaway frame: resynchronise
|
||||
s_len = 0;
|
||||
s_sync = false;
|
||||
continue;
|
||||
}
|
||||
s_buf[s_len++] = b;
|
||||
|
||||
// Need header(4) + length(2) before we know how much to expect.
|
||||
if (s_len < 6) continue;
|
||||
|
||||
const uint16_t payload_len = rd16(&s_buf[4]);
|
||||
const size_t total = 4 + 2 + payload_len + 4;
|
||||
if (payload_len > sizeof(s_buf) - 10) { // implausible length
|
||||
s_len = 0;
|
||||
s_sync = false;
|
||||
continue;
|
||||
}
|
||||
if (s_len < total) continue;
|
||||
|
||||
const uint8_t* tail = &s_buf[6 + payload_len];
|
||||
const bool is_rpt = memcmp(s_buf, kReportHead, 4) == 0;
|
||||
const uint8_t* expect = is_rpt ? kReportTail : kCmdTail;
|
||||
|
||||
if (memcmp(tail, expect, 4) == 0 && is_rpt) {
|
||||
got |= decodeReport(&s_buf[6], payload_len);
|
||||
}
|
||||
// Command ACKs are consumed silently; the write helpers below poll for
|
||||
// them separately rather than routing them through this path.
|
||||
|
||||
s_len = 0;
|
||||
s_sync = false;
|
||||
}
|
||||
|
||||
// Keep the pin fresh even when the UART is silent (or absent).
|
||||
s_last.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
|
||||
return got;
|
||||
}
|
||||
|
||||
RadarReading radarLast() {
|
||||
RadarReading r = s_last;
|
||||
r.out_pin = digitalRead(PIN_RADAR_OUT) == HIGH;
|
||||
return r;
|
||||
}
|
||||
|
||||
bool radarIsTrigger(const RadarReading& r) {
|
||||
switch (g_cfg.radar_mode) {
|
||||
case RADAR_OUT_PIN_ONLY:
|
||||
return r.out_pin;
|
||||
|
||||
case RADAR_UART_ONLY:
|
||||
break; // fall through to the windowed check
|
||||
|
||||
case RADAR_BOTH:
|
||||
default:
|
||||
// The pin arms; the report has to agree. If the UART has gone
|
||||
// quiet (bad wiring, wrong baud) we would otherwise never trigger,
|
||||
// so a stale report degrades to pin-only rather than to silence.
|
||||
if (!r.out_pin) return false;
|
||||
if (!r.valid || (millis() - r.at_ms) > 3000) return true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!r.valid) return false;
|
||||
if (r.target == TARGET_NONE) return false;
|
||||
|
||||
const bool moving = (r.target == TARGET_MOVING || r.target == TARGET_BOTH);
|
||||
const bool stationary = (r.target == TARGET_STATIONARY || r.target == TARGET_BOTH);
|
||||
|
||||
if (moving &&
|
||||
r.moving_energy >= g_cfg.min_energy &&
|
||||
r.moving_cm >= g_cfg.min_distance_cm &&
|
||||
r.moving_cm <= g_cfg.max_distance_cm) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (stationary && g_cfg.accept_stationary &&
|
||||
r.stationary_energy >= g_cfg.min_energy &&
|
||||
r.stationary_cm >= g_cfg.min_distance_cm &&
|
||||
r.stationary_cm <= g_cfg.max_distance_cm) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void radarSelfTest(uint32_t duration_ms) {
|
||||
log_i("radar self-test: dumping raw UART for %u ms", duration_ms);
|
||||
const uint32_t end = millis() + duration_ms;
|
||||
size_t bytes = 0;
|
||||
uint32_t frames = 0;
|
||||
while ((int32_t)(end - millis()) > 0) {
|
||||
while (s_uart.available()) { s_uart.read(); bytes++; }
|
||||
if (radarPoll()) frames++;
|
||||
delay(5);
|
||||
}
|
||||
log_i("radar self-test: %u bytes, %u decoded frames, OUT=%d",
|
||||
(unsigned)bytes, (unsigned)frames, digitalRead(PIN_RADAR_OUT));
|
||||
if (bytes == 0) {
|
||||
log_w(" no UART data. Check TX/RX are crossed and the baud rate "
|
||||
"(factory 256000, some units ship at 115200).");
|
||||
}
|
||||
}
|
||||
|
||||
// --- command path -----------------------------------------------------------
|
||||
// Minimal: enough to raise sensitivity if the default rejects small targets.
|
||||
|
||||
static bool sendCommand(const uint8_t* payload, uint16_t len, uint32_t timeout_ms = 300) {
|
||||
uint8_t frame[32];
|
||||
if (len + 10 > sizeof(frame)) return false;
|
||||
|
||||
memcpy(frame, kCmdHead, 4);
|
||||
frame[4] = len & 0xFF;
|
||||
frame[5] = (len >> 8) & 0xFF;
|
||||
memcpy(frame + 6, payload, len);
|
||||
memcpy(frame + 6 + len, kCmdTail, 4);
|
||||
|
||||
while (s_uart.available()) s_uart.read(); // drop queued reports
|
||||
s_uart.write(frame, len + 10);
|
||||
s_uart.flush();
|
||||
|
||||
// The ACK mirrors the command word with bit 8 set. We only check that
|
||||
// *something* well-formed came back; the module is not chatty enough for
|
||||
// a mismatched ACK to be ambiguous in practice.
|
||||
const uint32_t end = millis() + timeout_ms;
|
||||
while ((int32_t)(end - millis()) > 0) {
|
||||
if (s_uart.available() >= 10) return true;
|
||||
delay(5);
|
||||
}
|
||||
log_w("radar: no ACK for command 0x%02X%02X", payload[1], payload[0]);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool radarEnterConfig() {
|
||||
const uint8_t p[] = {0xFF, 0x00, 0x01, 0x00};
|
||||
return sendCommand(p, sizeof(p));
|
||||
}
|
||||
|
||||
bool radarExitConfig() {
|
||||
const uint8_t p[] = {0xFE, 0x00};
|
||||
bool ok = sendCommand(p, sizeof(p));
|
||||
s_len = 0; s_sync = false; // report stream resumes; drop partial state
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool radarSetGateSensitivity(uint8_t gate, uint8_t moving, uint8_t stationary) {
|
||||
if (gate > 8) return false;
|
||||
// Command 0x0064: three (param-id, uint32 value) pairs.
|
||||
const uint8_t p[] = {
|
||||
0x64, 0x00,
|
||||
0x00, 0x00, gate, 0x00, 0x00, 0x00,
|
||||
0x01, 0x00, moving, 0x00, 0x00, 0x00,
|
||||
0x02, 0x00, stationary, 0x00, 0x00, 0x00,
|
||||
};
|
||||
return sendCommand(p, sizeof(p));
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
// poorBird — ESP32-S3 camera node
|
||||
//
|
||||
// Two operating modes, selected by g_cfg.deep_sleep_enabled and switchable
|
||||
// from the WebUI. See power_mgr.h for what each one costs you.
|
||||
//
|
||||
// AWAKE MODE (default, mains powered)
|
||||
// capture task (core 1) camera + PSRAM ring + stream frames
|
||||
// loop() (core 0) uploads, heartbeat, commands, OTA, sleep check
|
||||
//
|
||||
// Splitting it this way means a 3-second upload over marginal WiFi never
|
||||
// stops the ring from filling, so the pre-trigger history stays continuous
|
||||
// even while the previous event is still being sent. Exactly one task ever
|
||||
// touches the camera, which is the only threading rule esp32-camera cares
|
||||
// about.
|
||||
//
|
||||
// SLEEP MODE (battery)
|
||||
// One linear pass in setup(): wake -> capture burst -> upload -> drain
|
||||
// commands -> sleep. No tasks, no ring, no pre-trigger frames.
|
||||
//
|
||||
// Every failure path ends in sleep when sleep is on, and in a retry with
|
||||
// backoff when it is not (SPEC §4.3).
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "api_client.h"
|
||||
#include "app_config.h"
|
||||
#include "battery.h"
|
||||
#include "board_pins.h"
|
||||
#include "camera_mgr.h"
|
||||
#include "commands.h"
|
||||
#include "device_stats.h"
|
||||
#include "frame_ring.h"
|
||||
#include "ld2410.h"
|
||||
#include "net_mgr.h"
|
||||
#include "nightlight.h"
|
||||
#include "ota_mgr.h"
|
||||
#include "power_mgr.h"
|
||||
#include "stream_session.h"
|
||||
|
||||
// Firmware target from the most recent response envelope. commands.cpp reads it.
|
||||
OtaTarget g_fw_target = {};
|
||||
|
||||
// --- capture event handoff --------------------------------------------------
|
||||
struct CaptureEvent {
|
||||
uint32_t at_ms;
|
||||
const char* trigger;
|
||||
RadarReading radar;
|
||||
};
|
||||
|
||||
static QueueHandle_t s_events = nullptr;
|
||||
static TaskHandle_t s_capture_task = nullptr;
|
||||
static volatile bool s_manual_req = false;
|
||||
static uint32_t s_last_trigger_ms = 0;
|
||||
static uint32_t s_next_heartbeat_ms = 0;
|
||||
static uint32_t s_next_status_ms = 0;
|
||||
static uint32_t s_next_battery_ms = 0;
|
||||
static uint32_t s_burst_light_until_ms = 0;
|
||||
static uint8_t s_upload_failures = 0;
|
||||
|
||||
void requestManualCapture() { s_manual_req = true; }
|
||||
|
||||
static void statusLed(bool on) {
|
||||
#if STATUS_LED_ACTIVE_LOW
|
||||
digitalWrite(PIN_STATUS_LED, on ? LOW : HIGH);
|
||||
#else
|
||||
digitalWrite(PIN_STATUS_LED, on ? HIGH : LOW);
|
||||
#endif
|
||||
}
|
||||
|
||||
// A burst id the Pi can group frames by. Device uid + boot + millis is unique
|
||||
// without needing a random source or a synced clock.
|
||||
static void makeBurstId(char* out, size_t cap) {
|
||||
snprintf(out, cap, "%s-%u-%u", deviceUid(), (unsigned)powerBootCount(), (unsigned)millis());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Response handling shared by every API call
|
||||
// ---------------------------------------------------------------------------
|
||||
static void handleEnvelope(const ServerEnvelope& env) {
|
||||
if (!env.ok) return;
|
||||
|
||||
netAdoptServerTime(env.server_time_ms);
|
||||
|
||||
if (env.config_version != g_cfg.config_version) {
|
||||
log_i("config: endpoint is at v%u, we are at v%u — pulling",
|
||||
(unsigned)env.config_version, (unsigned)g_cfg.config_version);
|
||||
const bool was_sleeping = g_cfg.deep_sleep_enabled;
|
||||
const AppConfig before = g_cfg;
|
||||
if (apiFetchConfig()) {
|
||||
cameraApplyConfig();
|
||||
powerOnConfigChanged(was_sleeping);
|
||||
if (configNeedsCameraRestart(before, g_cfg)) cameraRestart();
|
||||
}
|
||||
}
|
||||
|
||||
if (env.has_firmware) {
|
||||
strncpy(g_fw_target.version, env.fw_version, sizeof(g_fw_target.version) - 1);
|
||||
strncpy(g_fw_target.url, env.fw_url, sizeof(g_fw_target.url) - 1);
|
||||
strncpy(g_fw_target.sha256, env.fw_sha256, sizeof(g_fw_target.sha256) - 1);
|
||||
g_fw_target.size = env.fw_size;
|
||||
|
||||
// The endpoint naming a different target is itself the instruction;
|
||||
// an explicit ota_update command is only needed for staged rollouts.
|
||||
if (otaIsNewer(g_fw_target) && g_cfg.ota_enabled) {
|
||||
log_i("ota: endpoint targets %s, we run %s", g_fw_target.version, FW_VERSION);
|
||||
otaApply(g_fw_target); // reboots on success
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recover from a rotated or revoked token without physical access: clear it,
|
||||
// re-enroll with the stored per-device secret, and carry on. This is why
|
||||
// enrollment does not wipe its secret — see apiEnroll().
|
||||
static bool reenrollAfterRejection() {
|
||||
log_w("auth: token rejected, re-enrolling");
|
||||
g_cfg.device_token[0] = '\0';
|
||||
configSave();
|
||||
|
||||
if (apiEnroll()) {
|
||||
log_i("auth: recovered, new token in use");
|
||||
return true;
|
||||
}
|
||||
log_e("auth: re-enrollment failed, will retry at the next check-in");
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool sendHeartbeat() {
|
||||
// A token cleared by a failed upload earlier in the loop gets replaced
|
||||
// here rather than waiting for a reboot.
|
||||
if (!g_cfg.device_token[0]) apiEnroll();
|
||||
|
||||
ServerEnvelope env = apiHeartbeat(commandOnReceived);
|
||||
|
||||
if (!env.ok && apiTokenRejected() && reenrollAfterRejection()) {
|
||||
env = apiHeartbeat(commandOnReceived); // one retry with the new token
|
||||
}
|
||||
|
||||
if (env.ok) {
|
||||
handleEnvelope(env);
|
||||
// A heartbeat the endpoint accepted proves WiFi, HTTP, auth and JSON
|
||||
// all work on this image. That is the bar for confirming a trial boot.
|
||||
otaMarkValid();
|
||||
powerRelease(INHIBIT_BOOT); // no-op after the first time
|
||||
s_upload_failures = 0;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Upload one event's worth of frames
|
||||
// ---------------------------------------------------------------------------
|
||||
static void uploadEvent(const CaptureEvent& ev, FrameCopy* frames, size_t n) {
|
||||
if (n == 0) return;
|
||||
|
||||
SleepGuard guard(INHIBIT_UPLOAD);
|
||||
statusLed(true);
|
||||
|
||||
char burst[48];
|
||||
makeBurstId(burst, sizeof(burst));
|
||||
|
||||
// pre_roll is how many of these frames predate the trigger, capped at what
|
||||
// the ring actually had.
|
||||
const size_t pre = (g_cfg.pre_roll < n) ? g_cfg.pre_roll : 0;
|
||||
|
||||
statsCountCaptured((uint16_t)n);
|
||||
|
||||
size_t sent = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
CaptureMeta meta = {};
|
||||
meta.trigger = ev.trigger;
|
||||
meta.burst_id = burst;
|
||||
meta.burst_index = (uint8_t)i;
|
||||
meta.burst_count = (uint8_t)n;
|
||||
meta.pre_trigger = (i < pre) ? 1 : 0;
|
||||
meta.radar_distance_cm = ev.radar.moving_cm ? ev.radar.moving_cm : ev.radar.stationary_cm;
|
||||
meta.radar_energy = ev.radar.moving_energy ? ev.radar.moving_energy
|
||||
: ev.radar.stationary_energy;
|
||||
meta.radar_state = ev.radar.target;
|
||||
|
||||
ServerEnvelope env = apiIngest(frames[i], meta, commandOnReceived);
|
||||
if (env.ok) {
|
||||
sent++;
|
||||
// Only the first response needs acting on; the rest of the burst
|
||||
// would just repeat the same commands.
|
||||
if (i == 0) handleEnvelope(env);
|
||||
} else if (apiTokenRejected()) {
|
||||
// Recover in place and finish the burst rather than losing the
|
||||
// whole event to a token that was rotated a second ago.
|
||||
if (reenrollAfterRejection()) {
|
||||
ServerEnvelope retry = apiIngest(frames[i], meta, commandOnReceived);
|
||||
if (retry.ok) { sent++; continue; }
|
||||
}
|
||||
log_w("auth: cannot recover mid-burst, abandoning the remaining frames");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < n; i++) free(frames[i].data);
|
||||
|
||||
statsCountDelivered((uint16_t)sent);
|
||||
statsCountFailed((uint16_t)(n - sent));
|
||||
|
||||
statusLed(false);
|
||||
log_i("event: %s, %u/%u frames uploaded (%u pre-trigger)",
|
||||
ev.trigger, (unsigned)sent, (unsigned)n, (unsigned)pre);
|
||||
|
||||
if (sent == 0) s_upload_failures++;
|
||||
else s_upload_failures = 0;
|
||||
|
||||
// Push conditions after a burst so the WebUI's delivered-today counter
|
||||
// tracks reality without waiting for the next heartbeat. /status carries
|
||||
// no command queue, so this costs one small POST and nothing else.
|
||||
if (g_cfg.status_interval_s) {
|
||||
apiPostStatus("after_event");
|
||||
s_next_status_ms = millis() + g_cfg.status_interval_s * 1000UL;
|
||||
}
|
||||
}
|
||||
|
||||
// Pull pre+post roll out of the ring and ship it. In AWAKE mode the ring is
|
||||
// still being filled by the capture task while we wait, so the post-roll
|
||||
// frames are real frames from after the trigger, not re-sent history.
|
||||
static void serviceEvent(const CaptureEvent& ev) {
|
||||
const size_t pre = g_cfg.pre_roll;
|
||||
const size_t post = g_cfg.post_roll;
|
||||
|
||||
// Let the capture task collect the post-roll before we take the slice.
|
||||
const uint32_t settle_ms = post * g_cfg.idle_period_ms;
|
||||
if (settle_ms) vTaskDelay(pdMS_TO_TICKS(settle_ms));
|
||||
|
||||
const size_t want = pre + post;
|
||||
FrameCopy frames[64];
|
||||
size_t n = ringTakeNewest(want, frames, sizeof(frames) / sizeof(frames[0]));
|
||||
if (n == 0) {
|
||||
log_w("event: ring was empty, nothing to upload");
|
||||
return;
|
||||
}
|
||||
uploadEvent(ev, frames, n);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// AWAKE MODE — capture task
|
||||
// ---------------------------------------------------------------------------
|
||||
static void captureTask(void*) {
|
||||
log_i("capture task running on core %d", xPortGetCoreID());
|
||||
|
||||
for (;;) {
|
||||
// Streaming takes over the camera entirely; the ring pauses for the
|
||||
// session. You are watching live, so history is not the point.
|
||||
if (streamActive()) {
|
||||
streamTick();
|
||||
radarPoll();
|
||||
vTaskDelay(pdMS_TO_TICKS(5));
|
||||
continue;
|
||||
}
|
||||
|
||||
radarPoll();
|
||||
RadarReading r = radarLast();
|
||||
|
||||
nightTick();
|
||||
|
||||
// NIGHT_IDLE / NIGHT_SLEEP: stop feeding the ring after dark. A manual
|
||||
// capture_now still works — an operator asking for a frame should get
|
||||
// one, dark or not.
|
||||
if (!nightCaptureAllowed() && !s_manual_req) {
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
continue;
|
||||
}
|
||||
|
||||
camera_fb_t* fb = cameraGrab();
|
||||
if (fb) {
|
||||
ringPush(fb->buf, fb->len, netEpochMs());
|
||||
esp_camera_fb_return(fb);
|
||||
}
|
||||
|
||||
const bool manual = s_manual_req;
|
||||
const bool trigger = manual || radarIsTrigger(r);
|
||||
const bool cooled = (millis() - s_last_trigger_ms) > (g_cfg.cooldown_s * 1000UL);
|
||||
|
||||
if (trigger && (cooled || manual)) {
|
||||
s_last_trigger_ms = millis();
|
||||
s_manual_req = false;
|
||||
|
||||
// NIGHTLIGHT_ON_BURST: light up and let exposure settle before the
|
||||
// post-roll frames are grabbed. Costs ~120 ms of trigger latency,
|
||||
// which is why NIGHTLIGHT_ALWAYS is the better option if you are
|
||||
// willing to run the light all night.
|
||||
nightIlluminateBurstBegin();
|
||||
|
||||
CaptureEvent ev = {millis(), manual ? "manual" : "radar", r};
|
||||
statsCountEvent();
|
||||
if (xQueueSend(s_events, &ev, 0) != pdTRUE) {
|
||||
log_w("event queue full, dropping trigger");
|
||||
} else {
|
||||
log_i("TRIGGER (%s) dist=%ucm energy=%u state=%u ring=%u",
|
||||
ev.trigger, r.moving_cm, r.moving_energy, r.target,
|
||||
(unsigned)ringCount());
|
||||
}
|
||||
// Keep the light on until the post-roll frames have been grabbed;
|
||||
// serviceEvent() takes its slice of the ring at about that point.
|
||||
s_burst_light_until_ms =
|
||||
millis() + g_cfg.post_roll * g_cfg.idle_period_ms + 300;
|
||||
|
||||
powerNoteActivity();
|
||||
}
|
||||
|
||||
if (s_burst_light_until_ms &&
|
||||
(int32_t)(s_burst_light_until_ms - millis()) <= 0) {
|
||||
s_burst_light_until_ms = 0;
|
||||
nightIlluminateBurstEnd();
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(g_cfg.idle_period_ms));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SLEEP MODE — one linear pass, then sleep
|
||||
// ---------------------------------------------------------------------------
|
||||
static void runSleepCycle() {
|
||||
log_i("=== sleep-mode wake (%s) ===", powerWakeCauseName());
|
||||
|
||||
const bool radar_wake = (powerWakeCause() == WAKE_RADAR);
|
||||
|
||||
if (radar_wake && !nightCaptureAllowed()) {
|
||||
log_i("woken by radar during the night window, not capturing");
|
||||
sendHeartbeat();
|
||||
commandRunDeferred();
|
||||
if (g_cfg.night_behaviour == NIGHT_SLEEP && !powerIsInhibited()) {
|
||||
apiPostStatus("before_night_sleep");
|
||||
powerSleepUntilMorning();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (radar_wake) {
|
||||
// No ring in this mode: the camera was off. This is SPEC C4's
|
||||
// 1-3 second latency, unavoidable without continuous capture.
|
||||
if (!cameraBegin()) {
|
||||
log_e("camera init failed, sleeping");
|
||||
powerSleepNow();
|
||||
return;
|
||||
}
|
||||
nightBegin(); // selects the day/night tuning profile for this wake
|
||||
|
||||
// A shallow ring just to reuse the same upload path. Depth = the burst
|
||||
// size; frames are grabbed back to back rather than at idle_period_ms.
|
||||
const uint8_t burst = g_cfg.post_roll ? g_cfg.post_roll : 5;
|
||||
ringBegin(burst);
|
||||
|
||||
radarPoll();
|
||||
RadarReading r = radarLast();
|
||||
statsCountEvent();
|
||||
|
||||
nightIlluminateBurstBegin();
|
||||
for (uint8_t i = 0; i < burst; i++) {
|
||||
camera_fb_t* fb = cameraGrab();
|
||||
if (fb) {
|
||||
ringPush(fb->buf, fb->len, netEpochMs());
|
||||
esp_camera_fb_return(fb);
|
||||
}
|
||||
if (g_cfg.post_roll_gap_ms) delay(g_cfg.post_roll_gap_ms);
|
||||
}
|
||||
nightIlluminateBurstEnd();
|
||||
|
||||
FrameCopy frames[64];
|
||||
size_t n = ringTakeNewest(burst, frames, sizeof(frames) / sizeof(frames[0]));
|
||||
if (n) {
|
||||
CaptureEvent ev = {millis(), "radar", r};
|
||||
// Nothing here predates the trigger, so pre_roll must not claim
|
||||
// otherwise in the metadata.
|
||||
const uint8_t saved_pre = g_cfg.pre_roll;
|
||||
g_cfg.pre_roll = 0;
|
||||
uploadEvent(ev, frames, n);
|
||||
g_cfg.pre_roll = saved_pre;
|
||||
}
|
||||
}
|
||||
|
||||
// Always check in, whatever woke us: this is how commands, config and
|
||||
// firmware targets reach a sleeping device (SPEC C1).
|
||||
sendHeartbeat();
|
||||
commandRunDeferred();
|
||||
|
||||
// A stream_start or wake_and_hold command may have just arrived. Stay up
|
||||
// and let loop() handle it; powerMaybeSleep() will put us back down.
|
||||
if (powerIsInhibited() || streamActive() || commandHasPending()) {
|
||||
log_i("sleep deferred: %s", powerInhibitSummary());
|
||||
return;
|
||||
}
|
||||
|
||||
// The endpoint may have switched sleep off in the heartbeat we just did.
|
||||
if (!g_cfg.deep_sleep_enabled) {
|
||||
log_i("deep sleep switched off by the endpoint, continuing in awake mode");
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_cfg.night_behaviour == NIGHT_SLEEP && nightIsNight()) {
|
||||
apiPostStatus("before_night_sleep");
|
||||
powerSleepUntilMorning();
|
||||
}
|
||||
|
||||
apiPostStatus("before_sleep");
|
||||
powerSleepNow();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
static void startAwakeMode() {
|
||||
if (s_capture_task) return;
|
||||
|
||||
if (!cameraBegin()) {
|
||||
log_e("camera init failed — retrying in 5 s");
|
||||
delay(5000);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
if (!ringBegin(g_cfg.ring_frames)) {
|
||||
log_w("ring buffer unavailable, running without pre-trigger history");
|
||||
}
|
||||
|
||||
nightBegin(); // after cameraBegin(): LEDC channel 0 is the camera's XCLK
|
||||
|
||||
s_events = xQueueCreate(4, sizeof(CaptureEvent));
|
||||
xTaskCreatePinnedToCore(captureTask, "capture", 6144, nullptr, 5, &s_capture_task, 1);
|
||||
log_i("awake mode: pre-trigger ring active (%u frames, ~%.1f s of history)",
|
||||
(unsigned)ringCount(), g_cfg.ring_frames * g_cfg.idle_period_ms / 1000.0f);
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(300); // let USB CDC enumerate so the boot banner is not lost
|
||||
|
||||
pinMode(PIN_STATUS_LED, OUTPUT);
|
||||
statusLed(true);
|
||||
|
||||
log_i("");
|
||||
log_i("poorBird %s (%s)", FW_VERSION, HW_REVISION);
|
||||
|
||||
powerBegin(); // first: reads the wake cause before anything resets it
|
||||
configLoad();
|
||||
otaBegin();
|
||||
statsBegin();
|
||||
configDump();
|
||||
|
||||
batteryBegin();
|
||||
otaSetBatteryCheck(batteryAboveOtaThreshold, g_cfg.battery_min_pct_ota);
|
||||
|
||||
radarBegin();
|
||||
if (powerWakeCause() == WAKE_POWER_ON) {
|
||||
// Only on a cold boot: it is noisy and pointless on every timer wake.
|
||||
radarSelfTest(2000);
|
||||
}
|
||||
|
||||
netBegin();
|
||||
apiBegin();
|
||||
|
||||
if (!netConnect()) {
|
||||
log_e("no network on boot");
|
||||
if (g_cfg.deep_sleep_enabled) powerSleepNow();
|
||||
else { delay(10000); ESP.restart(); }
|
||||
}
|
||||
|
||||
if (!apiEnroll()) {
|
||||
log_e("not enrolled — cannot talk to the endpoint");
|
||||
if (g_cfg.deep_sleep_enabled) powerSleepNow();
|
||||
else { delay(30000); ESP.restart(); }
|
||||
}
|
||||
|
||||
netSyncTime();
|
||||
|
||||
statusLed(false);
|
||||
|
||||
if (g_cfg.deep_sleep_enabled) {
|
||||
runSleepCycle();
|
||||
// Only reached if sleep was deferred or switched off.
|
||||
}
|
||||
|
||||
if (!g_cfg.deep_sleep_enabled) startAwakeMode();
|
||||
|
||||
s_next_heartbeat_ms = millis();
|
||||
s_next_status_ms = millis() + 5000;
|
||||
s_next_battery_ms = millis();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// In sleep mode with a deferred sleep, the capture task does not exist and
|
||||
// loop() is just servicing whatever held us awake.
|
||||
if (s_events) {
|
||||
CaptureEvent ev;
|
||||
while (xQueueReceive(s_events, &ev, 0) == pdTRUE) {
|
||||
if (streamActive()) {
|
||||
log_i("event dropped: a stream is running");
|
||||
continue;
|
||||
}
|
||||
serviceEvent(ev);
|
||||
}
|
||||
}
|
||||
|
||||
commandRunDeferred();
|
||||
|
||||
if ((int32_t)(s_next_heartbeat_ms - millis()) <= 0) {
|
||||
if (!netIsConnected()) netConnect();
|
||||
if (netIsConnected()) sendHeartbeat();
|
||||
|
||||
// Back off when the endpoint is unreachable so a Pi that is down for
|
||||
// an hour does not mean an hour of failed requests every 5 minutes.
|
||||
uint32_t interval = g_cfg.heartbeat_interval_s;
|
||||
if (s_upload_failures > 3) {
|
||||
uint8_t shift = s_upload_failures - 3;
|
||||
if (shift > 4) shift = 4;
|
||||
interval <<= shift;
|
||||
if (interval > 3600) interval = 3600;
|
||||
log_w("endpoint unreachable, next check-in in %us", (unsigned)interval);
|
||||
}
|
||||
s_next_heartbeat_ms = millis() + interval * 1000UL;
|
||||
}
|
||||
|
||||
// Battery is read on its own slower timer: the ADC read powers the divider
|
||||
// and averages 16 samples, so there is no point doing it per loop tick.
|
||||
if ((int32_t)(s_next_battery_ms - millis()) <= 0) {
|
||||
batteryPoll();
|
||||
s_next_battery_ms = millis() + 60000;
|
||||
}
|
||||
|
||||
// Conditions push. Distinct from the heartbeat because it carries no
|
||||
// command queue — see apiPostStatus().
|
||||
if (g_cfg.status_interval_s && (int32_t)(s_next_status_ms - millis()) <= 0) {
|
||||
if (netIsConnected()) apiPostStatus("periodic");
|
||||
s_next_status_ms = millis() + g_cfg.status_interval_s * 1000UL;
|
||||
}
|
||||
|
||||
statsRollover();
|
||||
|
||||
// Night policy. NIGHT_SLEEP overrides the deep-sleep switch: a camera with
|
||||
// no illuminator has nothing to do at 03:00 whether it is on mains or not.
|
||||
if (g_cfg.night_behaviour == NIGHT_SLEEP && nightIsNight() && !streamActive()) {
|
||||
if (netIsConnected()) apiPostStatus("before_night_sleep");
|
||||
powerSleepUntilMorning(); // does not return if it sleeps
|
||||
}
|
||||
|
||||
if (g_cfg.deep_sleep_enabled) {
|
||||
// Turning sleep on at runtime: tear the awake-mode machinery down
|
||||
// cleanly, then let powerMaybeSleep() take us under.
|
||||
if (s_capture_task) {
|
||||
log_i("deep sleep switched on, stopping capture task");
|
||||
vTaskDelete(s_capture_task);
|
||||
s_capture_task = nullptr;
|
||||
ringEnd();
|
||||
}
|
||||
// Tell the endpoint where we stand before the radio goes off. /status
|
||||
// carries no command queue, which is exactly right here: picking up a
|
||||
// command we are about to become unable to execute would just make it
|
||||
// look delivered.
|
||||
if (powerWouldSleepNow() && netIsConnected()) apiPostStatus("before_sleep");
|
||||
|
||||
powerMaybeSleep(); // does not return if it sleeps
|
||||
} else if (!s_capture_task) {
|
||||
// Sleep was switched off while we were running a sleep cycle.
|
||||
startAwakeMode();
|
||||
}
|
||||
|
||||
delay(20);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
#include "net_mgr.h"
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <esp_sntp.h>
|
||||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
|
||||
#include "app_config.h"
|
||||
|
||||
static bool s_time_valid = false;
|
||||
|
||||
// Anything before this is obviously not a real clock reading.
|
||||
static const int64_t kSaneEpochMs = 1735689600000LL; // 2025-01-01
|
||||
|
||||
bool netBegin() {
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.setSleep(true); // DTIM-based modem sleep; harmless on mains
|
||||
WiFi.setAutoReconnect(true);
|
||||
WiFi.setHostname(g_cfg.device_name);
|
||||
|
||||
setenv("TZ", g_cfg.tz, 1); // SPEC C7: set TZ explicitly, everywhere
|
||||
tzset();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool netConnect(uint8_t max_attempts) {
|
||||
if (WiFi.status() == WL_CONNECTED) return true;
|
||||
|
||||
if (!g_cfg.wifi_ssid[0]) {
|
||||
log_e("no WiFi SSID configured — set CFG_WIFI_SSID in secrets.ini");
|
||||
return false;
|
||||
}
|
||||
|
||||
for (uint8_t attempt = 1; attempt <= max_attempts; attempt++) {
|
||||
log_i("wifi: connecting to '%s' (attempt %u/%u)",
|
||||
g_cfg.wifi_ssid, attempt, max_attempts);
|
||||
|
||||
WiFi.begin(g_cfg.wifi_ssid, g_cfg.wifi_pass);
|
||||
|
||||
const uint32_t deadline = millis() + 10000;
|
||||
while (WiFi.status() != WL_CONNECTED && (int32_t)(deadline - millis()) > 0) {
|
||||
delay(100);
|
||||
}
|
||||
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
log_i("wifi: %s rssi %d dBm", WiFi.localIP().toString().c_str(), WiFi.RSSI());
|
||||
if (WiFi.RSSI() < -75) {
|
||||
// Worth surfacing: weak signal lengthens every transmit, which
|
||||
// on battery is a direct runtime cost (SPEC C5).
|
||||
log_w("wifi: RSSI %d dBm is marginal at this mounting point", WiFi.RSSI());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
WiFi.disconnect(true, false);
|
||||
// Exponential backoff, bounded. Never a tight retry loop (SPEC §4.3).
|
||||
if (attempt < max_attempts) delay(1000UL << attempt);
|
||||
}
|
||||
|
||||
log_w("wifi: giving up after %u attempts", max_attempts);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool netIsConnected() { return WiFi.status() == WL_CONNECTED; }
|
||||
|
||||
void netDisconnect() {
|
||||
WiFi.disconnect(true, false);
|
||||
WiFi.mode(WIFI_OFF);
|
||||
}
|
||||
|
||||
bool netSyncTime(uint32_t timeout_ms) {
|
||||
const char* host = g_cfg.ntp_host[0] ? g_cfg.ntp_host : g_cfg.api_host;
|
||||
log_i("time: SNTP against %s", host);
|
||||
|
||||
esp_sntp_stop();
|
||||
esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);
|
||||
esp_sntp_setservername(0, host);
|
||||
esp_sntp_init();
|
||||
|
||||
const uint32_t deadline = millis() + timeout_ms;
|
||||
while ((int32_t)(deadline - millis()) > 0) {
|
||||
if (esp_sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED || netEpochMs() > kSaneEpochMs) {
|
||||
s_time_valid = true;
|
||||
char iso[32];
|
||||
netIsoTime(iso, sizeof(iso));
|
||||
log_i("time: synced, %s", iso);
|
||||
return true;
|
||||
}
|
||||
delay(100);
|
||||
}
|
||||
|
||||
// Not fatal. The next ingest/heartbeat response will carry server_time and
|
||||
// netAdoptServerTime() picks it up from there.
|
||||
log_w("time: SNTP did not complete, falling back to the API response clock");
|
||||
return false;
|
||||
}
|
||||
|
||||
void netAdoptServerTime(int64_t server_ms) {
|
||||
if (server_ms < kSaneEpochMs) return;
|
||||
|
||||
const int64_t now = netEpochMs();
|
||||
const int64_t drift = (now > server_ms) ? (now - server_ms) : (server_ms - now);
|
||||
|
||||
if (s_time_valid && drift < 2000) return; // within tolerance, leave it
|
||||
|
||||
struct timeval tv = {
|
||||
.tv_sec = (time_t)(server_ms / 1000),
|
||||
.tv_usec = (suseconds_t)((server_ms % 1000) * 1000),
|
||||
};
|
||||
settimeofday(&tv, nullptr);
|
||||
s_time_valid = true;
|
||||
|
||||
char iso[32];
|
||||
netIsoTime(iso, sizeof(iso));
|
||||
log_i("time: adopted endpoint clock (%s, drift was %lld ms)", iso, (long long)drift);
|
||||
}
|
||||
|
||||
int64_t netEpochMs() {
|
||||
struct timeval tv;
|
||||
if (gettimeofday(&tv, nullptr) != 0) return 0;
|
||||
int64_t ms = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
|
||||
return (ms > kSaneEpochMs) ? ms : 0;
|
||||
}
|
||||
|
||||
bool netTimeValid() { return s_time_valid && netEpochMs() > 0; }
|
||||
|
||||
void netIsoTime(char* out, size_t cap) {
|
||||
if (!cap) return;
|
||||
out[0] = '\0';
|
||||
int64_t ms = netEpochMs();
|
||||
if (ms == 0) return;
|
||||
time_t t = (time_t)(ms / 1000);
|
||||
struct tm gm;
|
||||
gmtime_r(&t, &gm);
|
||||
strftime(out, cap, "%Y-%m-%dT%H:%M:%SZ", &gm);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
#include "nightlight.h"
|
||||
|
||||
#include <time.h>
|
||||
|
||||
#include "app_config.h"
|
||||
#include "board_pins.h"
|
||||
#include "camera_mgr.h"
|
||||
#include "net_mgr.h"
|
||||
|
||||
static bool s_led_on = false;
|
||||
static bool s_was_night = false;
|
||||
static bool s_pwm_ready = false;
|
||||
|
||||
static const uint32_t kPwmFreq = 5000;
|
||||
static const uint8_t kPwmBits = 8;
|
||||
|
||||
static void ledSet(bool on, uint8_t duty) {
|
||||
#if PIN_NIGHTLIGHT >= 0
|
||||
if (!s_pwm_ready) return;
|
||||
ledcWrite(PIN_NIGHTLIGHT, on ? duty : 0);
|
||||
s_led_on = on;
|
||||
#else
|
||||
(void)on; (void)duty;
|
||||
#endif
|
||||
}
|
||||
|
||||
void nightBegin() {
|
||||
#if PIN_NIGHTLIGHT >= 0
|
||||
// ledcAttach picks a free LEDC channel. The camera driver has already
|
||||
// taken channel 0 / timer 0 for XCLK by this point, so call nightBegin()
|
||||
// after cameraBegin() and let the allocator route around it.
|
||||
s_pwm_ready = ledcAttach(PIN_NIGHTLIGHT, kPwmFreq, kPwmBits);
|
||||
if (!s_pwm_ready) {
|
||||
log_e("nightlight: LEDC attach failed on GPIO%d (channel exhausted?)", PIN_NIGHTLIGHT);
|
||||
} else {
|
||||
ledcWrite(PIN_NIGHTLIGHT, 0);
|
||||
log_i("nightlight: PWM on GPIO%d", PIN_NIGHTLIGHT);
|
||||
}
|
||||
#else
|
||||
log_i("nightlight: no LED pin configured");
|
||||
#endif
|
||||
s_was_night = nightIsNight();
|
||||
cameraApplyTuning(s_was_night);
|
||||
}
|
||||
|
||||
bool nightIsNight() {
|
||||
if (!netTimeValid()) return false;
|
||||
|
||||
const int64_t ms = netEpochMs();
|
||||
if (ms == 0) return false;
|
||||
|
||||
time_t t = (time_t)(ms / 1000);
|
||||
struct tm lt;
|
||||
localtime_r(&t, <);
|
||||
const uint16_t now_min = lt.tm_hour * 60 + lt.tm_min;
|
||||
|
||||
const uint16_t start = g_cfg.night_start_min;
|
||||
const uint16_t end = g_cfg.night_end_min;
|
||||
if (start == end) return false; // window disabled
|
||||
|
||||
// The normal case wraps midnight (21:00 -> 06:00); the non-wrapping case
|
||||
// is only reachable from a deliberately odd config, but costs one branch.
|
||||
return (start > end) ? (now_min >= start || now_min < end)
|
||||
: (now_min >= start && now_min < end);
|
||||
}
|
||||
|
||||
uint32_t nightSecondsUntilMorning() {
|
||||
if (!nightIsNight()) return 0;
|
||||
|
||||
const int64_t ms = netEpochMs();
|
||||
time_t t = (time_t)(ms / 1000);
|
||||
struct tm lt;
|
||||
localtime_r(&t, <);
|
||||
const int32_t now_s = lt.tm_hour * 3600 + lt.tm_min * 60 + lt.tm_sec;
|
||||
const int32_t end_s = (int32_t)g_cfg.night_end_min * 60;
|
||||
|
||||
int32_t delta = end_s - now_s;
|
||||
if (delta <= 0) delta += 86400; // morning is tomorrow
|
||||
|
||||
// Wake a minute early: the first frames after a long sleep are throwaway
|
||||
// while auto-exposure settles, and being late for dawn is worse than
|
||||
// being early for it.
|
||||
if (delta > 60) delta -= 60;
|
||||
return (uint32_t)delta;
|
||||
}
|
||||
|
||||
bool nightCaptureAllowed() {
|
||||
if (!nightIsNight()) return true;
|
||||
return g_cfg.night_behaviour == NIGHT_CAPTURE;
|
||||
}
|
||||
|
||||
bool nightlightIsOn() { return s_led_on; }
|
||||
|
||||
void nightTick() {
|
||||
const bool is_night = nightIsNight();
|
||||
|
||||
if (is_night != s_was_night) {
|
||||
log_i("night: %s", is_night ? "dusk — switching to the night profile"
|
||||
: "dawn — back to the day profile");
|
||||
s_was_night = is_night;
|
||||
cameraApplyTuning(is_night);
|
||||
}
|
||||
|
||||
// NIGHTLIGHT_ALWAYS keeps the illuminator on for the whole night. Steady
|
||||
// light is easier on wildlife than a burst per trigger, and it also means
|
||||
// auto-exposure is already settled when a bird arrives.
|
||||
const bool want_on = is_night &&
|
||||
g_cfg.nightlight_mode == NIGHTLIGHT_ALWAYS &&
|
||||
g_cfg.night_behaviour == NIGHT_CAPTURE;
|
||||
|
||||
if (want_on != s_led_on) ledSet(want_on, g_cfg.nightlight_brightness);
|
||||
}
|
||||
|
||||
void nightIlluminateBurstBegin() {
|
||||
if (!nightIsNight()) return;
|
||||
if (g_cfg.nightlight_mode != NIGHTLIGHT_ON_BURST) return;
|
||||
if (g_cfg.night_behaviour != NIGHT_CAPTURE) return;
|
||||
|
||||
ledSet(true, g_cfg.nightlight_brightness);
|
||||
// Auto-exposure needs a moment to react to the light appearing. Without
|
||||
// this the first frames of the burst are the blown-out ones.
|
||||
delay(120);
|
||||
cameraDiscardFrames(2);
|
||||
}
|
||||
|
||||
void nightIlluminateBurstEnd() {
|
||||
if (g_cfg.nightlight_mode != NIGHTLIGHT_ON_BURST) return;
|
||||
ledSet(false, 0);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
#include "ota_mgr.h"
|
||||
|
||||
#include <esp_http_client.h>
|
||||
#include <esp_ota_ops.h>
|
||||
#include <esp_partition.h>
|
||||
#include <mbedtls/sha256.h>
|
||||
#include <strings.h> // strcasecmp
|
||||
|
||||
#include "app_config.h"
|
||||
#include "power_mgr.h"
|
||||
|
||||
static bool s_pending_verify = false;
|
||||
static OtaBatteryOkFn s_battery_fn = nullptr;
|
||||
static uint8_t s_battery_min = 50;
|
||||
|
||||
void otaBegin() {
|
||||
const esp_partition_t* running = esp_ota_get_running_partition();
|
||||
esp_ota_img_states_t state;
|
||||
|
||||
if (esp_ota_get_state_partition(running, &state) == ESP_OK) {
|
||||
s_pending_verify = (state == ESP_OTA_IMG_PENDING_VERIFY);
|
||||
}
|
||||
|
||||
log_i("ota: running %s from %s%s", FW_VERSION, running->label,
|
||||
s_pending_verify ? " [TRIAL BOOT - unconfirmed]" : "");
|
||||
}
|
||||
|
||||
bool otaPendingVerify() { return s_pending_verify; }
|
||||
|
||||
void otaMarkValid() {
|
||||
if (!s_pending_verify) return;
|
||||
if (esp_ota_mark_app_valid_cancel_rollback() == ESP_OK) {
|
||||
s_pending_verify = false;
|
||||
log_i("ota: trial image confirmed good, rollback cancelled");
|
||||
} else {
|
||||
log_e("ota: failed to confirm trial image");
|
||||
}
|
||||
}
|
||||
|
||||
void otaRollback(const char* reason) {
|
||||
log_e("ota: rolling back — %s", reason);
|
||||
delay(200);
|
||||
esp_ota_mark_app_invalid_rollback_and_reboot();
|
||||
}
|
||||
|
||||
bool otaIsNewer(const OtaTarget& t) {
|
||||
// Deliberately a string inequality, not a semver comparison: the endpoint
|
||||
// decides which version a device should run (SPEC §3 `firmware.is_target`),
|
||||
// so "different from target" is the correct trigger. That also makes
|
||||
// deliberate downgrades work, which semver ordering would block.
|
||||
return t.version[0] && strcmp(t.version, FW_VERSION) != 0;
|
||||
}
|
||||
|
||||
void otaSetBatteryCheck(OtaBatteryOkFn fn, uint8_t min_pct) {
|
||||
s_battery_fn = fn;
|
||||
s_battery_min = min_pct;
|
||||
}
|
||||
|
||||
static bool hexEq(const uint8_t* digest, const char* expect_hex) {
|
||||
char hex[65];
|
||||
for (int i = 0; i < 32; i++) snprintf(hex + i * 2, 3, "%02x", digest[i]);
|
||||
hex[64] = '\0';
|
||||
return strcasecmp(hex, expect_hex) == 0;
|
||||
}
|
||||
|
||||
bool otaApply(const OtaTarget& t) {
|
||||
if (!g_cfg.ota_enabled) {
|
||||
log_w("ota: disabled in config, ignoring target %s", t.version);
|
||||
return false;
|
||||
}
|
||||
|
||||
// SPEC C6: a brownout mid-write bricks the device.
|
||||
if (s_battery_fn && !s_battery_fn(s_battery_min)) {
|
||||
log_w("ota: refused, battery below %u%%", s_battery_min);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (strlen(t.sha256) != 64) {
|
||||
log_e("ota: refused, target has no usable SHA-256");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Never sleep while flashing.
|
||||
SleepGuard guard(INHIBIT_OTA);
|
||||
|
||||
String url = (strncmp(t.url, "http", 4) == 0) ? String(t.url) : (apiBaseUrl() + t.url);
|
||||
log_i("ota: %s -> %s (%u bytes) from %s", FW_VERSION, t.version, (unsigned)t.size, url.c_str());
|
||||
|
||||
esp_http_client_config_t cfg = {};
|
||||
cfg.url = url.c_str();
|
||||
cfg.method = HTTP_METHOD_GET;
|
||||
cfg.timeout_ms = 30000;
|
||||
|
||||
esp_http_client_handle_t c = esp_http_client_init(&cfg);
|
||||
char bearer[80];
|
||||
snprintf(bearer, sizeof(bearer), "Bearer %s", g_cfg.device_token);
|
||||
esp_http_client_set_header(c, "Authorization", bearer);
|
||||
|
||||
bool ok = false;
|
||||
esp_ota_handle_t ota = 0;
|
||||
const esp_partition_t* target_part = nullptr;
|
||||
mbedtls_sha256_context sha;
|
||||
mbedtls_sha256_init(&sha);
|
||||
|
||||
do {
|
||||
if (esp_http_client_open(c, 0) != ESP_OK) { log_e("ota: connect failed"); break; }
|
||||
|
||||
int content_len = esp_http_client_fetch_headers(c);
|
||||
int status = esp_http_client_get_status_code(c);
|
||||
if (status != 200) { log_e("ota: HTTP %d", status); break; }
|
||||
if (content_len <= 0) {
|
||||
// Chunked responses are legal but we want the length to sanity
|
||||
// check against the manifest before erasing a partition.
|
||||
log_e("ota: server did not send Content-Length");
|
||||
break;
|
||||
}
|
||||
if (t.size && (uint32_t)content_len != t.size) {
|
||||
log_e("ota: size mismatch, manifest %u vs body %d", (unsigned)t.size, content_len);
|
||||
break;
|
||||
}
|
||||
|
||||
target_part = esp_ota_get_next_update_partition(nullptr);
|
||||
if (!target_part) { log_e("ota: no free OTA slot"); break; }
|
||||
if ((uint32_t)content_len > target_part->size) {
|
||||
log_e("ota: image %d does not fit in %s (%u)", content_len,
|
||||
target_part->label, (unsigned)target_part->size);
|
||||
break;
|
||||
}
|
||||
|
||||
log_i("ota: erasing %s", target_part->label);
|
||||
if (esp_ota_begin(target_part, content_len, &ota) != ESP_OK) {
|
||||
log_e("ota: esp_ota_begin failed");
|
||||
ota = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
mbedtls_sha256_starts(&sha, 0);
|
||||
|
||||
static uint8_t buf[4096];
|
||||
int written = 0, last_pct = -10;
|
||||
bool io_error = false;
|
||||
|
||||
while (written < content_len) {
|
||||
int n = esp_http_client_read(c, (char*)buf, sizeof(buf));
|
||||
if (n <= 0) { log_e("ota: download truncated at %d/%d", written, content_len); io_error = true; break; }
|
||||
|
||||
if (esp_ota_write(ota, buf, n) != ESP_OK) { log_e("ota: flash write failed"); io_error = true; break; }
|
||||
mbedtls_sha256_update(&sha, buf, n);
|
||||
written += n;
|
||||
|
||||
int pct = (int)((int64_t)written * 100 / content_len);
|
||||
if (pct >= last_pct + 10) { log_i("ota: %d%%", pct); last_pct = pct; }
|
||||
}
|
||||
if (io_error) break;
|
||||
|
||||
uint8_t digest[32];
|
||||
mbedtls_sha256_finish(&sha, digest);
|
||||
if (!hexEq(digest, t.sha256)) {
|
||||
log_e("ota: SHA-256 mismatch, discarding image");
|
||||
break;
|
||||
}
|
||||
log_i("ota: SHA-256 verified");
|
||||
|
||||
if (esp_ota_end(ota) != ESP_OK) { log_e("ota: esp_ota_end failed"); ota = 0; break; }
|
||||
ota = 0;
|
||||
|
||||
if (esp_ota_set_boot_partition(target_part) != ESP_OK) {
|
||||
log_e("ota: set_boot_partition failed");
|
||||
break;
|
||||
}
|
||||
ok = true;
|
||||
} while (false);
|
||||
|
||||
if (ota) esp_ota_abort(ota);
|
||||
mbedtls_sha256_free(&sha);
|
||||
esp_http_client_close(c);
|
||||
esp_http_client_cleanup(c);
|
||||
|
||||
if (ok) {
|
||||
// The new image boots in PENDING_VERIFY. If it cannot reach the
|
||||
// endpoint it never calls otaMarkValid(), and the next reset returns
|
||||
// to this slot automatically.
|
||||
log_i("ota: activated %s, restarting into trial boot", target_part->label);
|
||||
delay(300);
|
||||
esp_restart();
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
const char* otaRunningVersion() { return FW_VERSION; }
|
||||
const char* otaRunningPartition() { return esp_ota_get_running_partition()->label; }
|
||||
@@ -0,0 +1,247 @@
|
||||
#include "power_mgr.h"
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <esp_sleep.h>
|
||||
|
||||
#include "app_config.h"
|
||||
#include "board_pins.h"
|
||||
#include "camera_mgr.h"
|
||||
#include "nightlight.h"
|
||||
#include "stream_session.h"
|
||||
|
||||
// RTC slow memory survives deep sleep but not a power cycle — exactly the
|
||||
// semantics SPEC C7 assumes for the boot counter.
|
||||
RTC_DATA_ATTR static uint32_t s_boot_count = 0;
|
||||
RTC_DATA_ATTR static uint32_t s_sleep_epoch = 0; // seconds slept, cumulative
|
||||
RTC_DATA_ATTR static uint32_t s_last_sleep_s = 0; // duration of the last sleep
|
||||
|
||||
static WakeCause s_cause = WAKE_POWER_ON;
|
||||
static uint8_t s_inhibit[INHIBIT_COUNT] = {0};
|
||||
static uint32_t s_last_activity_ms = 0;
|
||||
static uint32_t s_awake_since_ms = 0;
|
||||
static uint32_t s_hold_until_ms = 0;
|
||||
|
||||
static const char* kInhibitNames[INHIBIT_COUNT] = {
|
||||
"boot", "upload", "stream", "ota", "hold"
|
||||
};
|
||||
|
||||
void powerBegin() {
|
||||
s_boot_count++;
|
||||
s_awake_since_ms = millis();
|
||||
s_last_activity_ms = millis();
|
||||
|
||||
switch (esp_sleep_get_wakeup_cause()) {
|
||||
case ESP_SLEEP_WAKEUP_EXT1: s_cause = WAKE_RADAR; break;
|
||||
case ESP_SLEEP_WAKEUP_TIMER: s_cause = WAKE_TIMER; break;
|
||||
case ESP_SLEEP_WAKEUP_UNDEFINED: s_cause = WAKE_POWER_ON; break;
|
||||
default: s_cause = WAKE_OTHER; break;
|
||||
}
|
||||
|
||||
// Hold the device awake until the first successful check-in. Without this
|
||||
// a device configured with a bad endpoint would sleep before it could ever
|
||||
// be told otherwise, and the only fix would be USB.
|
||||
memset(s_inhibit, 0, sizeof(s_inhibit));
|
||||
powerInhibit(INHIBIT_BOOT);
|
||||
|
||||
log_i("power: boot #%u, wake cause %s, %us slept so far",
|
||||
(unsigned)s_boot_count, powerWakeCauseName(), (unsigned)s_sleep_epoch);
|
||||
}
|
||||
|
||||
WakeCause powerWakeCause() { return s_cause; }
|
||||
uint32_t powerBootCount() { return s_boot_count; }
|
||||
uint32_t powerLastSleepSeconds() { return s_last_sleep_s; }
|
||||
uint32_t powerTotalSleepSeconds() { return s_sleep_epoch; }
|
||||
|
||||
const char* powerWakeCauseName() {
|
||||
switch (s_cause) {
|
||||
case WAKE_RADAR: return "radar";
|
||||
case WAKE_TIMER: return "timer";
|
||||
case WAKE_POWER_ON: return "power-on";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
void powerInhibit(SleepInhibit r) {
|
||||
if (r < INHIBIT_COUNT && s_inhibit[r] < 255) s_inhibit[r]++;
|
||||
}
|
||||
|
||||
void powerRelease(SleepInhibit r) {
|
||||
if (r < INHIBIT_COUNT && s_inhibit[r] > 0) s_inhibit[r]--;
|
||||
}
|
||||
|
||||
bool powerIsInhibited() {
|
||||
for (uint8_t i = 0; i < INHIBIT_COUNT; i++) {
|
||||
if (s_inhibit[i]) return true;
|
||||
}
|
||||
return (int32_t)(s_hold_until_ms - millis()) > 0;
|
||||
}
|
||||
|
||||
const char* powerInhibitSummary() {
|
||||
static char buf[64];
|
||||
buf[0] = '\0';
|
||||
for (uint8_t i = 0; i < INHIBIT_COUNT; i++) {
|
||||
if (!s_inhibit[i]) continue;
|
||||
if (buf[0]) strncat(buf, ",", sizeof(buf) - strlen(buf) - 1);
|
||||
strncat(buf, kInhibitNames[i], sizeof(buf) - strlen(buf) - 1);
|
||||
}
|
||||
if (!buf[0]) strncpy(buf, "none", sizeof(buf));
|
||||
return buf;
|
||||
}
|
||||
|
||||
void powerNoteActivity() { s_last_activity_ms = millis(); }
|
||||
|
||||
void powerHoldAwake(uint32_t seconds) {
|
||||
uint32_t until = millis() + seconds * 1000UL;
|
||||
if ((int32_t)(until - s_hold_until_ms) > 0) s_hold_until_ms = until;
|
||||
powerNoteActivity();
|
||||
log_i("power: holding awake for %us", (unsigned)seconds);
|
||||
}
|
||||
|
||||
bool powerSleepModeActive() { return g_cfg.deep_sleep_enabled; }
|
||||
|
||||
const char* powerSleepBlockedReason() {
|
||||
if (!g_cfg.deep_sleep_enabled) return "deep sleep switched off";
|
||||
if (g_cfg.stream_enabled && g_cfg.stream_blocks_sleep)
|
||||
return "streaming enabled (stream_blocks_sleep)";
|
||||
if (powerIsInhibited()) return powerInhibitSummary();
|
||||
return "";
|
||||
}
|
||||
|
||||
bool powerSleepAllowed() { return powerSleepBlockedReason()[0] == '\0'; }
|
||||
|
||||
// Configure wake sources and go. Does not return.
|
||||
// `wake_on_radar` is separate from the config flag so the night sleep can
|
||||
// force it off without mutating config.
|
||||
static void enterDeepSleep(uint32_t seconds, bool wake_on_radar) {
|
||||
if (seconds == 0) seconds = g_cfg.deep_sleep_s;
|
||||
|
||||
log_i("power: sleeping %us (wake: timer%s)", (unsigned)seconds,
|
||||
wake_on_radar ? " + radar" : "");
|
||||
|
||||
// Flush the camera and radio explicitly. Letting deep sleep cut power out
|
||||
// from under an initialised camera has been a reliable source of failures
|
||||
// to re-init on the next boot.
|
||||
cameraEnd();
|
||||
WiFi.disconnect(true, /*eraseap=*/false);
|
||||
WiFi.mode(WIFI_OFF);
|
||||
delay(20);
|
||||
|
||||
esp_sleep_enable_timer_wakeup((uint64_t)seconds * 1000000ULL);
|
||||
|
||||
if (wake_on_radar) {
|
||||
// ESP32-S3 has no EXT0; EXT1 with ANY_HIGH is the supported way to
|
||||
// wake on an active-high presence pin. PIN_RADAR_OUT must be an RTC
|
||||
// GPIO (0-21 on the S3) — GPIO3 is.
|
||||
esp_sleep_enable_ext1_wakeup(1ULL << PIN_RADAR_OUT, ESP_EXT1_WAKEUP_ANY_HIGH);
|
||||
|
||||
// If the radar is *already* asserting when we try to sleep we would
|
||||
// wake instantly and spin. Wait briefly for it to clear; if it does
|
||||
// not, drop to a timer-only sleep for this cycle.
|
||||
uint32_t wait_until = millis() + 3000;
|
||||
while (digitalRead(PIN_RADAR_OUT) == HIGH && (int32_t)(wait_until - millis()) > 0) {
|
||||
delay(50);
|
||||
}
|
||||
if (digitalRead(PIN_RADAR_OUT) == HIGH) {
|
||||
log_w("power: radar still asserted, sleeping on timer only this cycle");
|
||||
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_EXT1);
|
||||
}
|
||||
}
|
||||
|
||||
s_sleep_epoch += seconds;
|
||||
s_last_sleep_s = seconds;
|
||||
Serial.flush();
|
||||
esp_deep_sleep_start();
|
||||
// unreachable
|
||||
}
|
||||
|
||||
void powerSleepUntilMorning() {
|
||||
const uint32_t secs = nightSecondsUntilMorning();
|
||||
if (secs == 0) return; // not night, or clock unsynced
|
||||
|
||||
// Night sleep overrides the deep_sleep_enabled switch, but never an OTA.
|
||||
if (s_inhibit[INHIBIT_OTA]) {
|
||||
log_w("power: night sleep deferred, OTA in progress");
|
||||
return;
|
||||
}
|
||||
if (streamActive()) {
|
||||
log_i("power: night sleep deferred, a stream is running");
|
||||
return;
|
||||
}
|
||||
|
||||
log_i("power: night — sleeping %u min until morning", (unsigned)(secs / 60));
|
||||
enterDeepSleep(secs, /*wake_on_radar=*/false);
|
||||
}
|
||||
|
||||
bool powerWouldSleepNow() {
|
||||
if (!powerSleepAllowed()) return false;
|
||||
return (millis() - s_last_activity_ms) >= g_cfg.sleep_idle_timeout_s * 1000UL;
|
||||
}
|
||||
|
||||
bool powerMaybeSleep() {
|
||||
if (!g_cfg.deep_sleep_enabled) return false;
|
||||
|
||||
const uint32_t now = millis();
|
||||
const uint32_t idle_ms = now - s_last_activity_ms;
|
||||
const uint32_t awake_ms = now - s_awake_since_ms;
|
||||
|
||||
// The hard cap is a deadlock escape, not a normal path: if something holds
|
||||
// an inhibit forever (a stream whose socket never closes, an OTA that
|
||||
// stalled) the device would otherwise stay awake until the battery is flat.
|
||||
// OTA is the one inhibit we never override — sleeping mid-flash bricks it.
|
||||
if (awake_ms > g_cfg.sleep_max_awake_s * 1000UL) {
|
||||
if (s_inhibit[INHIBIT_OTA]) {
|
||||
log_w("power: past max_awake but OTA in progress, staying up");
|
||||
return false;
|
||||
}
|
||||
log_w("power: max_awake %us exceeded (inhibits: %s), sleeping anyway",
|
||||
g_cfg.sleep_max_awake_s, powerInhibitSummary());
|
||||
enterDeepSleep(0, g_cfg.sleep_wake_on_radar);
|
||||
}
|
||||
|
||||
// Streaming enabled means "keep me reachable", not just "a session is
|
||||
// running" — a sleeping device cannot be told to start one (SPEC C1).
|
||||
if (!powerSleepAllowed()) return false;
|
||||
if (idle_ms < g_cfg.sleep_idle_timeout_s * 1000UL) return false;
|
||||
|
||||
enterDeepSleep(0, g_cfg.sleep_wake_on_radar);
|
||||
return true; // unreachable
|
||||
}
|
||||
|
||||
void powerSleepNow(uint32_t seconds) {
|
||||
// Deliberately laxer than powerSleepAllowed(): an explicit sleep request
|
||||
// overrides "streaming is enabled" and the boot hold, because something
|
||||
// asked for it on purpose. It does NOT override an OTA (bricks the device)
|
||||
// or a live stream (cutting a viewer off mid-frame is never what was meant
|
||||
// — send stream_stop first).
|
||||
if (!g_cfg.deep_sleep_enabled) {
|
||||
log_w("power: sleep_now ignored, deep sleep is switched off");
|
||||
return;
|
||||
}
|
||||
if (s_inhibit[INHIBIT_OTA]) {
|
||||
log_w("power: sleep_now refused, OTA in progress");
|
||||
return;
|
||||
}
|
||||
if (streamActive()) {
|
||||
log_w("power: sleep_now refused, a stream is running");
|
||||
return;
|
||||
}
|
||||
enterDeepSleep(seconds, g_cfg.sleep_wake_on_radar);
|
||||
}
|
||||
|
||||
void powerOnConfigChanged(bool was_enabled) {
|
||||
if (was_enabled == g_cfg.deep_sleep_enabled) return;
|
||||
|
||||
if (g_cfg.deep_sleep_enabled) {
|
||||
// Do not slam the door on the way out: finish this wake so the ack for
|
||||
// the config command reaches the Pi, and so an operator who flipped the
|
||||
// switch by mistake still has sleep_idle_timeout_s to flip it back.
|
||||
log_i("power: deep sleep switched ON, will sleep after %us idle",
|
||||
g_cfg.sleep_idle_timeout_s);
|
||||
powerNoteActivity();
|
||||
} else {
|
||||
log_i("power: deep sleep switched OFF, staying awake");
|
||||
s_hold_until_ms = 0;
|
||||
// The ring and camera are brought back up by the caller in main.cpp,
|
||||
// which owns their lifecycle.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
#include "stream_session.h"
|
||||
|
||||
#include "api_client.h"
|
||||
#include "app_config.h"
|
||||
#include "camera_mgr.h"
|
||||
#include "net_mgr.h"
|
||||
#include "power_mgr.h"
|
||||
|
||||
static bool s_active = false;
|
||||
static char s_id[40] = {0};
|
||||
static uint32_t s_end_ms = 0;
|
||||
static uint32_t s_next_ms = 0;
|
||||
static uint32_t s_period_ms = 100;
|
||||
static uint32_t s_frames = 0;
|
||||
static uint8_t s_prev_size = 0;
|
||||
static uint8_t s_fail_streak = 0;
|
||||
|
||||
bool streamActive() { return s_active; }
|
||||
|
||||
bool streamStart(const char* session_id, uint8_t mode_override,
|
||||
uint8_t framesize_override, uint16_t duration_override) {
|
||||
if (s_active) {
|
||||
log_w("stream: already running as %s", s_id);
|
||||
return false;
|
||||
}
|
||||
if (!g_cfg.stream_enabled) {
|
||||
log_w("stream: refused, streaming is disabled in config");
|
||||
return false;
|
||||
}
|
||||
if (!netIsConnected() || !cameraReady()) {
|
||||
log_w("stream: refused, network or camera not ready");
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint8_t mode = (mode_override == 0xFF) ? g_cfg.stream_mode : mode_override;
|
||||
const uint8_t fsize = framesize_override ? framesize_override : g_cfg.stream_frame_size;
|
||||
uint16_t duration = duration_override ? duration_override : g_cfg.stream_duration_s;
|
||||
if (duration > 600) duration = 600; // SPEC C9: always time-boxed
|
||||
|
||||
strncpy(s_id, session_id, sizeof(s_id) - 1);
|
||||
s_id[sizeof(s_id) - 1] = '\0';
|
||||
|
||||
if (!apiStreamOpen(s_id, mode, duration)) return false;
|
||||
|
||||
// Drop to the stream resolution for the session and restore it after, so
|
||||
// a stream never silently changes the resolution of stills.
|
||||
s_prev_size = g_cfg.frame_size;
|
||||
if (fsize != s_prev_size) cameraSetFrameSize(fsize);
|
||||
|
||||
s_period_ms = 1000UL / (g_cfg.stream_fps ? g_cfg.stream_fps : 10);
|
||||
s_end_ms = millis() + duration * 1000UL;
|
||||
s_next_ms = millis();
|
||||
s_frames = 0;
|
||||
s_fail_streak = 0;
|
||||
s_active = true;
|
||||
|
||||
powerInhibit(INHIBIT_STREAM); // released in streamStop()
|
||||
powerNoteActivity();
|
||||
|
||||
log_i("stream: %s started, %us @ %ufps, size %u", s_id, duration, g_cfg.stream_fps, fsize);
|
||||
return true;
|
||||
}
|
||||
|
||||
void streamTick() {
|
||||
if (!s_active) return;
|
||||
|
||||
if ((int32_t)(s_end_ms - millis()) <= 0) { streamStop("duration reached"); return; }
|
||||
if (!netIsConnected()) { streamStop("wifi lost"); return; }
|
||||
if ((int32_t)(s_next_ms - millis()) > 0) return;
|
||||
|
||||
s_next_ms += s_period_ms;
|
||||
// If we fell behind (a slow upload, a burst of uploads competing for the
|
||||
// radio) do not try to catch up by bursting — just resync to now.
|
||||
if ((int32_t)(s_next_ms - millis()) < 0) s_next_ms = millis() + s_period_ms;
|
||||
|
||||
camera_fb_t* fb = cameraGrab();
|
||||
if (!fb) {
|
||||
if (++s_fail_streak > 10) streamStop("camera keeps failing");
|
||||
return;
|
||||
}
|
||||
|
||||
bool sent = apiStreamSendFrame(fb->buf, fb->len, netEpochMs());
|
||||
esp_camera_fb_return(fb);
|
||||
|
||||
if (sent) {
|
||||
s_frames++;
|
||||
s_fail_streak = 0;
|
||||
powerNoteActivity();
|
||||
} else if (++s_fail_streak > 5) {
|
||||
// The Pi closed the connection — a viewer navigated away, or the
|
||||
// session was cancelled server-side. Treat that as a normal end.
|
||||
streamStop("endpoint stopped accepting frames");
|
||||
}
|
||||
}
|
||||
|
||||
void streamStop(const char* reason) {
|
||||
if (!s_active) return;
|
||||
s_active = false;
|
||||
|
||||
apiStreamClose();
|
||||
if (s_prev_size && s_prev_size != g_cfg.stream_frame_size) {
|
||||
cameraSetFrameSize(s_prev_size);
|
||||
}
|
||||
|
||||
powerRelease(INHIBIT_STREAM);
|
||||
powerNoteActivity(); // give the idle timer a fresh start before sleeping
|
||||
|
||||
log_i("stream: %s ended after %u frames — %s", s_id, (unsigned)s_frames, reason);
|
||||
s_id[0] = '\0';
|
||||
}
|
||||
|
||||
uint32_t streamFramesSent() { return s_frames; }
|
||||
|
||||
uint32_t streamSecondsLeft() {
|
||||
if (!s_active) return 0;
|
||||
int32_t left = (int32_t)(s_end_ms - millis());
|
||||
return left > 0 ? (uint32_t)(left / 1000) : 0;
|
||||
}
|
||||
Reference in new issue
Block a user