ESP: first implementation; compiles fine; not tested with MCU

This commit is contained in:
Thomas Karner committed 2026-09-20 18:55:26 +02:00
1 parent 5bdcb51bff
commit 6bda641ce8
36 files changed
+6234

No files matched your search

+583
View File
@@ -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);
}
+475
View File
@@ -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("--------------------------------------------------");
}
+115
View File
@@ -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;
}
+231
View File
@@ -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; }
+200
View File
@@ -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;
}
+94
View File
@@ -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, &lt);
// 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; }
+140
View File
@@ -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;
}
+296
View File
@@ -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));
}
+562
View File
@@ -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);
}
+137
View File
@@ -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);
}
+129
View File
@@ -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, &lt);
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, &lt);
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);
}
+191
View File
@@ -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; }
+247
View File
@@ -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.
}
}
+118
View File
@@ -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;
}