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,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();
|
||||
Reference in new issue
Block a user