Added scheduling

This commit is contained in:
Joren de Graaf
2026-10-10 16:03:44 +02:00
parent 7f5ef0b61b
commit c35ac005fb
24 changed files with 896 additions and 39 deletions
@@ -5,6 +5,7 @@
#include "boomcast_config.h"
#include "boomcast_display.h"
#include "boomcast_network.h"
#include "boomcast_monitor.h"
#include "boomcast_queue.h"
#include "boomcast_state.h"
#include "boomcast_uploader.h"
@@ -40,7 +41,8 @@ static void handleBootButton() {
// Ignore switch bounce and very long holds. A normal click changes page.
if (heldMs >= 40 && heldMs < 1500) {
boomDisplay.nextPage();
if (boomMonitor.idle()) boomMonitor.overrideNow();
else boomDisplay.nextPage();
}
}
}
@@ -56,6 +58,7 @@ void setup() {
pinMode(BOOT_BUTTON_PIN, INPUT_PULLUP);
boomMonitor.begin();
boomQueue.begin();
boomDisplay.begin();
@@ -74,6 +77,7 @@ void setup() {
void loop() {
boomWeb.handle();
boomNetwork.tick();
boomMonitor.tick();
boomDisplay.update();
handleBootButton();
@@ -99,5 +103,5 @@ void loop() {
ESP.restart();
}
delay(2);
delay(boomMonitor.idle() ? 20 : 2);
}
+13 -3
View File
@@ -1,13 +1,13 @@
# BoomCast Waveshare ESP32-S3-ePaper-1.54 V2 firmware
Arduino sketch for the **non-touch V2** board. This folder is the imported `v0.1.0-concept` prototype, updated for the BoomCast sensor API. Its original source was supplied by the project owner; no upstream copyright notice was present in the archive. Official Waveshare support is fetched separately and retains its own attribution and component licenses. The top-level `arduino/` folder is outside the current Django Git repository (`django/`), so include this firmware folder when establishing a project-wide repository or firmware repository.
Arduino sketch for the **non-touch V2** board. This folder started from the owner's `v0.1.0-concept` prototype and has been updated for the BoomCast sensor API. Its original source was supplied by the project owner; no upstream copyright notice was present in the archive. Official Waveshare support is fetched separately and retains its own attribution and component licenses.
**Hardware status:** The owner has confirmed V2, but no physical board has been flashed or tested in this workspace. See [physical validation checklist](docs/validation-checklist.md).
**Hardware status:** The owner has run earlier firmware on the V2 board. This detector revision has only been checked with synthetic PCM traces and compilation; its microphone sensitivity still needs a physical check. See [physical validation checklist](docs/validation-checklist.md).
## Features
- ES8311 microphone capture at 16 kHz through pinned Waveshare support; one fixed stereo slot is selected for mono. The slot assignment still requires playback validation on the real V2 board.
- RMS/peak sound trigger, approximately 2.5 seconds of rolling pre-trigger audio and 2.5 seconds of post-trigger audio. Early startup captures contain the available pre-roll and keep the intended post-trigger interval.
- Browser-worklet-aligned RMS/peak sound trigger, up to 8 seconds of rolling pre-trigger audio and a 2-second tail. Early startup captures contain the available pre-roll and keep the intended tail. See [detection parity and calibration](docs/detection-parity.md).
- 16-bit mono PCM WAVs saved on microSD with a metadata sidecar. A `.meta` file is the queue commit marker; incomplete or invalid WAVs are not upload eligible. Interrupted commits with valid `.meta.tmp` are recovered on startup. FAT cannot guarantee full power-loss atomicity of multi-file transactions; inspect the queue after hard power cuts.
- Wi-Fi setup AP, local owner UI, two ePaper screens, automatic upload retry with bounded backoff, and confirmed-receipt deletion.
- CA-verified HTTPS using the ESP32 core's built-in public CA bundle and an ignored local credentials header. No insecure TLS mode is enabled.
@@ -43,3 +43,13 @@ Queue filenames are stable across reboot. The queue selects the oldest eligible
## Known limits
The Waveshare codec read API returns an error status but no byte count. A failed read is discarded and aborts an active clip; a successful short read cannot be measured through this wrapper. The selected microphone slot and actual recording quality must be checked on a V2 board. Uploads run in the main loop and may pause the local web UI while a slow request is in progress. FAT multi-file commits and SD flush durability need interruption testing. Physical acceptance remains pending.
### Scheduled monitoring (0.4.0-concept)
The local management page now offers persistent weekday/weekend schedules,
Amsterdam DST handling, temporary monitoring and a dedicated idle screen.
Scheduling defaults to off. Outside configured hours, audio stops and CPU/Wi-Fi
power use is reduced while web management stays reachable. Hardware light/deep
sleep remains unavailable pending V2 power-hold validation; no board was flashed.
See [scheduled monitoring](docs/scheduled-monitoring.md) for behavior, tests and
physical validation still required.
+67 -8
View File
@@ -1,4 +1,5 @@
#include "boomcast_audio.h"
#include "boomcast_audio_session.h"
#include "boomcast_config.h"
#include "boomcast_state.h"
#include "audio_bsp.h"
@@ -8,6 +9,9 @@
extern "C" {
#include "src/esp_codec_dev/include/esp_codec_dev.h"
extern esp_codec_dev_handle_t record;
extern esp_codec_dev_handle_t playback;
#include "src/codec_board/codec_board.h"
#include "src/codec_board/codec_init.h"
}
BoomAudio boomAudio;
@@ -18,25 +22,55 @@ bool BoomAudio::begin(BoomQueue* queue) {
ring_ = (int16_t*)heap_caps_malloc(PRE_EVENT_SAMPLES * sizeof(int16_t), MALLOC_CAP_SPIRAM);
capture_ = (int16_t*)heap_caps_malloc(CAPTURE_SAMPLES * sizeof(int16_t), MALLOC_CAP_SPIRAM);
if (!ring_ || !capture_) {
fault_.store(true);
restartRequired_.store(true);
free(ring_); free(capture_); ring_ = capture_ = nullptr;
Serial.println("[Audio] PSRAM allocation failed");
return false;
}
memset(ring_, 0, PRE_EVENT_SAMPLES * sizeof(int16_t));
memset(capture_, 0, CAPTURE_SAMPLES * sizeof(int16_t));
// Waveshare's official audio support opens the ES8311 at 16 kHz / 16-bit.
audio_bsp_init();
audio_play_init();
if (!record) {
Serial.println("[Audio] codec record handle unavailable");
return false;
// Use the same board setup without the example's abort-on-error wrapper.
set_codec_board_type("S3_ePaper_1_54");
codec_init_cfg_t cfg{};
cfg.in_mode = cfg.out_mode = CODEC_I2S_MODE_STD;
if (init_codec(&cfg) != 0) { fault_.store(true); restartRequired_.store(true); return false; }
record = get_record_handle(); playback = get_playback_handle();
if (!record || !playback) { fault_.store(true); restartRequired_.store(true); return false; }
if (xTaskCreatePinnedToCore(taskThunk, "boom_audio", 8192, this, 5, &task_, 0) != pdPASS) {
fault_.store(true); restartRequired_.store(true); return false;
}
xTaskCreatePinnedToCore(taskThunk, "boom_audio", 8192, this, 5, &task_, 0);
Serial.println("[Audio] detector task started");
return true;
}
void BoomAudio::resetBuffers() {
ringFilled_ = ringWrite_ = captureWrite_ = 0;
detector_.reset();
int8_t empty[BOOMCAST_WAVEFORM_POINTS]{};
boomState.setWaveform(empty, BOOMCAST_WAVEFORM_POINTS);
}
void BoomAudio::closeCodec() {
// Both handles share I2S. Close both to stop RX and TX DMA; keep allocated
// handles/buffers for reuse (deinit_codec also destroys the shared RTC I2C bus).
esp_codec_dev_close(record);
esp_codec_dev_close(playback);
active_.store(false);
resetBuffers();
}
bool BoomAudio::openCodec() {
esp_codec_dev_sample_info_t fs{};
fs.sample_rate = AUDIO_SAMPLE_RATE; fs.channel = 2; fs.bits_per_sample = 16;
bool ok = esp_codec_dev_open(playback, &fs) == ESP_CODEC_DEV_OK &&
esp_codec_dev_open(record, &fs) == ESP_CODEC_DEV_OK &&
esp_codec_dev_set_in_gain(record, BOOMCAST_CODEC_INPUT_GAIN_DB) == ESP_CODEC_DEV_OK;
if (!ok) closeCodec();
resetBuffers();
fault_.store(!ok);
return ok;
}
void BoomAudio::setSensitivity(uint8_t value) {
sensitivity_ = constrain(value, 1, 100);
}
@@ -49,16 +83,37 @@ void BoomAudio::taskLoop() {
uint8_t* raw = (uint8_t*)heap_caps_malloc(AUDIO_RAW_BLOCK_BYTES, MALLOC_CAP_SPIRAM);
int16_t* mono = (int16_t*)heap_caps_malloc(AUDIO_FRAMES_PER_BLOCK * sizeof(int16_t), MALLOC_CAP_SPIRAM);
if (!raw || !mono) {
fault_.store(true);
restartRequired_.store(true);
free(raw); free(mono);
Serial.println("[Audio] block allocation failed");
vTaskDelete(nullptr);
return;
}
BoomAudioSession session(AUDIO_SAMPLE_RATE);
while (true) {
auto action = session.next(requested_.load(), capturing_);
if (action == BoomAudioSession::Action::Suspend) {
if (session.isOpen()) { closeCodec(); session.closed(); }
suspended_.store(true);
delay(200);
continue;
}
suspended_.store(false);
if (action == BoomAudioSession::Action::Open) {
if (!openCodec()) { delay(1000); continue; }
session.opened();
// Drain a second of fresh DMA input before feeding baseline/pre-trigger
// buffers. Detector reset then adds its usual 3-second trigger cooldown.
}
memset(raw, 0, AUDIO_RAW_BLOCK_BYTES);
const int readResult = esp_codec_dev_read(record, raw, AUDIO_RAW_BLOCK_BYTES);
if (readResult != ESP_CODEC_DEV_OK) {
++failedReads_;
active_.store(false);
fault_.store(true);
if (session.failedRead()) { closeCodec(); session.closed(); }
droppedSamples_ += AUDIO_FRAMES_PER_BLOCK;
// A failed read invalidates timing continuity. Discard an active clip.
if (capturing_) {
@@ -76,6 +131,9 @@ void BoomAudio::taskLoop() {
delay(10);
continue;
}
fault_.store(false);
if (!session.usableRead(AUDIO_FRAMES_PER_BLOCK)) continue;
active_.store(true);
const int16_t* stereo = reinterpret_cast<const int16_t*>(raw);
for (size_t i = 0; i < AUDIO_FRAMES_PER_BLOCK; ++i) {
mono[i] = stereo[i * 2 + AUDIO_MIC_SLOT];
@@ -117,6 +175,7 @@ void BoomAudio::processMonoBlock(const int16_t* mono, size_t frames) {
if (result == BoomDetector::Result::TailDone) {
appendCapture(sample);
finishCapture();
if (!requested_.load()) return;
}
}
}
@@ -1,5 +1,6 @@
#pragma once
#include <Arduino.h>
#include <atomic>
#include "boomcast_queue.h"
#include "boomcast_config.h"
#include "boomcast_detector.h"
@@ -8,8 +9,17 @@ class BoomAudio {
public:
bool begin(BoomQueue* queue);
void setSensitivity(uint8_t value);
void requestMonitoring(bool enabled) { requested_.store(enabled); }
bool active() const { return active_.load(); }
bool suspended() const { return suspended_.load(); }
bool fault() const { return fault_.load(); }
bool restartRequired() const { return restartRequired_.load(); }
private:
std::atomic<bool> requested_{true}, active_{false}, suspended_{false}, fault_{false}, restartRequired_{false};
bool openCodec();
void closeCodec();
void resetBuffers();
BoomQueue* queue_ = nullptr;
TaskHandle_t task_ = nullptr;
int16_t* ring_ = nullptr;
@@ -0,0 +1,29 @@
#pragma once
#include <cstdint>
// Audio-task lifecycle policy. Queue contents deliberately do not gate suspend:
// only the current capture/save operation must finish before closing the codec.
class BoomAudioSession {
public:
enum class Action { Suspend, Open, Read };
explicit BoomAudioSession(uint32_t settleFrames) : settleFrames_(settleFrames) {}
Action next(bool requested, bool capturing) const {
if (!requested && !capturing) return Action::Suspend;
return opened_ ? Action::Read : Action::Open;
}
bool isOpen() const { return opened_; }
void opened() { opened_ = true; remaining_ = settleFrames_; failures_ = 0; }
void closed() { opened_ = false; remaining_ = 0; failures_ = 0; }
bool failedRead() { return ++failures_ >= 10; }
bool usableRead(uint32_t frames) {
failures_ = 0;
if (remaining_) {
remaining_ = remaining_ > frames ? remaining_ - frames : 0;
return false;
}
return true;
}
private:
uint32_t settleFrames_, remaining_ = 0, failures_ = 0;
bool opened_ = false;
};
+1 -1
View File
@@ -7,7 +7,7 @@
// Target: Waveshare ESP32-S3-ePaper-1.54 V2 (non-touch)
// -----------------------------------------------------------------------------
#define BOOMCAST_FIRMWARE_VERSION "0.3.0-concept"
#define BOOMCAST_FIRMWARE_VERSION "0.4.0-concept"
// Set to 180 when the board is physically mounted upside-down.
// Supported by this sketch: 0 or 180.
@@ -68,9 +68,8 @@ bool BoomDisplay::begin() {
esp_timer_create_args_t timerArgs = {};
timerArgs.callback = &tickCb;
timerArgs.name = "boom_lv_tick";
esp_timer_handle_t tickTimer = nullptr;
ESP_ERROR_CHECK(esp_timer_create(&timerArgs, &tickTimer));
ESP_ERROR_CHECK(esp_timer_start_periodic(tickTimer, 5 * 1000));
ESP_ERROR_CHECK(esp_timer_create(&timerArgs, &tickTimer_));
ESP_ERROR_CHECK(esp_timer_start_periodic(tickTimer_, 5 * 1000));
if (lock()) {
createScreens();
@@ -104,10 +103,10 @@ void BoomDisplay::lvglTask() {
while (true) {
uint32_t delayMs = 50;
if (lock()) {
delayMs = lv_timer_handler();
delayMs = scheduledIdle_ ? 500 : lv_timer_handler();
unlock();
}
delayMs = constrain(delayMs, 20U, 250U);
delayMs = constrain(delayMs, 20U, 500U);
vTaskDelay(pdMS_TO_TICKS(delayMs));
}
}
@@ -334,6 +333,7 @@ void BoomDisplay::applySnapshot(const BoomStateSnapshot& s) {
}
void BoomDisplay::update() {
if (scheduledIdle_) return;
if (millis() - lastStatusUpdateMs_ < DISPLAY_STATUS_UPDATE_MS) return;
lastStatusUpdateMs_ = millis();
@@ -362,3 +362,52 @@ void BoomDisplay::update() {
haveLast_ = true;
}
}
void BoomDisplay::setScheduledIdle(bool idle, const String& next) {
if (idle == scheduledIdle_ && (!idle || next == sleepNext_)) return;
if (!display_ || !lock()) return;
scheduledIdle_ = idle;
if (idle) {
if (!sleepScreen_) {
sleepScreen_ = lv_obj_create(nullptr);
stylePlainScreen(sleepScreen_);
auto label = [this](const char* text, int y, int width) {
lv_obj_t* l = lv_label_create(sleepScreen_);
lv_label_set_text(l, text); lv_obj_set_width(l, width);
lv_obj_set_style_text_align(l, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(l, LV_ALIGN_TOP_MID, 0, y); return l;
};
label("BoomCast", 8, 190);
static const lv_point_t sleepingZ[3][4] = {
{{0,0},{24,0},{0,27},{24,27}},
{{0,0},{17,0},{0,19},{17,19}},
{{0,0},{11,0},{0,12},{11,12}}
};
for (int i = 0; i < 3; ++i) {
auto z = lv_line_create(sleepScreen_);
lv_line_set_points(z, sleepingZ[i], 4);
lv_obj_set_pos(z, 61 + i * 30, 36 + i * 6);
lv_obj_set_style_line_width(z, 3, 0);
lv_obj_set_style_line_color(z, lv_color_black(), 0);
}
label("SLAAPSTAND", 70, 190);
label("Zelfs de knalidioten zijn\nblijkbaar even stil.", 94, 190);
sleepNextLabel_ = label("", 140, 190);
label("BOOT: tijdelijk luisteren", 179, 190);
}
sleepNext_ = next;
lv_label_set_text(sleepNextLabel_, (String("Luistert weer:\n") + next).c_str());
lv_scr_load(sleepScreen_);
} else {
lv_scr_load(page_ == 0 ? publicScreen_ : detailScreen_);
haveLast_ = false;
}
requestFullRefresh();
if (idle) {
lv_refr_now(display_); // finish the single sleep-screen flush before stopping ticks
esp_timer_stop(tickTimer_);
} else {
if (!esp_timer_is_active(tickTimer_)) esp_timer_start_periodic(tickTimer_, 5000);
}
unlock();
}
@@ -2,12 +2,14 @@
#include <Arduino.h>
#include "boomcast_state.h"
#include "lvgl.h"
#include "esp_timer.h"
#include "src/display/epaper_driver_bsp.h"
class BoomDisplay {
public:
bool begin();
void update();
void setScheduledIdle(bool idle, const String& next);
void nextPage();
void showPage(uint8_t page);
uint8_t page() const { return page_; }
@@ -23,6 +25,11 @@ private:
uint16_t partialCount_ = 0;
uint32_t lastStatusUpdateMs_ = 0;
esp_timer_handle_t tickTimer_ = nullptr;
bool scheduledIdle_ = false;
String sleepNext_;
lv_obj_t* sleepScreen_ = nullptr;
lv_obj_t* sleepNextLabel_ = nullptr;
lv_obj_t* publicScreen_ = nullptr;
lv_obj_t* detailScreen_ = nullptr;
@@ -0,0 +1,150 @@
#include "boomcast_monitor.h"
#include "boomcast_rtc.h"
#include "boomcast_audio.h"
#include "boomcast_state.h"
#include "boomcast_config.h"
#include "boomcast_display.h"
#include "src/i2c_bsp/i2c_bsp.h"
#include <ArduinoJson.h>
#include <WiFi.h>
#include <atomic>
#include <sys/time.h>
#include "esp_sntp.h"
BoomMonitor boomMonitor;
static std::atomic<bool> ntpUpdated{false};
static void ntpCallback(struct timeval*) { ntpUpdated.store(true); }
static uint8_t toBcd(int value) { return (value / 10) * 16 + value % 10; }
// PCF85063 registers from the pinned Waveshare driver. RTC stores UTC.
static bool readRtc(time_t& result) {
uint8_t control, bytes[7], controlReg = 0, secondsReg = 4;
if (i2c_master_transmit_receive(rtc_dev_handle, &controlReg, 1, &control, 1, 100) != ESP_OK ||
i2c_master_transmit_receive(rtc_dev_handle, &secondsReg, 1, bytes, 7, 100) != ESP_OK) return false;
return BoomRtc::decode(control, bytes, result);
}
static bool writeRtc(time_t now) {
tm utc{}; gmtime_r(&now, &utc);
uint8_t control;
uint8_t reg = 0;
if (i2c_master_transmit_receive(rtc_dev_handle, &reg, 1, &control, 1, 100) != ESP_OK) return false;
uint8_t mode[2] = {0, uint8_t(control & ~0x28)};
uint8_t bytes[8] = {4, toBcd(utc.tm_sec), toBcd(utc.tm_min), toBcd(utc.tm_hour),
toBcd(utc.tm_mday), toBcd(utc.tm_wday), toBcd(utc.tm_mon + 1), toBcd(utc.tm_year % 100)};
return i2c_master_transmit(rtc_dev_handle, mode, 2, 100) == ESP_OK &&
i2c_master_transmit(rtc_dev_handle, bytes, 8, 100) == ESP_OK;
}
void BoomMonitor::load() {
auto& p = boomState.prefs();
// One versioned record prevents a power loss leaving half a new schedule.
String stored = p.getString("schedule", "");
JsonDocument doc;
if (!stored.length()) return;
bool invalid = deserializeJson(doc, stored) || doc["schema"].as<int>() != 1 ||
!doc["enabled"].is<bool>() || !doc["modemSleep"].is<bool>();
for (const char* key : {"weekdayStart", "weekdayEnd", "weekendStart", "weekendEnd", "overrideMinutes"})
invalid = invalid || !doc[key].is<uint16_t>();
if (invalid) {
fault_ = "Invalid saved schedule; monitoring continuously"; return;
}
BoomScheduleConfig c;
c.enabled = doc["enabled"]; c.modemSleep = doc["modemSleep"];
c.weekdayStart = doc["weekdayStart"]; c.weekdayEnd = doc["weekdayEnd"];
c.weekendStart = doc["weekendStart"]; c.weekendEnd = doc["weekendEnd"];
c.overrideMinutes = doc["overrideMinutes"];
if (c.valid()) config_ = c;
else fault_ = "Invalid saved schedule; monitoring continuously";
}
bool BoomMonitor::save(const BoomScheduleConfig& c) {
if (!c.valid()) return false;
JsonDocument doc;
doc["schema"] = 1; doc["enabled"] = c.enabled; doc["modemSleep"] = c.modemSleep;
doc["weekdayStart"] = c.weekdayStart; doc["weekdayEnd"] = c.weekdayEnd;
doc["weekendStart"] = c.weekendStart; doc["weekendEnd"] = c.weekendEnd;
doc["overrideMinutes"] = c.overrideMinutes;
String stored; serializeJson(doc, stored);
if (!boomState.prefs().putString("schedule", stored)) return false;
config_ = c; nextCalculatedAt_ = 0; lastCheck_ = millis() - 1000; return true;
}
void BoomMonitor::begin() {
setenv("TZ", TZ_INFO, 1); tzset();
normalCpuMHz_ = getCpuFrequencyMhz();
load();
time_t rtc;
// Only trust RTC values previously written by this firmware after NTP.
rtcHealthy_ = boomState.prefs().getBool("rtc_utc", false) && readRtc(rtc);
if (rtcHealthy_) {
timeval tv{rtc, 0}; settimeofday(&tv, nullptr); trusted_ = true;
wakeReason_ = "Boot; UTC clock restored from RTC";
}
sntp_set_time_sync_notification_cb(ntpCallback);
lastCheck_ = millis() - 1000;
}
uint32_t BoomMonitor::overrideRemaining() const {
int32_t remaining = int32_t(overrideUntil_ - millis());
return overrideUntil_ && remaining > 0 ? (uint32_t(remaining) + 999) / 1000 : 0;
}
void BoomMonitor::overrideNow() {
overrideUntil_ = millis() + uint32_t(config_.overrideMinutes) * 60000;
if (!overrideUntil_) overrideUntil_ = 1;
wakeReason_ = "Manual override"; lastCheck_ = millis() - 1000;
}
void BoomMonitor::returnToSchedule() { overrideUntil_ = 0; lastCheck_ = millis() - 1000; }
void BoomMonitor::tick() {
if (millis() - lastCheck_ < 1000) return;
lastCheck_ = millis();
time_t now = time(nullptr);
if (ntpUpdated.exchange(false) && now >= 1704067200) {
trusted_ = true;
rtcHealthy_ = writeRtc(now);
boomState.prefs().putBool("rtc_utc", rtcHealthy_);
}
if (now < 1704067200) trusted_ = false;
if (!overrideRemaining()) overrideUntil_ = 0;
bool monitor = BoomSchedule::shouldMonitor(config_, now, trusted_, overrideRemaining() > 0);
if (monitor && getCpuFrequencyMhz() != normalCpuMHz_) setCpuFrequencyMhz(normalCpuMHz_);
boomAudio.requestMonitoring(monitor);
if (!trusted_) next_ = 0;
else if (!nextCalculatedAt_ || now < nextCalculatedAt_ || now - nextCalculatedAt_ >= 60 || (next_ && now >= next_)) {
next_ = BoomSchedule::nextTransition(config_, now);
nextCalculatedAt_ = now;
}
auto previous = state_;
state_ = overrideRemaining() ? BoomOperatingState::MANUAL_OVERRIDE :
(!monitor && boomAudio.suspended() ? BoomOperatingState::SCHEDULED_IDLE : BoomOperatingState::MONITORING);
fault_ = !trusted_ ? "Clock untrusted; monitoring until NTP synchronises" :
!rtcHealthy_ ? "RTC unavailable; NTP time valid for this boot only" : "";
if (!monitor && !boomAudio.suspended()) fault_ = "Waiting for audio to finish and suspend";
if (boomAudio.fault()) fault_ = boomAudio.restartRequired() ?
"Audio setup failed; reboot from device settings to retry" : "Audio peripheral fault; retrying initialization";
if (idle() && getCpuFrequencyMhz() > 80) setCpuFrequencyMhz(80);
WiFi.setSleep(idle() && config_.modemSleep);
if (previous == BoomOperatingState::SCHEDULED_IDLE && !idle()) wakeReason_ = overrideRemaining() ? "Manual override" : "Scheduled monitoring / settings change";
boomDisplay.setScheduledIdle(idle(), nextTransitionText());
}
const char* BoomMonitor::stateName() const {
switch (state_) {
case BoomOperatingState::SCHEDULED_IDLE: return "SCHEDULED_IDLE";
case BoomOperatingState::SCHEDULED_SLEEP: return "SCHEDULED_SLEEP";
case BoomOperatingState::MANUAL_OVERRIDE: return "MANUAL_OVERRIDE";
default: return "MONITORING";
}
}
String BoomMonitor::nextTransitionText() const {
if (!next_) return trusted_ ? "Continuous monitoring" : "Waiting for time";
tm local{}; localtime_r(&next_, &local); char value[40];
strftime(value, sizeof(value), "%a %d-%m %H:%M %Z", &local); return value;
}
String BoomMonitor::json() const {
JsonDocument d;
d["enabled"] = config_.enabled; d["modemSleep"] = config_.modemSleep;
d["weekdayStart"] = config_.weekdayStart; d["weekdayEnd"] = config_.weekdayEnd;
d["weekendStart"] = config_.weekendStart; d["weekendEnd"] = config_.weekendEnd;
d["overrideMinutes"] = config_.overrideMinutes;
d["state"] = stateName(); d["nextTransition"] = nextTransitionText();
d["microphoneActive"] = boomAudio.active(); d["overrideRemaining"] = overrideRemaining();
d["clockTrusted"] = trusted_; d["rtcHealthy"] = rtcHealthy_;
d["fault"] = fault_; d["wakeReason"] = wakeReason_;
d["hardwareSleepSupported"] = false;
d["cpuMHz"] = getCpuFrequencyMhz();
String result; serializeJson(d, result); return result;
}
@@ -0,0 +1,28 @@
#pragma once
#include <Arduino.h>
#include "boomcast_schedule.h"
class BoomMonitor {
public:
void begin();
void tick();
bool save(const BoomScheduleConfig& config);
void overrideNow();
void returnToSchedule();
const BoomScheduleConfig& config() const { return config_; }
const char* stateName() const;
bool idle() const { return state_ == BoomOperatingState::SCHEDULED_IDLE; }
uint32_t overrideRemaining() const;
String nextTransitionText() const;
String json() const;
private:
BoomScheduleConfig config_;
BoomOperatingState state_ = BoomOperatingState::MONITORING;
uint32_t normalCpuMHz_ = 240;
uint32_t overrideUntil_ = 0, lastCheck_ = 0;
time_t next_ = 0, nextCalculatedAt_ = 0;
bool trusted_ = false, rtcHealthy_ = false;
String fault_, wakeReason_ = "Boot";
void load();
};
extern BoomMonitor boomMonitor;
@@ -60,7 +60,7 @@ void BoomNetwork::startFallbackAp() {
void BoomNetwork::configureTimeAndMdns() {
setenv("TZ", TZ_INFO, 1);
tzset();
configTime(0, 0, NTP_SERVER_1, NTP_SERVER_2);
configTzTime(TZ_INFO, NTP_SERVER_1, NTP_SERVER_2);
if (MDNS.begin(MDNS_HOSTNAME)) {
MDNS.addService("http", "tcp", 80);
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <ctime>
#include <cstdint>
namespace BoomRtc {
inline int bcd(uint8_t value) {
return (value & 15) <= 9 && (value >> 4) <= 9 ? (value >> 4) * 10 + (value & 15) : -1;
}
inline bool decode(uint8_t control, const uint8_t bytes[7], time_t& result) {
if ((control & 0x28) || (bytes[0] & 0x80)) return false;
tm utc{};
utc.tm_sec = bcd(bytes[0]); utc.tm_min = bcd(bytes[1]); utc.tm_hour = bcd(bytes[2]);
utc.tm_mday = bcd(bytes[3]); utc.tm_mon = bcd(bytes[5]) - 1; utc.tm_year = bcd(bytes[6]) + 100;
if (utc.tm_sec < 0 || utc.tm_sec > 59 || utc.tm_min < 0 || utc.tm_min > 59 ||
utc.tm_hour < 0 || utc.tm_hour > 23 || utc.tm_mday < 1 || utc.tm_mday > 31 ||
utc.tm_mon < 0 || utc.tm_mon > 11 || utc.tm_year < 124 || utc.tm_year > 199) return false;
// UTC conversion without changing the process TZ used by other tasks.
int year = utc.tm_year + 1900, month = utc.tm_mon + 1;
year -= month <= 2;
int era = year / 400, yoe = year - era * 400;
int doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + utc.tm_mday - 1;
int days = era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468;
result = time_t(days) * 86400 + utc.tm_hour * 3600 + utc.tm_min * 60 + utc.tm_sec;
tm check{}; gmtime_r(&result, &check);
return check.tm_mon == utc.tm_mon && check.tm_mday == utc.tm_mday;
}
}
@@ -0,0 +1,77 @@
#pragma once
#include <ctime>
#include <cstdint>
#include <initializer_list>
// Calendar policy only: no Wi-Fi, Arduino or hardware dependency. TZ is Amsterdam.
struct BoomScheduleConfig {
uint16_t weekdayStart = 12 * 60, weekdayEnd = 60;
uint16_t weekendStart = 12 * 60, weekendEnd = 2 * 60;
uint16_t overrideMinutes = 30;
bool enabled = false;
bool modemSleep = true;
bool valid() const {
return weekdayStart < 1440 && weekdayEnd < 1440 && weekendStart < 1440 &&
weekendEnd < 1440 && overrideMinutes >= 1 && overrideMinutes <= 1440;
}
};
enum class BoomOperatingState { MONITORING, SCHEDULED_IDLE, SCHEDULED_SLEEP, MANUAL_OVERRIDE };
namespace BoomSchedule {
// Repeated autumn hour: earliest start, latest end. Missing spring hour:
// libc normalises forward. Each interval remains anchored to its starting day.
inline time_t boundary(tm day, int minute, bool end) {
day.tm_hour = minute / 60; day.tm_min = minute % 60; day.tm_sec = 0;
time_t chosen = -1;
for (int dst = 0; dst <= 1; ++dst) {
tm candidate = day; candidate.tm_isdst = dst;
time_t value = mktime(&candidate);
tm roundtrip{}; localtime_r(&value, &roundtrip);
if (roundtrip.tm_year == day.tm_year && roundtrip.tm_yday == day.tm_yday &&
roundtrip.tm_hour == day.tm_hour && roundtrip.tm_min == day.tm_min) {
if (chosen == -1 || (end ? value > chosen : value < chosen)) chosen = value;
}
}
if (chosen != -1) return chosen;
day.tm_isdst = 0; // Amsterdam spring gap: move forward by the skipped hour
return mktime(&day);
}
inline tm dayAt(time_t now, int offset) {
tm day{}; localtime_r(&now, &day);
day.tm_mday += offset; day.tm_hour = 12; day.tm_min = day.tm_sec = 0; day.tm_isdst = -1;
mktime(&day);
return day;
}
inline void interval(const BoomScheduleConfig& c, time_t now, int offset, time_t& start, time_t& end) {
tm day = dayAt(now, offset);
bool weekend = day.tm_wday == 0 || day.tm_wday == 6;
int first = weekend ? c.weekendStart : c.weekdayStart;
int last = weekend ? c.weekendEnd : c.weekdayEnd;
start = boundary(day, first, false);
if (last <= first) day = dayAt(now, offset + 1); // equal means a full calendar day
end = boundary(day, last, true);
}
inline bool active(const BoomScheduleConfig& c, time_t now) {
if (!c.enabled || !c.valid()) return true;
for (int offset = -1; offset <= 0; ++offset) {
time_t start, end; interval(c, now, offset, start, end);
if (now >= start && now < end) return true;
}
return false;
}
inline time_t nextTransition(const BoomScheduleConfig& c, time_t now) {
if (!c.enabled || !c.valid()) return 0;
time_t next = 0;
for (int offset = -1; offset <= 8; ++offset) {
time_t start, end; interval(c, now, offset, start, end);
for (time_t candidate : {start, end}) {
if (candidate > now && (!next || candidate < next) &&
active(c, candidate - 1) != active(c, candidate)) next = candidate;
}
}
return next;
}
inline bool shouldMonitor(const BoomScheduleConfig& c, time_t now, bool trusted, bool overrideActive) {
return overrideActive || !trusted || active(c, now);
}
}
@@ -2,6 +2,7 @@
#include "boomcast_config.h"
#include "boomcast_network.h"
#include "boomcast_state.h"
#include "boomcast_monitor.h"
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
@@ -31,7 +32,10 @@ static String isoUtc(uint64_t epochMs) {
static bool writeAll(WiFiClientSecure& client, const uint8_t* bytes, size_t size) {
size_t done = 0;
const uint32_t started = millis();
while (done < size && client.connected()) {
boomMonitor.tick();
if (millis() - started > 15000) return false;
size_t n = client.write(bytes + done, size - done);
if (!n) return false;
done += n;
@@ -52,6 +56,7 @@ static bool waitForNtpTime() {
const uint32_t started = millis();
while (!synchronized && boomNetwork.connected() && millis() - started < 20000) {
if (sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED) synchronized = true;
boomMonitor.tick();
if (!synchronized) delay(100);
}
time_t now = time(nullptr);
@@ -73,7 +78,9 @@ bool BoomUploader::submitOne(const String& filename) {
int BoomUploader::submitAll() {
if (!queue_ || !boomNetwork.connected()) return 0;
int sent = 0;
while (sent < 500) {
const uint32_t started = millis();
while (sent < 500 && millis() - started < 30000) {
boomMonitor.tick();
String first[1];
if (!queue_->listNames(first, 1) || !submitOne(first[0])) break;
++sent;
@@ -148,11 +155,12 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
WiFiClientSecure client;
client.useBuiltinCACertBundle();
client.setTimeout(60);
client.setTimeout(5);
client.setHandshakeTimeout(15);
Serial.printf("[Upload] free heap=%u PSRAM=%u largest PSRAM=%u\n",
unsigned(ESP.getFreeHeap()), unsigned(ESP.getFreePsram()),
unsigned(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)));
if (!client.connect(host.c_str(), port)) { fclose(file); return false; }
if (!client.connect(host.c_str(), port, 5000)) { fclose(file); return false; }
String header = "POST " + String(SUBMIT_PATH) + " HTTP/1.1\r\nHost: " + host + "\r\n";
header += "Authorization: Bearer " + token + "\r\n";
header += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n";
@@ -160,7 +168,8 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
bool sent = writeAll(client, header) && writeAll(client, preamble);
uint8_t chunk[1024];
size_t fileSent = 0;
while (sent && fileSent < fileBytes) {
const uint32_t uploadStarted = millis();
while (sent && fileSent < fileBytes && millis() - uploadStarted < 30000) {
size_t n = fread(chunk, 1, min(sizeof(chunk), fileBytes - fileSent), file);
if (n == 0) { sent = false; break; }
sent = writeAll(client, chunk, n);
@@ -171,7 +180,21 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
if (sent) sent = writeAll(client, trailer);
if (!sent) { client.stop(); return false; }
String statusLine = client.readStringUntil('\n');
const uint32_t responseStarted = millis();
auto readLine = [&client, responseStarted](String& line) {
line = "";
while (millis() - responseStarted < 60000 && line.length() < 1024) {
boomMonitor.tick();
if (client.available()) {
char c = char(client.read());
if (c == '\n') return true;
line += c;
} else { if (!client.connected()) return false; delay(5); }
}
return false;
};
String statusLine;
if (!readLine(statusLine)) { client.stop(); return false; }
int status = 0;
if (statusLine.startsWith("HTTP/1.")) {
int firstSpace = statusLine.indexOf(' ');
@@ -179,16 +202,20 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
}
// Django returns an ordinary Content-Length response; do not accept redirects.
int contentLength = -1;
while (client.connected()) {
String line = client.readStringUntil('\n'); line.trim();
size_t headerBytes = 0;
while (true) {
String line;
if (!readLine(line) || (headerBytes += line.length()) > 8192) { client.stop(); return false; }
line.trim();
if (!line.length()) break;
if (line.startsWith("Content-Length:") || line.startsWith("content-length:"))
contentLength = line.substring(line.indexOf(':') + 1).toInt();
}
if (contentLength < 0 || contentLength > 8192) { client.stop(); return false; }
String body; body.reserve(contentLength);
uint32_t started = millis();
while (body.length() < size_t(contentLength) && millis() - started < 60000) {
while (body.length() < size_t(contentLength) && millis() - responseStarted < 60000) {
boomMonitor.tick();
if (!client.connected() && !client.available()) break;
while (client.available() && body.length() < size_t(contentLength)) body += char(client.read());
delay(1);
}
+77 -2
View File
@@ -1,5 +1,6 @@
#include "boomcast_web.h"
#include "boomcast_audio.h"
#include "boomcast_monitor.h"
#include "boomcast_config.h"
#include "boomcast_network.h"
#include "boomcast_queue.h"
@@ -24,7 +25,7 @@ static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>BoomCast</title>
<style>
:root{color-scheme:light;--ink:#18201e;--muted:#64706d;--line:#d9e1df;--paper:#f5f7f6;--card:#fff;--accent:#143f35;--soft:#e6efec;--warn:#fff5d8;--bad:#ffe7e3}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.wrap{max-width:920px;margin:auto;padding:24px 16px 56px}header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:20px}.brand{display:flex;align-items:center;gap:12px}.logo{width:44px;height:44px;border:2px solid var(--ink);border-radius:14px;display:grid;place-items:center;font-size:23px;background:white}.brand h1{font-size:22px;margin:0}.brand p{margin:1px 0 0;color:var(--muted);font-size:13px}.pill{border:1px solid var(--line);border-radius:999px;padding:7px 11px;background:white;font-size:12px}.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.metric,.card{background:var(--card);border:1px solid var(--line);border-radius:16px}.metric{padding:14px}.metric b{display:block;font-size:22px;margin-top:2px}.metric span{color:var(--muted);font-size:12px}.cards{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:14px}.card{padding:18px}.card.full{grid-column:1/-1}.card h2{font-size:16px;margin:0 0 4px}.sub{color:var(--muted);font-size:13px;margin:0 0 15px}.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.statusdot{width:9px;height:9px;border-radius:50%;display:inline-block;background:#9aa4a1;margin-right:6px}.statusdot.ok{background:#18794e}.statusdot.warn{background:#c48400}.statusdot.bad{background:#c73a30}button,input,select{font:inherit}button{border:0;border-radius:10px;padding:10px 13px;background:var(--accent);color:white;font-weight:650;cursor:pointer}button.secondary{background:var(--soft);color:var(--ink)}button.danger{background:#8f2e28}button:disabled{opacity:.5;cursor:not-allowed}input[type=text],input[type=password],select{width:100%;border:1px solid var(--line);border-radius:10px;padding:10px;background:white;color:var(--ink)}label{font-size:12px;color:var(--muted);display:block;margin-bottom:6px}.field{margin-bottom:12px}.sliderline{display:grid;grid-template-columns:1fr auto;gap:14px;align-items:center}.sliderline input{width:100%}.sens{font-size:24px;font-weight:750;min-width:54px;text-align:right}canvas{width:100%;height:128px;border:1px solid var(--line);border-radius:12px;background:#fbfcfc;display:block}.queue{display:grid;gap:8px}.event{border:1px solid var(--line);border-radius:11px;padding:10px 11px;display:grid;grid-template-columns:1fr auto;gap:10px;align-items:center}.event strong{font-size:13px;word-break:break-all}.event small{display:block;color:var(--muted);margin-top:2px}.empty{color:var(--muted);padding:8px 0}.message{margin-top:10px;font-size:13px;color:var(--muted);min-height:20px}.privacy{padding:12px 14px;background:var(--soft);border-radius:12px;font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}.switcher{display:flex;gap:8px;align-items:center}.wifi-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.wifi-form .wide{grid-column:1/-1}@media(max-width:700px){.grid{grid-template-columns:1fr 1fr}.cards{grid-template-columns:1fr}.card.full{grid-column:auto}.wifi-form{grid-template-columns:1fr}.wifi-form .wide{grid-column:auto}}@media(max-width:420px){.grid{grid-template-columns:1fr 1fr}header{align-items:flex-start;flex-direction:column}.event{grid-template-columns:1fr}.event button{width:100%}}
:root{color-scheme:light;--ink:#18201e;--muted:#64706d;--line:#d9e1df;--paper:#f5f7f6;--card:#fff;--accent:#143f35;--soft:#e6efec;--warn:#fff5d8;--bad:#ffe7e3}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.45 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.wrap{max-width:920px;margin:auto;padding:24px 16px 56px}header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:20px}.brand{display:flex;align-items:center;gap:12px}.logo{width:44px;height:44px;border:2px solid var(--ink);border-radius:14px;display:grid;place-items:center;font-size:23px;background:white}.brand h1{font-size:22px;margin:0}.brand p{margin:1px 0 0;color:var(--muted);font-size:13px}.pill{border:1px solid var(--line);border-radius:999px;padding:7px 11px;background:white;font-size:12px}.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.metric,.card{background:var(--card);border:1px solid var(--line);border-radius:16px}.metric{padding:14px}.metric b{display:block;font-size:22px;margin-top:2px}.metric span{color:var(--muted);font-size:12px}.cards{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:14px}.card{padding:18px}.card.full{grid-column:1/-1}.card h2{font-size:16px;margin:0 0 4px}.sub{color:var(--muted);font-size:13px;margin:0 0 15px}.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.statusdot{width:9px;height:9px;border-radius:50%;display:inline-block;background:#9aa4a1;margin-right:6px}.statusdot.ok{background:#18794e}.statusdot.warn{background:#c48400}.statusdot.bad{background:#c73a30}button,input,select{font:inherit}button{border:0;border-radius:10px;padding:10px 13px;background:var(--accent);color:white;font-weight:650;cursor:pointer}button.secondary{background:var(--soft);color:var(--ink)}button.danger{background:#8f2e28}button:disabled{opacity:.5;cursor:not-allowed}input[type=text],input[type=password],input[type=time],input[type=number],select{width:100%;border:1px solid var(--line);border-radius:10px;padding:10px;background:white;color:var(--ink)}label{font-size:12px;color:var(--muted);display:block;margin-bottom:6px}.field{margin-bottom:12px}.sliderline{display:grid;grid-template-columns:1fr auto;gap:14px;align-items:center}.sliderline input{width:100%}.sens{font-size:24px;font-weight:750;min-width:54px;text-align:right}canvas{width:100%;height:128px;border:1px solid var(--line);border-radius:12px;background:#fbfcfc;display:block}.queue{display:grid;gap:8px}.event{border:1px solid var(--line);border-radius:11px;padding:10px 11px;display:grid;grid-template-columns:1fr auto;gap:10px;align-items:center}.event strong{font-size:13px;word-break:break-all}.event small{display:block;color:var(--muted);margin-top:2px}.empty{color:var(--muted);padding:8px 0}.message{margin-top:10px;font-size:13px;color:var(--muted);min-height:20px}.privacy{padding:12px 14px;background:var(--soft);border-radius:12px;font-size:13px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}.switcher{display:flex;gap:8px;align-items:center}.wifi-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.wifi-form .wide{grid-column:1/-1}@media(max-width:700px){.grid{grid-template-columns:1fr 1fr}.cards{grid-template-columns:1fr}.card.full{grid-column:auto}.wifi-form{grid-template-columns:1fr}.wifi-form .wide{grid-column:auto}}@media(max-width:420px){.grid{grid-template-columns:1fr 1fr}header{align-items:flex-start;flex-direction:column}.event{grid-template-columns:1fr}.event button{width:100%}}
</style>
</head>
<body>
@@ -64,6 +65,28 @@ static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
<p class="mono" id="firmwareVersion">Firmware: —</p>
</section>
<section class="card full" aria-labelledby="scheduleHeading">
<h2 id="scheduleHeading">Scheduled monitoring</h2>
<p class="sub">Europe/Amsterdam · adjusts for daylight saving. Overnight hours belong to the day they start. Equal start and end means 24 hours.</p>
<p id="monitorState" role="status">Loading monitoring status…</p>
<p id="monitorNext" class="sub"></p>
<p id="monitorFault" role="status"></p>
<form id="scheduleForm">
<div class="field"><label><input type="checkbox" id="scheduleEnabled"> Enable scheduled monitoring</label></div>
<div class="wifi-form">
<div class="field"><label for="weekdayStart">Monday–Friday start</label><input id="weekdayStart" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="12:00"></div>
<div class="field"><label for="weekdayEnd">Monday–Friday end</label><input id="weekdayEnd" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="01:00"></div>
<div class="field"><label for="weekendStart">Saturday–Sunday start</label><input id="weekendStart" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="12:00"></div>
<div class="field"><label for="weekendEnd">Saturday–Sunday end</label><input id="weekendEnd" type="text" inputmode="numeric" pattern="([01][0-9]|2[0-3]):[0-5][0-9]" maxlength="5" placeholder="HH:MM" title="24-hour time, HH:MM" required value="02:00"></div>
<div class="field"><label for="powerPreference">Outside monitoring hours</label><select id="powerPreference"><option value="1">Idle + Wi-Fi power saving</option><option value="0">Idle + responsive Wi-Fi</option></select></div>
<div class="field"><label for="overrideMinutes">Temporary monitoring (minutes)</label><input id="overrideMinutes" type="number" min="1" max="1440" value="30" required></div>
</div>
<p class="sub">Idle stops the microphone and keeps this page reachable. Hardware sleep is unavailable in this release pending V2 power-hold testing. BOOT wakes listening from idle; PWR keeps its existing function.</p>
<div class="row"><button type="submit" id="saveSchedule">Save schedule</button><button type="button" class="secondary" id="monitorOverride">Monitor temporarily</button><button type="button" class="secondary" id="monitorReturn">Return to schedule</button></div>
<div id="scheduleMessage" class="message" role="status"></div>
</form>
</section>
<section class="card full">
<div class="row" style="justify-content:space-between"><div><h2>Upload queue</h2><p class="sub">Files stay on the SD card until the server returns a successful response. Discard permanently removes recordings from this device and adjusts today's count.</p></div><div class="row"><button id="sendAll">Send all</button><button class="danger" id="clearQueue">Clear queue</button><button class="secondary" id="resetToday">Reset today count</button></div></div>
<div class="queue" id="eventList"><div class="empty">Loading queue…</div></div>
@@ -88,7 +111,7 @@ function stopPreview(){if(previewAudio){previewAudio.onended=null;previewAudio.o
function fmtBytes(n){if(n<1024)return n+' B';if(n<1048576)return (n/1024).toFixed(1)+' kB';return (n/1048576).toFixed(1)+' MB'}
function drawWave(points){const c=$('wave'),g=c.getContext('2d'),w=c.width,h=c.height;g.clearRect(0,0,w,h);g.strokeStyle='#d9e1df';g.lineWidth=1;g.beginPath();g.moveTo(0,h/2+.5);g.lineTo(w,h/2+.5);g.stroke();if(!points||!points.length)return;g.strokeStyle='#143f35';g.lineWidth=2;g.beginPath();points.forEach((p,i)=>{const x=i*(w/(points.length-1));const y=h/2-(p/100)*(h*.43);i?g.lineTo(x,y):g.moveTo(x,y)});g.stroke()}
async function api(path,opts={}){const r=await fetch(path,{cache:'no-store',...opts});let data={};try{data=await r.json()}catch(e){}if(!r.ok)throw new Error(data.error||('HTTP '+r.status));return data}
async function refreshStatus(){if(statusBusy)return;statusBusy=true;try{const s=await api('/api/status');$('today').textContent=s.today;$('queued').textContent=s.queue;$('clearQueue').disabled=!s.queue;$('mic').textContent=s.capturing?'Saving':'Listening';$('sd').textContent=s.sd?'Ready':'Missing';$('deviceAddress').textContent='IP: '+s.ip;$('ssidLine').textContent='Wi-Fi: '+(s.ssid||'—');$('firmwareVersion').textContent='Firmware: '+(s.version||'—');$('networkTop').textContent=s.wifi?('Connected · '+s.ip):(s.ap?'Setup AP · '+s.ip:'Offline');$('netDot').className='statusdot '+(s.wifi?'ok':(s.ap?'warn':'bad'));if(document.activeElement!==$('sensitivity')){$('sensitivity').value=s.sensitivity;$('sensValue').textContent=s.sensitivity}$('syncMessage').textContent=s.syncMessage||'';drawWave(s.waveform)}catch(e){$('networkTop').textContent='Interface unavailable';$('netDot').className='statusdot bad'}finally{statusBusy=false}}
async function refreshStatus(){if(statusBusy)return;statusBusy=true;try{const s=await api('/api/status');$('today').textContent=s.today;$('queued').textContent=s.queue;$('clearQueue').disabled=!s.queue;$('mic').textContent=s.capturing?'Saving':(s.monitoring.microphoneActive?'Listening':'Off');renderMonitor(s.monitoring);$('sd').textContent=s.sd?'Ready':'Missing';$('deviceAddress').textContent='IP: '+s.ip;$('ssidLine').textContent='Wi-Fi: '+(s.ssid||'—');$('firmwareVersion').textContent='Firmware: '+(s.version||'—');$('networkTop').textContent=s.wifi?('Connected · '+s.ip):(s.ap?'Setup AP · '+s.ip:'Offline');$('netDot').className='statusdot '+(s.wifi?'ok':(s.ap?'warn':'bad'));if(document.activeElement!==$('sensitivity')){$('sensitivity').value=s.sensitivity;$('sensValue').textContent=s.sensitivity}$('syncMessage').textContent=s.syncMessage||'';drawWave(s.waveform)}catch(e){$('networkTop').textContent='Interface unavailable';$('netDot').className='statusdot bad'}finally{statusBusy=false}}
async function refreshQueue(){if(queueBusy)return;queueBusy=true;try{const items=await api('/api/events'),box=$('eventList');const fingerprint=JSON.stringify(items);if(fingerprint===queueFingerprint)return;stopPreview();queueFingerprint=fingerprint;box.textContent='';if(!items.length){const e=document.createElement('div');e.className='empty';e.textContent='Queue is empty. Nice.';box.appendChild(e)}else items.forEach(item=>{const row=document.createElement('div');row.className='event';const info=document.createElement('div');const name=document.createElement('strong');name.textContent=item.name;const size=document.createElement('small');size.textContent=fmtBytes(item.bytes);info.append(name,size);const actions=document.createElement('div');actions.className='row';const b=document.createElement('button');b.className='secondary';b.textContent='Send';b.onclick=async()=>{b.disabled=true;try{await api('/api/sync',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({file:item.name})});$('syncMessage').textContent='Upload queued: '+item.name}catch(e){$('syncMessage').textContent=e.message}finally{setTimeout(refreshQueue,1200)}};const discard=document.createElement('button');discard.className='danger';discard.textContent='Discard';discard.setAttribute('aria-label','Discard '+item.name);discard.onclick=async()=>{if(!confirm('Permanently discard '+item.name+' from this device?'))return;discard.disabled=true;try{await api('/api/events/discard',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-BoomCast-Action':'discard'},body:new URLSearchParams({file:item.name})});$('syncMessage').textContent='Discarded '+item.name;await refreshQueue();await refreshStatus()}catch(e){$('syncMessage').textContent=e.message}finally{discard.disabled=false}};const play=document.createElement('button');play.className='secondary';play.textContent='Play';play.setAttribute('aria-label','Play '+item.name);play.onclick=async()=>{if(previewAudio&&previewButton===play){if(previewAudio.paused){try{await previewAudio.play();play.textContent='Pause';play.setAttribute('aria-label','Pause '+item.name)}catch(e){$('syncMessage').textContent='Could not play '+item.name}}else{previewAudio.pause();play.textContent='Play';play.setAttribute('aria-label','Play '+item.name)}return}stopPreview();const audio=new Audio('/api/events/audio?file='+encodeURIComponent(item.name));previewAudio=audio;previewButton=play;audio.onended=()=>stopPreview();audio.onerror=()=>{$('syncMessage').textContent='Could not load '+item.name;stopPreview()};try{await audio.play();play.textContent='Pause';play.setAttribute('aria-label','Pause '+item.name)}catch(e){$('syncMessage').textContent='Could not play '+item.name;stopPreview()}};actions.append(b,play,discard);row.append(info,actions);box.appendChild(row)})}catch(e){queueFingerprint='';$('eventList').textContent='Could not read queue: '+e.message}finally{queueBusy=false}}
$('sensitivity').addEventListener('input',e=>$('sensValue').textContent=e.target.value);$('sensitivity').addEventListener('change',async e=>{try{const d=await api('/api/sensitivity',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({value:e.target.value})});$('sensMessage').textContent='Saved at '+d.value+'%'}catch(err){$('sensMessage').textContent=err.message}});
$('sendAll').onclick=async()=>{try{await api('/api/sync',{method:'POST'});$('syncMessage').textContent='Upload of queued events requested.'}catch(e){$('syncMessage').textContent=e.message}};
@@ -99,6 +122,23 @@ $('wifiSelect').onchange=e=>{if(e.target.value)$('ssidInput').value=e.target.val
$('saveWifi').onclick=async()=>{const ssid=$('ssidInput').value.trim(),password=$('passwordInput').value;if(!ssid){$('wifiMessage').textContent='Enter an SSID first.';return}try{await api('/api/wifi',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams({ssid,password})});$('wifiMessage').textContent='Saved. BoomCast is rebooting…'}catch(e){$('wifiMessage').textContent=e.message}};
$('forgetWifi').onclick=async()=>{if(!confirm('Forget the saved Wi-Fi credentials and return to setup AP mode?'))return;try{await api('/api/wifi/forget',{method:'POST'});$('wifiMessage').textContent='Credentials removed. Rebooting…'}catch(e){$('wifiMessage').textContent=e.message}};
$('reboot').onclick=async()=>{try{await api('/api/reboot',{method:'POST'});$('wifiMessage').textContent='Rebooting…'}catch(e){$('wifiMessage').textContent=e.message}};
let scheduleLoaded=false;
const scheduleTimes=['weekdayStart','weekdayEnd','weekendStart','weekendEnd'];
function renderMonitor(m){
const names={MONITORING:'Monitoring',SCHEDULED_IDLE:'Scheduled idle',SCHEDULED_SLEEP:'Scheduled sleep',MANUAL_OVERRIDE:'Temporary monitoring'};
$('monitorState').textContent=(names[m.state]||m.state)+(m.overrideRemaining?' · '+Math.ceil(m.overrideRemaining/60)+' min remaining':'');
$('monitorNext').textContent='Next schedule transition: '+m.nextTransition+' · Last wake: '+m.wakeReason;
$('monitorFault').textContent=m.fault||'';
$('monitorReturn').disabled=!m.overrideRemaining;
if(!scheduleLoaded){
$('scheduleEnabled').checked=m.enabled;$('powerPreference').value=m.modemSleep?'1':'0';$('overrideMinutes').value=m.overrideMinutes;
scheduleTimes.forEach(id=>{$(id).value=String(Math.floor(m[id]/60)).padStart(2,'0')+':'+String(m[id]%60).padStart(2,'0')});
scheduleLoaded=true;
}
}
$('scheduleForm').onsubmit=async e=>{e.preventDefault();const button=$('saveSchedule');button.disabled=true;const body=new URLSearchParams({enabled:$('scheduleEnabled').checked?'1':'0',modemSleep:$('powerPreference').value,overrideMinutes:$('overrideMinutes').value});scheduleTimes.forEach(id=>body.set(id,$(id).value));try{await api('/api/monitoring',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-BoomCast-Action':'monitoring'},body});$('scheduleMessage').textContent='Schedule saved. Changes take effect after any current recording finishes.';await refreshStatus()}catch(err){$('scheduleMessage').textContent=err.message}finally{button.disabled=false}};
async function monitorAction(action){try{await api('/api/monitoring/'+action,{method:'POST',headers:{'X-BoomCast-Action':'monitoring'}});$('scheduleMessage').textContent=action==='override'?'Temporary monitoring requested.':'Returning to schedule.';await refreshStatus()}catch(err){$('scheduleMessage').textContent=err.message}}
$('monitorOverride').onclick=()=>monitorAction('override');$('monitorReturn').onclick=()=>monitorAction('return');
refreshStatus();refreshQueue();setInterval(refreshStatus,1000);setInterval(refreshQueue,4000);
</script>
</body>
@@ -127,6 +167,40 @@ void BoomWeb::begin() {
server_.collectHeaders(actionHeaders, 1);
server_.on("/", HTTP_GET, [this]() { handleRoot(); });
server_.on("/api/status", HTTP_GET, [this]() { handleStatus(); });
server_.on("/api/monitoring", HTTP_POST, [this]() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "monitoring") { sendJson(403, "{\"error\":\"Missing monitoring action header\"}"); return; }
BoomScheduleConfig c;
auto parseTime = [this](const char* key, uint16_t& value) {
String v = server_.arg(key);
if (v.length() != 5 || v[2] != ':' || !isDigit(v[0]) || !isDigit(v[1]) || !isDigit(v[3]) || !isDigit(v[4])) return false;
int h = v.substring(0,2).toInt(), m = v.substring(3).toInt();
if (h > 23 || m > 59) return false;
value = h * 60 + m; return true;
};
String minutes = server_.arg("overrideMinutes");
bool numeric = minutes.length() > 0 && minutes.length() <= 4;
for (size_t i = 0; i < minutes.length(); ++i) numeric = numeric && isDigit(minutes[i]);
String enabled = server_.arg("enabled"), modem = server_.arg("modemSleep");
c.enabled = enabled == "1"; c.modemSleep = modem == "1"; c.overrideMinutes = minutes.toInt();
if (!numeric || (enabled != "0" && enabled != "1") || (modem != "0" && modem != "1") ||
!parseTime("weekdayStart", c.weekdayStart) || !parseTime("weekdayEnd", c.weekdayEnd) ||
!parseTime("weekendStart", c.weekendStart) || !parseTime("weekendEnd", c.weekendEnd) || !c.valid()) {
sendJson(400, "{\"error\":\"Use valid 24-hour times and 1–1440 override minutes\"}"); return;
}
if (!boomMonitor.save(c)) { sendJson(500, "{\"error\":\"Could not persist schedule\"}"); return; }
sendJson(200, "{\"ok\":true}");
});
server_.on("/api/monitoring/override", HTTP_POST, [this]() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "monitoring") { sendJson(403, "{\"error\":\"Missing monitoring action header\"}"); return; }
boomMonitor.overrideNow(); sendJson(200, "{\"ok\":true}");
});
server_.on("/api/monitoring/return", HTTP_POST, [this]() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "monitoring") { sendJson(403, "{\"error\":\"Missing monitoring action header\"}"); return; }
boomMonitor.returnToSchedule(); sendJson(200, "{\"ok\":true}");
});
server_.on("/api/events", HTTP_GET, [this]() { handleEvents(); });
server_.on("/api/events/audio", HTTP_GET, [this]() { handleEventAudio(); });
server_.on("/api/wifi/scan", HTTP_GET, [this]() { handleWifiScan(); });
@@ -161,6 +235,7 @@ void BoomWeb::handleStatus() {
String json;
json.reserve(900);
json += "{\"version\":\"" + String(BOOMCAST_FIRMWARE_VERSION) + "\"";
json += ",\"monitoring\":" + boomMonitor.json();
json += ",\"wifi\":" + String(s.wifiConnected ? "true" : "false");
json += ",\"ap\":" + String(s.apMode ? "true" : "false");
json += ",\"sd\":" + String(s.sdReady ? "true" : "false");
@@ -0,0 +1,24 @@
# Detection parity with the browser listener
Reference: `django/frontend/src/scripts/burst-listener-worklet.js` in the same project. The firmware processes each mono PCM sample with the same level-window and trigger state machine. The browser code was not changed.
| Behaviour | Browser reference | ESP32 firmware |
| --- | --- | --- |
| Input | `Float32` mono samples, nominally -1 to +1, at the `AudioContext` rate | ES8311 16-bit stereo at 16 kHz; configured mic slot divided by 32768, then scaled by hardware calibration and the local sensitivity factor |
| Level window | `round(sampleRate / 30)` samples | `round(16000 / 30)` = 533 samples |
| RMS / peak | Square root of mean squared samples; maximum absolute sample in window | Same calculation in normalised units |
| Starting baseline | 0.01 | 0.01 |
| Baseline update | `0.98 * baseline + 0.02 * min(rms, baseline * 2)` while listening and not triggered | Same |
| Trigger | After more than 1 s and more than 3 s since last trigger: `rms > max(0.075, baseline * 5)` **and** `peak > 0.16` | Same sample counts and strict comparisons |
| Tail / clip | 2 s tail, final clip is at most the latest 10 s | 2 s tail, up to 8 s preceding the trigger plus tail, maximum 10 s |
| Resume | User resumes or discards; clears ring and baseline, starts 3 s cooldown | Automatically resumes after saving to SD; clears ring and baseline, starts 3 s cooldown |
The prior firmware used 256-frame (16 ms) windows, independent RMS **or** peak gates, an RMS and peak noise estimate, 3 s boot warmup, 1.5 s cooldown, and 2.5 s before/after the trigger. Those rules have been removed from detection. Its offline queue, upload receipt checks, and WAV format are unchanged.
## Hardware calibration
Shared browser constants are in `boomcast_config.h`. Hardware-only values are in `boomcast_audio_calibration.h`: the Waveshare example's ES8311 input gain is 45 dB, and the additional detection input multiplier starts at 1.0. The local sensitivity control scales the normalised detection input by `setting / 55`; its default 55 means unity. It does not alter the recorded WAV or browser thresholds. Change the hardware multiplier only after measuring representative ambient sound and fireworks on the actual V2 board. Avoid extra noise suppression, which could erase distant impulses.
The browser asks only for one channel in `getUserMedia`; it does not fix sample rate, echo cancellation, noise suppression, or automatic gain control. Browser support and selected values vary by device; [MediaStreamTrack.getSettings()](https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/getSettings) can expose the actual settings during a physical comparison. Safari/iPhone may apply processing that the ES8311 path does not. The browser's actual track settings and iPhone microphone level/clipping need a device measurement. The firmware's fixed mic slot, codec gain, acoustic response, and clipping also need verification with real V2 recordings. Equal PCM samples prove algorithm timing, not equal acoustic sensitivity.
Run `PATH=/path/to/node:$PATH python -m unittest discover -s arduino/tests -p 'test_detector_parity.py' -v` from the project root for deterministic traces. The test feeds identical 16-bit PCM samples to the compiled C++ detector and the actual unchanged browser worklet, comparing trigger, clip-start, and clip-end sample positions and final baseline across silence, a startup impulse, low-level kitchen activity, one impulse, repeated impulses, and overlap. Physical calibration remains separate.
@@ -0,0 +1,84 @@
# Scheduled monitoring — 0.4.0-concept
Version changes from **0.3.0-concept → 0.4.0-concept**. Scheduling is disabled by default, preserving continuous monitoring until enabled in local management.
## Available behavior
The authenticated management page adds weekday/weekend hours, a saved enable switch, Wi-Fi power preference and a temporary monitoring duration (1–1440 minutes, default 30). Suggested windows are Monday–Friday 12:00–01:00 and Saturday–Sunday 12:00–02:00. Settings are stored as one versioned NVS record. Invalid saved settings fail open to continuous monitoring.
Hours use Europe/Amsterdam and the current EU DST rule. Intervals belong to their starting day: Friday's window ends Saturday at 01:00; Sunday's ends Monday at 02:00. Equal times mean a full calendar day. Overlapping windows form a union, without unnecessary stop/start transitions. A nonexistent spring time moves forward by the skipped hour; an ambiguous autumn start uses its first occurrence and an end its last occurrence. Timezone legislation changes require updating `TZ_INFO` and its tests.
States exposed by `/api/status` under `monitoring`:
- `MONITORING`: listening requested, including while an active recording finishes before suspension. `microphoneActive` separately describes usable microphone input.
- `SCHEDULED_IDLE`: audio task has acknowledged suspension; local management remains available.
- `MANUAL_OVERRIDE`: temporary monitoring requested. The UI shows remaining seconds rounded to minutes. Override expiry uses monotonic time and is unaffected by NTP corrections. Overrides are intentionally not persisted across reboot.
- `SCHEDULED_SLEEP`: reserved; **not entered in this release**. `hardwareSleepSupported` is false.
A normal BOOT click while idle requests an override; during monitoring it still switches display pages. The web page can start an override or return immediately to the schedule. This is resume from idle, not remote wake from hardware sleep. PWR and BOOT-at-reset flashing behavior are not reassigned.
## Time and RTC
NTP uses `configTzTime` so synchronization does not replace Amsterdam with UTC. An NTP callback marks the clock trusted and writes UTC to PCF85063. A persisted `rtc_utc` marker distinguishes this firmware's NTP-set RTC from Waveshare example dates. Reboot restores UTC only if this marker, oscillator integrity, 24-hour/run mode, BCD fields and date are valid. Untrusted time keeps monitoring active and surfaces a fault. Once trusted, scheduling does not require Wi-Fi. Periodic SNTP updates refresh the RTC; failure to write RTC is reported while the current boot's NTP clock remains usable.
TLS still requires this boot's NTP synchronization through the existing uploader check. No CA, credentials or TLS-verification changes are made by this feature.
## Audio and power sequence
1. The main loop requests suspension, but the audio task owns codec operations. An active two-second tail and synchronous SD save complete first.
2. Both record and playback handles are closed. The pinned codec data driver disables both I2S DMA directions, and its ES8311 enable callback requests codec standby. Handles and PSRAM buffers stay allocated for reuse; `deinit_codec()` would also destroy the shared RTC I2C bus and is therefore unsuitable here.
3. The audio task acknowledges suspension and waits 200 ms between checks. The main loop reduces CPU frequency to 80 MHz; Wi-Fi modem sleep is optional. The radio remains connected, so SD uploads can continue during idle.
4. The display renders the static BoomCast/Zzz/SLAAPSTAND layout once, then stops its 5 ms LVGL tick timer. The display task checks at 500 ms; ordinary status refreshes are suppressed while idle. Display power gating is not enabled: the pinned driver lacks a public panel-sleep API, and safely gating SPI pins requires board verification.
5. On resume, CPU frequency is restored before audio is requested. The task reopens both streams, restores gain, clears rolling audio/trigger state, drains one second of input, then applies the detector's existing three-second cooldown. Detection thresholds and event clip lengths are unchanged.
Repeated read failures close/reopen the streams; failed opens retry once per second. Initial driver/task/PSRAM setup failure is diagnosed and requires a reboot using the existing management control. Automatic full driver teardown is deliberately avoided because the RTC shares its bus. The vendor close wrapper does not propagate all lower-level errors; actual DMA/codec shutdown and reopening still need hardware verification.
The existing uploader remains retry-safe and keeps files until a valid receipt. Bulk sends start no further item after a 30-second batch budget; an in-flight request may finish later. Individual transport phases have deadlines (TCP 5 s, TLS handshake 15 s, file transfer 30 s plus an in-progress write, response 60 s). Scheduler checks run between chunks and during response/NTP waits. A synchronous DNS/connect/write or display refresh can still delay a transition; timing is not a hard real-time guarantee. There is no wait for the whole SD queue before suspending audio. No queue entries are discarded by scheduling.
## Hardware inspection and deferred hardware sleep
Reviewed the pinned official Waveshare commit `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`, Arduino `11_RTC_Sleep_Test`, including `user_app.cpp`, `src/power/board_power_bsp.cpp`, `user_config.h`, and its SensorPCF85063 driver. Sources:
- https://docs.waveshare.com/ESP32-S3-ePaper-1.54
- https://github.com/waveshareteam/ESP32-S3-ePaper-1.54/tree/aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956/02_Example/Arduino/11_RTC_Sleep_Test
The V2 example identifies PCF85063 INT GPIO 5, BOOT GPIO 0 and PWR GPIO 18 as active-low EXT1 wake sources. It also drives GPIO 17 high before sleeping, holds it, and drops that hold on its PWR wake path. This is materially different from BoomCast's existing GPIO-17 initialization; it cannot be treated as merely an unused measurement rail when implementing hardware sleep. The example alarm helpers overwrite the calendar with a fixed 2025 test date and must not be copied into production scheduling.
Deep sleep, light sleep and RTC alarm programming are **not implemented/enabled** pending a physical V2 power-hold and button validation. RTC calendar retention is implemented; RTC alarms are not used for idle transitions. The ESP32 system clock supplies deadlines while awake. No alarm-success claim is exposed. Deep sleep must eventually combine verified RTC alarm setup/readback/clearing, GPIO wake diagnostics, a timer safety wake, safe SD/display shutdown, and a boot path that restores monitoring. Radio-off sleep cannot offer web wake.
The installed ESP32 core 3.3.12 S3 `qio_opi` SDK configuration does not enable `CONFIG_PM_ENABLE` or tickless idle. This release uses explicit idle CPU scaling and reduced task wake-ups; it does not pretend automatic light sleep is available, change global FreeRTOS configuration, or suspend a CPU core.
Current firmware has no independent heartbeat sender. Django's heartbeat endpoint records last-seen time but has no planned-sleep/expected-wake fields. No Django changes are made. Before radio-off sleep is enabled, extend that contract and its offline presentation; idle in this release remains network-accessible.
## Automated and browser verification
Run from the `arduino` directory:
```sh
g++ -std=c++17 -Wall -Wextra -Werror tests/schedule_test.cpp -o /tmp/boomcast-schedule-test
/tmp/boomcast-schedule-test
g++ -std=c++17 -Wall -Wextra -Werror tests/audio_session_test.cpp -o /tmp/boomcast-audio-session-test
/tmp/boomcast-audio-session-test
python3 tests/test_detector_parity.py
python3 tests/preview_management.py
```
Calendar tests cover weekday/weekend boundaries, overnight attribution, equal-time schedules, spring gaps, autumn repeated hours, disabled scheduling, trusted offline time, invalid time, override policy and reboot-time calculation. The production RTC decoder is checked against stopped/12-hour clocks, oscillator faults, malformed BCD and impossible calendar dates. The actual audio-task lifecycle policy and detector are tested over 100 simulated cycles: capture-drain gating, failed-open retry decisions, repeated read failure, startup input discard and cooldown-spike rejection. These are host simulations, not I2S/SD/NVS hardware tests.
Playwright checks the exact embedded HTML with the preview server's **simulated responses**, at desktop, intermediate and mobile widths. Save, override, return, reload, invalid-time validation, overflow and browser errors are checked. The preview does not execute firmware HTTP handlers or prove device persistence. Native time inputs displayed AM/PM in the browser locale; explicit validated HH:MM inputs fixed that observed issue.
## Physical validation still required — no board flashed
No current draw, wake accuracy or wake-to-listening latency has been measured. No ePaper rendering or physical capture-cycle validation is claimed. Before deployment:
- Flash only with the owner's authorization. Measure active and scheduled-idle current on battery and USB; record board revision and settings. Light/deep-sleep currents are N/A until implemented.
- Run at least 100 idle/resume cycles, inspect playable WAVs, stale-buffer/startup-spike behavior, heap and largest free block, codec/I2S stop/restart, and task watchdog behavior.
- End a window during recording and verify SD file/metadata integrity. Leave queued files through idle, reboot and connectivity loss; verify upload receipts and deduplication after reconnecting.
- Verify NVS persistence across power loss, PCF85063 retention/oscillator-stop detection, offline reboot, NTP recovery, and DST transitions using a controlled clock.
- Measure boundary-to-listening latency and actual recovery after codec initialization/read faults. Do not equate the designed settling/cooldown intervals with a measured wake latency.
- Inspect the 200×200 sleep screen, next-wake legibility, normal-screen restoration, BOOT override, and PWR behavior on the exact non-touch V2.
Final Arduino CLI compile (ESP32 core 3.3.12, ESP32S3 Dev Module, 8 MB flash,
OPI PSRAM, `default_8MB`) succeeded: **1,543,240 bytes / 3,342,336 (46%)**
program storage; **102,032 bytes / 327,680 (31%)** global dynamic memory.
Runtime heap, stack margins and power consumption are not established by this result.
@@ -2,8 +2,9 @@
- [ ] Confirm non-touch V2 marking, 8 MB flash and 8 MB PSRAM, and boot stability.
- [ ] Verify ES8311 microphone initialization and the actual slot assignment using known speech and impulse recordings.
- [ ] Capture and play a five-second WAV; check 16 kHz mono PCM header and duration.
- [ ] Verify 2.5-second pre-trigger and post-trigger content and startup short-preroll behavior.
- [ ] Capture and play a triggered WAV; check 16 kHz mono PCM header and actual duration (up to 10 seconds).
- [ ] Verify up to 8 seconds of pre-trigger content, the 2-second tail, and startup short-preroll behavior.
- [ ] Compare quiet room, kitchen activity, distant fireworks, and close impulses against iPhone Safari at the default sensitivity; note clipping and missed or false triggers before adjusting hardware calibration.
- [ ] Interrupt power during both WAV and metadata writes; verify recovery and that incomplete files never upload.
- [ ] Fill SD card near the configured reserve and confirm a visible error without overwriting queued clips.
- [ ] Verify ePaper listening, recording, queued/offline, uploading, success, retry, and error states.
@@ -13,4 +14,4 @@
- [ ] Disable Wi-Fi during capture and restore it; confirm automatic queue drain and no lost clip.
- [ ] Repeat capture/upload/outage cycles while measuring free heap, PSRAM, largest free PSRAM block, and recovery after failures.
No physical-board test has been performed in this workspace.
This detector revision has not been physically checked in this workspace.
+39
View File
@@ -0,0 +1,39 @@
#include "../BoomCast_Waveshare_Arduino/boomcast_audio_session.h"
#include "../BoomCast_Waveshare_Arduino/boomcast_detector.h"
#include <cassert>
#include <cstdio>
int main() {
using A = BoomAudioSession::Action;
BoomAudioSession session(16000);
assert(session.next(true, false) == A::Open);
// Failed initialization does not transition to read; the task retries open.
assert(session.next(true, false) == A::Open);
assert(session.next(false, false) == A::Suspend);
for (int cycle = 0; cycle < 100; ++cycle) {
session.opened();
assert(session.next(false, true) == A::Read); // finish active capture/save
assert(session.next(false, false) == A::Suspend); // persisted queue is independent
// Codec startup transients cannot enter trigger or pre-event buffers.
for (int block = 0; block < 63; ++block) assert(!session.usableRead(256));
assert(session.usableRead(256));
assert(session.next(true, false) == A::Read);
for (int failed = 0; failed < 9; ++failed) assert(!session.failedRead());
assert(session.failedRead()); // repeated DMA failure requests close/reopen
session.closed();
assert(session.next(true, false) == A::Open);
}
BoomDetector detector(16000, 533, 32000, 16000, 48000,
.01f, .02f, 2.f, .075f, 5.f, .16f);
for (int cycle = 0; cycle < 100; ++cycle) {
detector.reset();
assert(!detector.inTail());
// After each resume, reset preserves the full trigger cooldown.
for (int sample = 0; sample < 48000; ++sample)
assert(detector.process(sample < 533 ? 1.f : 0.f) == BoomDetector::Result::None);
bool triggered = false;
for (int sample = 0; sample < 1066; ++sample)
triggered |= detector.process(.8f) == BoomDetector::Result::Trigger;
assert(triggered);
}
puts("100 simulated audio cycles, capture draining, open/read failure recovery and startup-spike checks passed");
}
+8 -1
View File
@@ -7,13 +7,20 @@ int main() {
0.01f, 0.02f, 2.0f, 0.075f, 5.0f, 0.16f);
int16_t sample;
uint64_t frame = 0;
uint64_t listeningStart = 1;
uint64_t captureStart = 0;
while (std::fread(&sample, sizeof(sample), 1, stdin) == 1) {
++frame;
auto result = detector.process(float(sample) / 32768.0f);
if (result == BoomDetector::Result::Trigger) std::printf("T %llu\n", (unsigned long long)frame);
if (result == BoomDetector::Result::Trigger) {
captureStart = frame >= listeningStart + 128000 ? frame - 128000 + 1 : listeningStart;
std::printf("T %llu\n", (unsigned long long)frame);
}
if (result == BoomDetector::Result::TailDone) {
std::printf("S %llu\n", (unsigned long long)captureStart);
std::printf("E %llu\n", (unsigned long long)frame);
detector.reset();
listeningStart = frame + 1;
}
}
std::printf("B %.8f\n", detector.baseline());
+85
View File
@@ -0,0 +1,85 @@
"""Render the exact embedded management HTML with simulated device responses.
Browser/UI verification only: this does not emulate ESP32 peripherals or prove
firmware route behavior. Run: python3 tests/preview_management.py [port]
"""
import json
import re
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.parse import parse_qs
SOURCE = Path(__file__).resolve().parents[1] / 'BoomCast_Waveshare_Arduino/boomcast_web.cpp'
HTML = re.search(r'R"BOOMHTML\((.*?)\)BOOMHTML"', SOURCE.read_text(), re.S).group(1).encode()
MONITOR = dict(enabled=False, modemSleep=True, weekdayStart=720, weekdayEnd=60,
weekendStart=720, weekendEnd=120, overrideMinutes=30,
state='MONITORING', nextTransition='Continuous monitoring',
microphoneActive=True, overrideRemaining=0, clockTrusted=True,
rtcHealthy=True, fault='', wakeReason='Boot', hardwareSleepSupported=False)
class Preview(BaseHTTPRequestHandler):
def reply(self, data, status=200):
payload = json.dumps(data).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.end_headers()
html = re.search(r'R"BOOMHTML\((.*?)\)BOOMHTML"', SOURCE.read_text(), re.S).group(1).encode()
self.wfile.write(html)
elif self.path == '/api/status':
self.reply(dict(version='0.4.0-concept (SIMULATED)', today=0, queue=0, capturing=False,
sd=True, ip='127.0.0.1', ssid='Browser test fixture', wifi=True, ap=False,
sensitivity=55, syncMessage='', waveform=[0]*48, monitoring=MONITOR))
elif self.path == '/api/events':
self.reply([])
elif self.path == '/favicon.ico':
self.send_response(204); self.end_headers()
else:
self.reply({'error': 'Not found'}, 404)
def do_POST(self):
if self.headers.get('X-BoomCast-Action') != 'monitoring':
return self.reply({'error': 'Missing monitoring action header'}, 403)
if self.path == '/api/monitoring':
data = parse_qs(self.rfile.read(int(self.headers.get('Content-Length', 0))).decode())
try:
result = {}
for key in ('weekdayStart', 'weekdayEnd', 'weekendStart', 'weekendEnd'):
h, m = map(int, data[key][0].split(':'))
assert 0 <= h < 24 and 0 <= m < 60
result[key] = h*60+m
result['overrideMinutes'] = int(data['overrideMinutes'][0])
assert 1 <= result['overrideMinutes'] <= 1440
result['enabled'] = data['enabled'][0] == '1'
result['modemSleep'] = data['modemSleep'][0] == '1'
MONITOR.update(result)
except (ValueError, KeyError, AssertionError):
return self.reply({'error': 'Invalid schedule'}, 400)
self.normal()
elif self.path == '/api/monitoring/override':
MONITOR.update(state='MANUAL_OVERRIDE', overrideRemaining=MONITOR['overrideMinutes']*60,
microphoneActive=True, wakeReason='Manual override')
elif self.path == '/api/monitoring/return':
MONITOR['overrideRemaining'] = 0
self.normal()
else:
return self.reply({'error': 'Not found'}, 404)
self.reply({'ok': True})
def normal(self):
MONITOR.update(state='SCHEDULED_IDLE' if MONITOR['enabled'] else 'MONITORING',
microphoneActive=not MONITOR['enabled'],
nextTransition='Mon 12-10 12:00 CEST' if MONITOR['enabled'] else 'Continuous monitoring')
def log_message(self, *args):
pass
if __name__ == '__main__':
HTTPServer(('127.0.0.1', int(sys.argv[1]) if len(sys.argv)>1 else 8765), Preview).serve_forever()
+61
View File
@@ -0,0 +1,61 @@
#include "../BoomCast_Waveshare_Arduino/boomcast_schedule.h"
#include "../BoomCast_Waveshare_Arduino/boomcast_rtc.h"
#include <cassert>
#include <cstdlib>
#include <cstdio>
time_t at(int month, int day, int hour, int minute = 0, int dst = -1) {
tm t{}; t.tm_year = 126; t.tm_mon = month-1; t.tm_mday = day;
t.tm_hour = hour; t.tm_min = minute; t.tm_isdst = dst; return mktime(&t);
}
int main() {
setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 1); tzset();
BoomScheduleConfig c; c.enabled = true;
using namespace BoomSchedule;
assert(active(c, at(10,9,23))); // Friday
assert(active(c, at(10,10,0,59))); // Friday window until 01:00
assert(!active(c, at(10,10,1)));
assert(nextTransition(c, at(10,9,23)) == at(10,10,1));
assert(!active(c, at(10,10,11,59)));
assert(active(c, at(10,10,12)));
assert(active(c, at(10,11,1,59)));
assert(!active(c, at(10,11,2)));
assert(active(c, at(10,12,1,59))); // Sunday into Monday uses Sunday
assert(!active(c, at(10,12,2)));
assert(nextTransition(c, at(10,12,3)) == at(10,12,12)); // reboot offline
assert(shouldMonitor(c, at(10,12,3), false, false)); // invalid RTC fail open
assert(!shouldMonitor(c, at(10,12,3), true, false)); // offline valid RTC
assert(shouldMonitor(c, at(10,12,3), true, true)); // override
assert(!shouldMonitor(c, at(10,12,3), true, false)); // expiration/return
c.enabled = false; assert(active(c, at(10,12,3))); assert(!nextTransition(c, at(10,12,3)));
c.enabled = true;
c.weekdayStart = c.weekdayEnd = c.weekendStart = c.weekendEnd = 720;
assert(active(c, at(10,12,3))); assert(nextTransition(c, at(10,12,3)) == 0);
c.weekdayStart = c.weekendStart = 9*60; c.weekdayEnd = c.weekendEnd = 17*60;
assert(!active(c, at(10,12,8,59))); assert(active(c, at(10,12,9)));
assert(!active(c, at(10,12,17)));
// Overnight spring gap: non-existent 02:30 resolves to 03:30.
c.weekdayStart = c.weekendStart = 12*60; c.weekdayEnd = c.weekendEnd = 150;
assert(active(c, at(3,29,3,29)));
assert(!active(c, at(3,29,3,30)));
assert(nextTransition(c, at(3,28,23)) == at(3,29,3,30));
// Autumn repeated hour: both 02:15s remain monitored, ends at later 02:30.
assert(active(c, at(10,25,2,15,1))); assert(active(c, at(10,25,2,15,0)));
assert(nextTransition(c, at(10,24,23)) == at(10,25,2,30,0));
assert(!active(c, at(10,25,2,30,0)));
// Repeated start chooses first occurrence; overlapping windows stay active.
c.weekdayStart = c.weekendStart = 150; c.weekdayEnd = c.weekendEnd = 240;
assert(active(c, at(10,25,2,30,1))); assert(active(c, at(10,25,2,15,0)));
c.weekdayStart=1440; assert(!c.valid()); assert(active(c, at(10,12,3)));
uint8_t rtc[7] = {0x30,0x15,0x10,0x10,0x06,0x10,0x26};
time_t decoded;
assert(BoomRtc::decode(0, rtc, decoded));
assert(decoded == at(10,10,12,15) + 30); // UTC 10:15 = Amsterdam 12:15
assert(!BoomRtc::decode(0x20, rtc, decoded)); // clock stopped
assert(!BoomRtc::decode(0x08, rtc, decoded)); // 12h mode unsupported
rtc[0] |= 0x80; assert(!BoomRtc::decode(0, rtc, decoded)); // oscillator fault
rtc[0] = 0x6a; assert(!BoomRtc::decode(0, rtc, decoded)); // malformed BCD
rtc[0] = 0; rtc[3] = 0x31; rtc[5] = 0x02;
assert(!BoomRtc::decode(0, rtc, decoded)); // impossible February day
puts("Scheduler calendar, DST, clock validity and override policy checks passed");
}
+7 -3
View File
@@ -27,6 +27,7 @@ def samples(kind):
for j in range(round(duration * RATE)):
if start + j < length:
values[start + j] = round(amplitude * 32767 * math.sin(j * .28))
if kind == "startup": bang(.2)
if kind == "kitchen":
for at in (2, 4, 7):
bang(at, .15, .12) # below the browser's peak gate
@@ -53,7 +54,7 @@ class DetectorParity(unittest.TestCase):
cls.directory.cleanup()
def test_reference_traces(self):
for kind in ("silence", "kitchen", "impulse", "repeated", "overlap"):
for kind in ("silence", "startup", "kitchen", "impulse", "repeated", "overlap"):
with self.subTest(kind=kind):
path = Path(self.directory.name) / f"{kind}.pcm"
raw = array('h', samples(kind))
@@ -63,8 +64,11 @@ class DetectorParity(unittest.TestCase):
browser = subprocess.check_output(["node", str(JS), str(REFERENCE), str(path)], text=True).splitlines()
self.assertEqual(firmware[:-1], browser[:-1])
self.assertAlmostEqual(float(firmware[-1][2:]), float(browser[-1][2:]), delta=0.00002)
if kind == "silence" or kind == "kitchen": self.assertFalse(firmware[:-1])
else: self.assertIn("T ", firmware[0])
if kind in {"silence", "startup", "kitchen"}: self.assertFalse(firmware[:-1])
else:
self.assertEqual(sum(line.startswith("T ") for line in firmware), 2 if kind == "repeated" else 1)
self.assertEqual(sum(line.startswith("S ") for line in firmware), 2 if kind == "repeated" else 1)
self.assertEqual(sum(line.startswith("E ") for line in firmware), 2 if kind == "repeated" else 1)
if __name__ == "__main__": unittest.main()
+2 -1
View File
@@ -3,7 +3,7 @@ const vm = require('vm');
const source = fs.readFileSync(process.argv[2], 'utf8');
let Processor;
class AudioWorkletProcessor {
constructor() { this.port = { postMessage(message) { messages.push({ type: message.type, frame: processor.frame }); } }; }
constructor() { this.port = { postMessage(message) { messages.push({ type: message.type, frame: processor.frame, length: message.samples?.length }); } }; }
}
let messages = [];
vm.runInNewContext(source, {
@@ -22,6 +22,7 @@ for (let offset = 0; offset < bytes.length;) {
for (const message of messages) {
if (message.type === 'trigger') process.stdout.write(`T ${message.frame}\n`);
if (message.type === 'clip') {
process.stdout.write(`S ${message.frame - message.length + 1}\n`);
process.stdout.write(`E ${message.frame}\n`);
processor.reset();
}