fixing ui stuff

This commit is contained in:
Joren de Graaf
2026-10-09 19:10:42 +02:00
parent dad0001df1
commit 2b0bbdd201
12 changed files with 175 additions and 27 deletions
+11 -5
View File
@@ -10,15 +10,21 @@ Arduino sketch for the **non-touch V2** board. This folder is the imported `v0.1
- 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. - 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.
- 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. - 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. - Wi-Fi setup AP, local owner UI, two ePaper screens, automatic upload retry with bounded backoff, and confirmed-receipt deletion.
- CA-verified HTTPS and an ignored local configuration header. No insecure TLS mode is enabled. - 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.
## Build and flash ## Build and flash
1. Install Arduino IDE 2.x and Espressif ESP32 Arduino core **3.3.0**. 1. Install Arduino IDE 2.x and Espressif ESP32 Arduino core **3.3.12** (the verified version with a built-in CA bundle).
2. Install **ArduinoJson 7.4.3** and Waveshare's `lvgl8/lvgl` **8.4.0** library from the pinned support commit below. Install LVGL 8 only for this sketch. 2. Install **ArduinoJson 7.4.3** and Waveshare's `lvgl8/lvgl` **8.4.0** library from the pinned support commit below. Install LVGL 8 only for this sketch.
3. Run `./prepare_from_waveshare.sh`. It fetches only `02_Example/Arduino/08_Audio_Test` from Waveshare commit `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`, or accepts a local checkout at that exact commit. The helper copies the board support locally. See [hardware and dependency notes](docs/hardware.md). 3. Run `./prepare_from_waveshare.sh`. It fetches only `02_Example/Arduino/08_Audio_Test` from Waveshare commit `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`, or accepts a local checkout at that exact commit. The helper copies the board support locally. See [hardware and dependency notes](docs/hardware.md).
4. Copy `boomcast_config.local.example.h` to `boomcast_config.local.h`. Set the HTTPS origin, registered `sensor_id`, token, and trusted CA certificate. This local file is ignored by Git. A renewed server certificate signed by the same CA needs no firmware change. 4. Copy `boomcast_config.local.example.h` to `boomcast_config.local.h`. Set the HTTPS origin, registered `sensor_id`, and token. This local file is ignored by Git; no certificate needs to be pasted into it.
5. Select `ESP32S3 Dev Module`, 8 MB flash, and OPI PSRAM. Open `BoomCast_Waveshare_Arduino.ino`, compile, flash, and monitor serial at 115200 baud. An Arduino CLI 1.5.1 compile passed in this workspace with ESP32 core 3.3.0 and partition scheme `default_8MB`; no board was flashed. 5. In Arduino IDE **Tools**, select board **ESP32S3 Dev Module**, **Flash Size → 8MB (64Mb)**, **Partition Scheme → 8M with spiffs (3MB APP/1.5MB SPIFFS)**, and **PSRAM → OPI PSRAM**. All four settings are required for this board; the default 4 MB partition allows only a 1.2 MB app and reports `text section exceeds available space in board`. Open `BoomCast_Waveshare_Arduino.ino`, compile, flash, and monitor serial at 115200 baud. An Arduino CLI 1.5.1 compile passed in this workspace with ESP32 core 3.3.12 and these settings; no board was flashed.
## HTTPS trust and renewal
The uploader uses `WiFiClientSecure::useBuiltinCACertBundle()` from Espressif's Arduino ESP32 core 3.3.12. The core's public CA bundle is compiled into the firmware, separate from `boomcast_config.local.h` credentials. TLS verifies both the certificate chain and the server hostname. Uploads wait for a successful NTP synchronization after boot, so an unset clock cannot invalidate certificate date checks. If NTP is unavailable, the WAV remains queued for retry.
Normal Caddy/Let's Encrypt server-certificate renewals need no firmware change as long as the renewed chain ends at a root in the installed bundle. If Caddy changes to a CA whose root is absent from that bundle, update the Espressif core and recompile/reflash the firmware with its newer bundle after checking that the new core still builds the sketch. Do not put a leaf certificate or private key in the credentials header. Arduino IDE's `HTTPClient` can fall back to insecure TLS when used without a CA; this uploader uses `WiFiClientSecure` directly with the built-in bundle instead.
The firmware has not yet been converted to PlatformIO: Waveshare's Arduino support uses a sketch-relative source layout, and a guessed PlatformIO configuration would not be reproducible without a verified V2 build. The pinned preparation script and library versions provide an explicit Arduino build starting point. The firmware has not yet been converted to PlatformIO: Waveshare's Arduino support uses a sketch-relative source layout, and a guessed PlatformIO configuration would not be reproducible without a verified V2 build. The pinned preparation script and library versions provide an explicit Arduino build starting point.
@@ -26,7 +32,7 @@ The firmware has not yet been converted to PlatformIO: Waveshare's Arduino suppo
On first boot, the device generates unique setup-AP and local-management passwords and stores them in NVS. They are printed on USB serial at 115200 baud on boot; keep physical access to the serial port controlled. The sensor token is loaded from the ignored local header, or from an NVS `token` value if provisioned separately. Rotate the sensor token in Django, update the local header, and reflash, or provision the new NVS value through a trusted local maintenance process. Tokens are never logged by this firmware. On first boot, the device generates unique setup-AP and local-management passwords and stores them in NVS. They are printed on USB serial at 115200 baud on boot; keep physical access to the serial port controlled. The sensor token is loaded from the ignored local header, or from an NVS `token` value if provisioned separately. Rotate the sensor token in Django, update the local header, and reflash, or provision the new NVS value through a trusted local maintenance process. Tokens are never logged by this firmware.
The local management UI uses HTTP Basic Auth on the device LAN and setup AP. Use trusted local networks; Basic Auth does not encrypt traffic. The public ePaper screen retains the short privacy message, while the owner screen shows connectivity, queue count, capture/upload state, and diagnostic counters. The local management UI uses HTTP Basic Auth on the device LAN and setup AP. Use trusted local networks; Basic Auth does not encrypt traffic. The Upload queue section can discard one recording or clear the backlog after confirmation; discarded clips are permanently removed from the SD card and will not reach Pending Review. Discarding a recording dated today reduces the ePaper's "Vandaag" count; successful uploads still count as captures. Clips saved without a valid clock cannot be matched to a day, so **Reset today count** can clear an old or stale total without deleting recordings. The public ePaper screen retains the short privacy message, while the owner screen shows connectivity, queue count, capture/upload state, and diagnostic counters.
## Server and queue behavior ## Server and queue behavior
@@ -36,14 +36,10 @@ constexpr const char* MANAGEMENT_USER = "admin";
#ifndef BOOMCAST_SENSOR_TOKEN #ifndef BOOMCAST_SENSOR_TOKEN
#define BOOMCAST_SENSOR_TOKEN "" #define BOOMCAST_SENSOR_TOKEN ""
#endif #endif
#ifndef BOOMCAST_CA_CERT
#define BOOMCAST_CA_CERT ""
#endif
constexpr const char* SERVER_BASE_URL = BOOMCAST_SERVER_BASE_URL; constexpr const char* SERVER_BASE_URL = BOOMCAST_SERVER_BASE_URL;
constexpr const char* SUBMIT_PATH = "/api/pending/"; constexpr const char* SUBMIT_PATH = "/api/pending/";
constexpr uint32_t SENSOR_ID = BOOMCAST_SENSOR_ID; constexpr uint32_t SENSOR_ID = BOOMCAST_SENSOR_ID;
constexpr const char* SENSOR_TOKEN = BOOMCAST_SENSOR_TOKEN; constexpr const char* SENSOR_TOKEN = BOOMCAST_SENSOR_TOKEN;
constexpr const char* SERVER_CA_CERT = BOOMCAST_CA_CERT;
// Audio pipeline: matches the earlier Atom Echo / YAMNet 16 kHz mono design. // Audio pipeline: matches the earlier Atom Echo / YAMNet 16 kHz mono design.
constexpr uint32_t AUDIO_SAMPLE_RATE = 16000; constexpr uint32_t AUDIO_SAMPLE_RATE = 16000;
@@ -1,9 +1,6 @@
#pragma once #pragma once
// Copy to boomcast_config.local.h, which is excluded from Git. Use a CA that // Copy to boomcast_config.local.h, which is excluded from Git.
// signs your server; ordinary leaf-certificate renewal then needs no reflash. // Public CA trust comes from the ESP32 core's built-in certificate bundle.
#define BOOMCAST_SERVER_BASE_URL "https://boomcast.example.com" #define BOOMCAST_SERVER_BASE_URL "https://boomcast.example.com"
#define BOOMCAST_SENSOR_ID 1 #define BOOMCAST_SENSOR_ID 1
#define BOOMCAST_SENSOR_TOKEN "paste-once-token-here" #define BOOMCAST_SENSOR_TOKEN "paste-once-token-here"
#define BOOMCAST_CA_CERT R"PEM(-----BEGIN CERTIFICATE-----
PASTE_TRUSTED_CA_CERTIFICATE_HERE
-----END CERTIFICATE-----)PEM"
@@ -351,8 +351,10 @@ void BoomDisplay::update() {
if (!changed) return; if (!changed) return;
if (lock()) { if (lock()) {
applySnapshot(current); applySnapshot(current);
// Clear old digits after a discard or explicit counter reset on ePaper.
if (haveLast_ && current.todayEvents < last_.todayEvents) requestFullRefresh();
unlock(); unlock();
last_ = current;
haveLast_ = true;
} }
last_ = current;
haveLast_ = true;
} }
+50 -3
View File
@@ -25,6 +25,18 @@ static uint32_t metaChecksum(const BoomEventMeta& meta) {
return hash; return hash;
} }
static bool queuedToday(const BoomEventMeta& meta) {
// queuedMs records when the clip was saved and the "today" count increased.
// Older recordings without a valid clock cannot be dated reliably; the
// owner can use the explicit counter reset for those legacy clips.
if (!meta.queuedMs) return false;
time_t recordedAt = meta.queuedMs / 1000;
time_t now = time(nullptr);
struct tm recorded = {}, current = {};
return localtime_r(&recordedAt, &recorded) && localtime_r(&now, &current) &&
recorded.tm_year == current.tm_year && recorded.tm_yday == current.tm_yday;
}
static bool writeAll(FILE* f, const void* data, size_t bytes) { static bool writeAll(FILE* f, const void* data, size_t bytes) {
return fwrite(data, 1, bytes, f) == bytes; return fwrite(data, 1, bytes, f) == bytes;
} }
@@ -199,13 +211,48 @@ size_t BoomQueue::fileSize(const String& filename) const {
bool BoomQueue::remove(const String& filename) { bool BoomQueue::remove(const String& filename) {
if (!ready_ || !exists(filename)) return false; if (!ready_ || !exists(filename)) return false;
String meta = absolutePath(filename); meta.remove(meta.length() - 4); meta += ".meta"; bool ok = removeFiles(filename);
if (unlink(meta.c_str()) != 0) return false;
bool ok = unlink(absolutePath(filename).c_str()) == 0;
refreshCount(); refreshCount();
return ok; return ok;
} }
bool BoomQueue::discard(const String& filename) {
BoomEventMeta meta;
if (!ready_ || !readMeta(filename, meta)) return false;
bool today = queuedToday(meta);
bool ok = removeFiles(filename);
refreshCount();
if (ok && today) boomState.discardTodayEvents(1);
return ok;
}
bool BoomQueue::removeFiles(const String& filename) {
String meta = absolutePath(filename); meta.remove(meta.length() - 4); meta += ".meta";
if (unlink(meta.c_str()) != 0) return false;
return unlink(absolutePath(filename).c_str()) == 0;
}
int BoomQueue::clearAll() {
if (!ready_) return -1;
int removed = 0;
int todayRemoved = 0;
String batch[MAX_QUEUE_ITEMS_SHOWN];
size_t found;
while ((found = listNames(batch, MAX_QUEUE_ITEMS_SHOWN)) != 0) {
for (size_t i = 0; i < found; ++i) {
BoomEventMeta meta;
if (!readMeta(batch[i], meta)) { refreshCount(); boomState.discardTodayEvents(todayRemoved); return -1; }
bool today = queuedToday(meta);
if (!removeFiles(batch[i])) { refreshCount(); boomState.discardTodayEvents(todayRemoved); return -1; }
++removed;
if (today) ++todayRemoved;
}
}
refreshCount();
boomState.discardTodayEvents(todayRemoved);
return removed;
}
size_t BoomQueue::listNames(String* out, size_t maxItems) { size_t BoomQueue::listNames(String* out, size_t maxItems) {
if (!ready_ || !out || !maxItems) return 0; if (!ready_ || !out || !maxItems) return 0;
DIR* dir = opendir(QUEUE_DIR); if (!dir) return 0; DIR* dir = opendir(QUEUE_DIR); if (!dir) return 0;
@@ -22,6 +22,8 @@ public:
uint64_t triggeredMs = 0); uint64_t triggeredMs = 0);
bool readMeta(const String& filename, BoomEventMeta& meta) const; bool readMeta(const String& filename, BoomEventMeta& meta) const;
bool remove(const String& filename); bool remove(const String& filename);
bool discard(const String& filename);
int clearAll(); // Returns removed recordings, or -1 if a deletion failed.
bool exists(const String& filename) const; bool exists(const String& filename) const;
size_t fileSize(const String& filename) const; size_t fileSize(const String& filename) const;
String absolutePath(const String& filename) const; String absolutePath(const String& filename) const;
@@ -32,6 +34,7 @@ private:
bool ready_ = false; bool ready_ = false;
int count_ = 0; int count_ = 0;
bool ensureQueueDir(); bool ensureQueueDir();
bool removeFiles(const String& filename);
String makeFilename(const char* triggerType); String makeFilename(const char* triggerType);
bool writeWavFile(const char* path, const int16_t* samples, size_t sampleCount); bool writeWavFile(const char* path, const int16_t* samples, size_t sampleCount);
bool validWav(const String& filename, uint32_t samples) const; bool validWav(const String& filename, uint32_t samples) const;
@@ -131,6 +131,24 @@ void BoomState::incrementTodayEvents() {
preferences_.putInt("today", value); preferences_.putInt("today", value);
} }
void BoomState::discardTodayEvents(int count) {
if (count <= 0) return;
rollDayIfNeeded();
int value;
xSemaphoreTake(mutex_, portMAX_DELAY);
state_.todayEvents = max(0, state_.todayEvents - count);
value = state_.todayEvents;
xSemaphoreGive(mutex_);
preferences_.putInt("today", value);
}
void BoomState::resetTodayEvents() {
xSemaphoreTake(mutex_, portMAX_DELAY);
state_.todayEvents = 0;
xSemaphoreGive(mutex_);
preferences_.putInt("today", 0);
}
void BoomState::requestSync(const String& filename) { void BoomState::requestSync(const String& filename) {
xSemaphoreTake(mutex_, portMAX_DELAY); xSemaphoreTake(mutex_, portMAX_DELAY);
syncRequested_ = true; syncRequested_ = true;
@@ -39,6 +39,8 @@ public:
void rollDayIfNeeded(); void rollDayIfNeeded();
void incrementTodayEvents(); void incrementTodayEvents();
void discardTodayEvents(int count);
void resetTodayEvents();
void requestSync(const String& filename = ""); void requestSync(const String& filename = "");
bool takeSyncRequest(String& filename); bool takeSyncRequest(String& filename);
@@ -7,6 +7,7 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <stdio.h> #include <stdio.h>
#include <time.h> #include <time.h>
#include "esp_sntp.h"
#include "esp_heap_caps.h" #include "esp_heap_caps.h"
BoomUploader boomUploader; BoomUploader boomUploader;
@@ -44,6 +45,19 @@ static void addPart(String& body, const String& boundary, const char* name, cons
body += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n"; body += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n";
} }
static bool waitForNtpTime() {
// SNTP reports COMPLETED once per synchronization. Retain that result for
// later uploads; a reboot clears it and requires a new NTP sync.
static bool synchronized = false;
const uint32_t started = millis();
while (!synchronized && boomNetwork.connected() && millis() - started < 20000) {
if (sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED) synchronized = true;
if (!synchronized) delay(100);
}
time_t now = time(nullptr);
return synchronized && now >= 1704067200; // Reject an unset or implausible clock.
}
bool BoomUploader::submitOne(const String& filename) { bool BoomUploader::submitOne(const String& filename) {
if (!queue_ || !queue_->ready() || !boomNetwork.connected() || !queue_->exists(filename)) return false; if (!queue_ || !queue_->ready() || !boomNetwork.connected() || !queue_->exists(filename)) return false;
boomState.setSyncing(true, "Uploading " + filename); boomState.setSyncing(true, "Uploading " + filename);
@@ -88,8 +102,8 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
BoomEventMeta meta; BoomEventMeta meta;
if (!queue_->readMeta(filename, meta)) return false; if (!queue_->readMeta(filename, meta)) return false;
String token = boomState.prefs().getString("token", SENSOR_TOKEN); String token = boomState.prefs().getString("token", SENSOR_TOKEN);
if (!token.length() || !SENSOR_ID || !strlen(SERVER_CA_CERT)) { if (!token.length() || !SENSOR_ID) {
Serial.println("[Upload] sensor ID, token or CA certificate missing"); Serial.println("[Upload] sensor ID or token missing");
permanentFailure_ = true; permanentFailure_ = true;
return false; return false;
} }
@@ -106,6 +120,11 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
if (colon >= 0) { port = host.substring(colon + 1).toInt(); host = host.substring(0, colon); } if (colon >= 0) { port = host.substring(colon + 1).toInt(); host = host.substring(0, colon); }
if (!host.length() || !port) return false; if (!host.length() || !port) return false;
if (!waitForNtpTime()) {
Serial.println("[Upload] waiting for NTP time before TLS validation");
return false;
}
FILE* file = fopen(path.c_str(), "rb"); FILE* file = fopen(path.c_str(), "rb");
if (!file) return false; if (!file) return false;
const size_t fileBytes = queue_->fileSize(filename); const size_t fileBytes = queue_->fileSize(filename);
@@ -128,7 +147,7 @@ bool BoomUploader::doPost(const String& filename, const String& path) {
const size_t length = preamble.length() + fileBytes + trailer.length(); const size_t length = preamble.length() + fileBytes + trailer.length();
WiFiClientSecure client; WiFiClientSecure client;
client.setCACert(SERVER_CA_CERT); client.useBuiltinCACertBundle();
client.setTimeout(60); client.setTimeout(60);
Serial.printf("[Upload] free heap=%u PSRAM=%u largest PSRAM=%u\n", Serial.printf("[Upload] free heap=%u PSRAM=%u largest PSRAM=%u\n",
unsigned(ESP.getFreeHeap()), unsigned(ESP.getFreePsram()), unsigned(ESP.getFreeHeap()), unsigned(ESP.getFreePsram()),
+59 -3
View File
@@ -63,7 +63,7 @@ static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
</section> </section>
<section class="card full"> <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.</p></div><button id="sendAll">Send all</button></div> <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> <div class="queue" id="eventList"><div class="empty">Loading queue…</div></div>
<div class="message" id="syncMessage"></div> <div class="message" id="syncMessage"></div>
</section> </section>
@@ -85,10 +85,12 @@ const $=id=>document.getElementById(id);let statusBusy=false,queueBusy=false;
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 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()} 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 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;$('mic').textContent=s.capturing?'Saving':'Listening';$('sd').textContent=s.sd?'Ready':'Missing';$('deviceAddress').textContent='IP: '+s.ip;$('ssidLine').textContent='Wi-Fi: '+(s.ssid||'—');$('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':'Listening';$('sd').textContent=s.sd?'Ready':'Missing';$('deviceAddress').textContent='IP: '+s.ip;$('ssidLine').textContent='Wi-Fi: '+(s.ssid||'—');$('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');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 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)}};row.append(info,b);box.appendChild(row)})}catch(e){$('eventList').textContent='Could not read queue: '+e.message}finally{queueBusy=false}} async function refreshQueue(){if(queueBusy)return;queueBusy=true;try{const items=await api('/api/events'),box=$('eventList');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}};actions.append(b,discard);row.append(info,actions);box.appendChild(row)})}catch(e){$('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}}); $('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}}; $('sendAll').onclick=async()=>{try{await api('/api/sync',{method:'POST'});$('syncMessage').textContent='Upload of queued events requested.'}catch(e){$('syncMessage').textContent=e.message}};
$('clearQueue').onclick=async()=>{const count=Number($('queued').textContent)||0;if(!count)return;if(!confirm('Permanently discard all '+count+' queued recording(s) from this device? They cannot be recovered.'))return;const b=$('clearQueue');b.disabled=true;try{const result=await api('/api/events/discard',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded','X-BoomCast-Action':'discard'},body:new URLSearchParams({all:'1'})});$('syncMessage').textContent='Discarded '+result.removed+' queued recording(s).';await refreshQueue();await refreshStatus()}catch(e){$('syncMessage').textContent=e.message}finally{b.disabled=false}};
$('resetToday').onclick=async()=>{if(!confirm('Reset the ePaper today count to zero? Queued recordings will stay on the SD card.'))return;const b=$('resetToday');b.disabled=true;try{await api('/api/today/reset',{method:'POST',headers:{'X-BoomCast-Action':'discard'}});$('syncMessage').textContent='Today count reset.';await refreshStatus()}catch(e){$('syncMessage').textContent=e.message}finally{b.disabled=false}};
$('scanWifi').onclick=async()=>{const b=$('scanWifi');b.disabled=true;$('wifiMessage').textContent='Scanning…';try{const nets=await api('/api/wifi/scan'),sel=$('wifiSelect');sel.textContent='';const empty=document.createElement('option');empty.value='';empty.textContent='Choose a network or type it below';sel.appendChild(empty);nets.forEach(n=>{const o=document.createElement('option');o.value=n.ssid;o.textContent=n.ssid+' · '+n.rssi+' dBm'+(n.secure?' · secured':'');sel.appendChild(o)});$('wifiMessage').textContent=nets.length+' network(s) found.'}catch(e){$('wifiMessage').textContent=e.message}finally{b.disabled=false}}; $('scanWifi').onclick=async()=>{const b=$('scanWifi');b.disabled=true;$('wifiMessage').textContent='Scanning…';try{const nets=await api('/api/wifi/scan'),sel=$('wifiSelect');sel.textContent='';const empty=document.createElement('option');empty.value='';empty.textContent='Choose a network or type it below';sel.appendChild(empty);nets.forEach(n=>{const o=document.createElement('option');o.value=n.ssid;o.textContent=n.ssid+' · '+n.rssi+' dBm'+(n.secure?' · secured':'');sel.appendChild(o)});$('wifiMessage').textContent=nets.length+' network(s) found.'}catch(e){$('wifiMessage').textContent=e.message}finally{b.disabled=false}};
$('wifiSelect').onchange=e=>{if(e.target.value)$('ssidInput').value=e.target.value}; $('wifiSelect').onchange=e=>{if(e.target.value)$('ssidInput').value=e.target.value};
$('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}}; $('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}};
@@ -118,6 +120,8 @@ void BoomWeb::sendJson(int code, const String& json) {
} }
void BoomWeb::begin() { void BoomWeb::begin() {
const char* actionHeaders[] = {"X-BoomCast-Action"};
server_.collectHeaders(actionHeaders, 1);
server_.on("/", HTTP_GET, [this]() { handleRoot(); }); server_.on("/", HTTP_GET, [this]() { handleRoot(); });
server_.on("/api/status", HTTP_GET, [this]() { handleStatus(); }); server_.on("/api/status", HTTP_GET, [this]() { handleStatus(); });
server_.on("/api/events", HTTP_GET, [this]() { handleEvents(); }); server_.on("/api/events", HTTP_GET, [this]() { handleEvents(); });
@@ -126,6 +130,8 @@ void BoomWeb::begin() {
server_.on("/api/wifi/forget", HTTP_POST, [this]() { handleWifiForget(); }); server_.on("/api/wifi/forget", HTTP_POST, [this]() { handleWifiForget(); });
server_.on("/api/sensitivity", HTTP_POST, [this]() { handleSensitivity(); }); server_.on("/api/sensitivity", HTTP_POST, [this]() { handleSensitivity(); });
server_.on("/api/sync", HTTP_POST, [this]() { handleSync(); }); server_.on("/api/sync", HTTP_POST, [this]() { handleSync(); });
server_.on("/api/events/discard", HTTP_POST, [this]() { handleDiscard(); });
server_.on("/api/today/reset", HTTP_POST, [this]() { handleTodayReset(); });
server_.on("/api/reboot", HTTP_POST, [this]() { handleReboot(); }); server_.on("/api/reboot", HTTP_POST, [this]() { handleReboot(); });
server_.onNotFound([this]() { server_.onNotFound([this]() {
if (!authorise()) return; if (!authorise()) return;
@@ -232,6 +238,56 @@ void BoomWeb::handleSync() {
sendJson(202, "{\"ok\":true,\"queued\":true}"); sendJson(202, "{\"ok\":true,\"queued\":true}");
} }
void BoomWeb::handleDiscard() {
if (!authorise()) return;
// Require a non-simple request header so another site cannot submit a
// cross-origin form using cached HTTP Basic credentials.
if (server_.header("X-BoomCast-Action") != "discard") {
sendJson(403, "{\"error\":\"Discard action header required\"}");
return;
}
if (!boomQueue.ready()) {
sendJson(503, "{\"error\":\"SD card is unavailable\"}");
return;
}
if (server_.arg("all") == "1") {
int removed = boomQueue.clearAll();
if (removed < 0) {
sendJson(500, "{\"error\":\"Could not remove every queued recording\"}");
return;
}
boomState.setSyncing(false, "Discarded " + String(removed) + " queued recording(s)");
sendJson(200, "{\"ok\":true,\"removed\":" + String(removed) + "}");
return;
}
String file = server_.arg("file");
if (!file.length() || file.indexOf('/') >= 0 || file.indexOf('\\') >= 0 || !file.endsWith(".wav")) {
sendJson(400, "{\"error\":\"Valid queued filename required\"}");
return;
}
if (!boomQueue.exists(file)) {
sendJson(404, "{\"error\":\"Queued recording not found\"}");
return;
}
if (!boomQueue.discard(file)) {
sendJson(500, "{\"error\":\"Could not discard recording\"}");
return;
}
boomState.setSyncing(false, "Discarded " + file);
sendJson(200, "{\"ok\":true,\"removed\":1}");
}
void BoomWeb::handleTodayReset() {
if (!authorise()) return;
if (server_.header("X-BoomCast-Action") != "discard") {
sendJson(403, "{\"error\":\"Reset action header required\"}");
return;
}
boomState.resetTodayEvents();
boomState.setSyncing(false, "Today count reset");
sendJson(200, "{\"ok\":true,\"today\":0}");
}
void BoomWeb::handleReboot() { void BoomWeb::handleReboot() {
if (!authorise()) return; if (!authorise()) return;
sendJson(200, "{\"ok\":true,\"rebooting\":true}"); sendJson(200, "{\"ok\":true,\"rebooting\":true}");
@@ -21,6 +21,8 @@ private:
void handleWifiForget(); void handleWifiForget();
void handleSensitivity(); void handleSensitivity();
void handleSync(); void handleSync();
void handleDiscard();
void handleTodayReset();
void handleReboot(); void handleReboot();
}; };
+2 -2
View File
@@ -6,6 +6,6 @@ The pinned official support commit is `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`
The codec API reports success/failure for a requested read, but not the actual byte count. The firmware clears the raw buffer, discards failed reads, and aborts an active clip; short successful reads cannot be measured through this wrapper. `AUDIO_MIC_SLOT=0` selects one fixed stereo slot. This assignment is **not physically verified**; inspect a V2 recording and slot levels before field deployment. The codec API reports success/failure for a requested read, but not the actual byte count. The firmware clears the raw buffer, discards failed reads, and aborts an active clip; short successful reads cannot be measured through this wrapper. `AUDIO_MIC_SLOT=0` selects one fixed stereo slot. This assignment is **not physically verified**; inspect a V2 recording and slot levels before field deployment.
The firmware retains the Arduino sketch layout because the official support expects that structure and no PlatformIO toolchain is currently installed. Use Arduino IDE 2.x, Espressif ESP32 Arduino core 3.3.0, board `ESP32S3 Dev Module`, 8 MB flash, enabled 8 MB PSRAM, Waveshare's pinned LVGL8 (`lvgl` 8.4.0), and ArduinoJson 7.4.3. Run `./prepare_from_waveshare.sh` to copy the pinned official support. The copied support and build products are ignored by Git. The `codec_board` support has Espressif Modified MIT licensing, `esp_codec_dev` has Apache-2.0, ArduinoJson has MIT, and LVGL has MIT. The Waveshare repository has no top-level license statement; preserve upstream attribution and check redistribution terms before vendoring its files. The firmware retains the Arduino sketch layout because the official support expects that structure and no PlatformIO toolchain is currently installed. Use Arduino IDE 2.x, Espressif ESP32 Arduino core 3.3.12, board `ESP32S3 Dev Module`, 8 MB flash, enabled 8 MB PSRAM, Waveshare's pinned LVGL8 (`lvgl` 8.4.0), and ArduinoJson 7.4.3. Run `./prepare_from_waveshare.sh` to copy the pinned official support. The copied support and build products are ignored by Git. The `codec_board` support has Espressif Modified MIT licensing, `esp_codec_dev` has Apache-2.0, ArduinoJson has MIT, and LVGL has MIT. The Waveshare repository has no top-level license statement; preserve upstream attribution and check redistribution terms before vendoring its files.
Build, flash, and serial monitor from Arduino IDE at 115200 baud. Arduino CLI 1.5.1 compiled this sketch with ESP32 core 3.3.0, `FlashSize=8M`, `PSRAM=opi`, and `PartitionScheme=default_8MB`. The reported program size was 1,350,599 bytes (40% of the selected application partition), with 99,368 bytes (30%) of global dynamic memory. A successful compile does not establish microphone, display, SD, TLS, or power behavior; no board was flashed. Build, flash, and serial monitor from Arduino IDE at 115200 baud. Arduino CLI 1.5.1 compiled this sketch with ESP32 core 3.3.12, `FlashSize=8M`, `PSRAM=opi`, and `PartitionScheme=default_8MB`. The reported program size was 1,513,404 bytes (45% of the selected application partition), with 101,808 bytes (31%) of global dynamic memory. A successful compile does not establish microphone, display, SD, TLS, or power behavior; no board was flashed.