first commit
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
# Local provisioning and build output
|
||||
boomcast_config.local.h
|
||||
.pio/
|
||||
.vscode/
|
||||
*.bin
|
||||
*.elf
|
||||
*.map
|
||||
*.log
|
||||
src/
|
||||
audio_bsp.c
|
||||
audio_bsp.h
|
||||
@@ -0,0 +1,103 @@
|
||||
#include <Arduino.h>
|
||||
#include "driver/gpio.h"
|
||||
|
||||
#include "boomcast_audio.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "boomcast_display.h"
|
||||
#include "boomcast_network.h"
|
||||
#include "boomcast_queue.h"
|
||||
#include "boomcast_state.h"
|
||||
#include "boomcast_uploader.h"
|
||||
#include "boomcast_web.h"
|
||||
#include "user_config.h"
|
||||
|
||||
// This header is supplied by Waveshare's official 08_Audio_Test support tree.
|
||||
#include "src/i2c_bsp/i2c_bsp.h"
|
||||
|
||||
static bool buttonWasDown = false;
|
||||
static uint32_t buttonDownAtMs = 0;
|
||||
static uint32_t lastDayCheckMs = 0;
|
||||
|
||||
static void initBoardPower() {
|
||||
gpio_set_direction(Audio_PWR_PIN, GPIO_MODE_OUTPUT);
|
||||
gpio_set_level(Audio_PWR_PIN, 0); // Waveshare audio power gate is active-low.
|
||||
|
||||
gpio_set_direction(VBAT_PWR_PIN, GPIO_MODE_OUTPUT);
|
||||
gpio_set_level(VBAT_PWR_PIN, 0); // We do not need the VBAT measurement rail here.
|
||||
}
|
||||
|
||||
static void handleBootButton() {
|
||||
const bool down = digitalRead(BOOT_BUTTON_PIN) == LOW;
|
||||
|
||||
if (down && !buttonWasDown) {
|
||||
buttonWasDown = true;
|
||||
buttonDownAtMs = millis();
|
||||
}
|
||||
|
||||
if (!down && buttonWasDown) {
|
||||
const uint32_t heldMs = millis() - buttonDownAtMs;
|
||||
buttonWasDown = false;
|
||||
|
||||
// Ignore switch bounce and very long holds. A normal click changes page.
|
||||
if (heldMs >= 40 && heldMs < 1500) {
|
||||
boomDisplay.nextPage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(250);
|
||||
Serial.printf("\nBoomCast %s starting\n", BOOMCAST_FIRMWARE_VERSION);
|
||||
|
||||
boomState.begin();
|
||||
initBoardPower();
|
||||
i2c_master_Init();
|
||||
|
||||
pinMode(BOOT_BUTTON_PIN, INPUT_PULLUP);
|
||||
|
||||
boomQueue.begin();
|
||||
boomDisplay.begin();
|
||||
|
||||
// Start listening before the possibly-slow Wi-Fi association attempt. The
|
||||
// microphone task runs independently while setup() waits for the network.
|
||||
boomAudio.begin(&boomQueue);
|
||||
|
||||
boomNetwork.begin();
|
||||
boomUploader.begin(&boomQueue);
|
||||
boomWeb.begin();
|
||||
|
||||
boomState.rollDayIfNeeded();
|
||||
Serial.printf("[Ready] management UI: http://%s/\n", boomNetwork.ip().c_str());
|
||||
}
|
||||
|
||||
void loop() {
|
||||
boomWeb.handle();
|
||||
boomNetwork.tick();
|
||||
boomDisplay.update();
|
||||
handleBootButton();
|
||||
|
||||
if (millis() - lastDayCheckMs >= 60000) {
|
||||
lastDayCheckMs = millis();
|
||||
boomState.rollDayIfNeeded();
|
||||
}
|
||||
|
||||
String syncFile;
|
||||
if (boomState.takeSyncRequest(syncFile)) {
|
||||
if (syncFile.length()) {
|
||||
boomUploader.submitOne(syncFile);
|
||||
} else {
|
||||
int sent = boomUploader.submitAll();
|
||||
boomState.setSyncing(false, "Upload pass finished: " + String(sent) + " sent");
|
||||
}
|
||||
}
|
||||
|
||||
boomUploader.tick();
|
||||
|
||||
if (boomState.rebootDue()) {
|
||||
delay(50);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
delay(2);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
# 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.
|
||||
|
||||
**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).
|
||||
|
||||
## 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.
|
||||
- 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 and an ignored local configuration header. No insecure TLS mode is enabled.
|
||||
|
||||
## Build and flash
|
||||
|
||||
1. Install Arduino IDE 2.x and Espressif ESP32 Arduino core **3.3.0**.
|
||||
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).
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## Initial provisioning
|
||||
|
||||
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.
|
||||
|
||||
## Server and queue behavior
|
||||
|
||||
See [API contract](docs/api-contract.md). The firmware sends multipart PCM WAV to `POST /api/pending/`, with sensor ID, stable event ID, captured time or explicit unknown-time state, duration, firmware version, and timing metadata. Files are deleted only after a parseable JSON receipt echoes the exact event ID, a submission UUID, and a valid status. HTTP 200 duplicates are accepted only when `duplicate: true` is present. Outages and ambiguous responses retain the queue item for a later retry. Permanent 4xx responses use a one-hour retry interval so a corrected server configuration can eventually recover.
|
||||
|
||||
Queue filenames are stable across reboot. The queue selects the oldest eligible filename across the whole directory rather than trusting directory iteration order. It refuses new captures when the configured event limit or SD free-space reserve is reached; it does not overwrite unsent recordings. Free heap and PSRAM metrics are logged before and after acknowledged uploads.
|
||||
|
||||
## 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.
|
||||
@@ -0,0 +1,210 @@
|
||||
#include "boomcast_audio.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "boomcast_state.h"
|
||||
#include "audio_bsp.h"
|
||||
#include <math.h>
|
||||
#include "esp_heap_caps.h"
|
||||
#include <sys/time.h>
|
||||
extern "C" {
|
||||
#include "src/esp_codec_dev/include/esp_codec_dev.h"
|
||||
extern esp_codec_dev_handle_t record;
|
||||
}
|
||||
|
||||
BoomAudio boomAudio;
|
||||
|
||||
bool BoomAudio::begin(BoomQueue* queue) {
|
||||
queue_ = queue;
|
||||
sensitivity_ = boomState.sensitivity();
|
||||
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_) {
|
||||
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;
|
||||
}
|
||||
|
||||
startedMs_ = millis();
|
||||
xTaskCreatePinnedToCore(taskThunk, "boom_audio", 8192, this, 5, &task_, 0);
|
||||
Serial.println("[Audio] detector task started");
|
||||
return true;
|
||||
}
|
||||
|
||||
void BoomAudio::setSensitivity(uint8_t value) {
|
||||
sensitivity_ = constrain(value, 1, 100);
|
||||
}
|
||||
|
||||
void BoomAudio::taskThunk(void* arg) {
|
||||
static_cast<BoomAudio*>(arg)->taskLoop();
|
||||
}
|
||||
|
||||
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) {
|
||||
Serial.println("[Audio] block allocation failed");
|
||||
vTaskDelete(nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
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_;
|
||||
droppedSamples_ += AUDIO_FRAMES_PER_BLOCK;
|
||||
// A failed read invalidates timing continuity. Discard an active clip.
|
||||
if (capturing_) {
|
||||
++recordingErrors_;
|
||||
capturing_ = false;
|
||||
captureWrite_ = 0;
|
||||
boomState.setCapturing(false);
|
||||
}
|
||||
ringFilled_ = 0;
|
||||
ringWrite_ = 0;
|
||||
boomState.setAudioDiagnostics(failedReads_, recordingErrors_);
|
||||
if (failedReads_ % 100 == 1) Serial.printf("[Audio] read errors=%lu dropped=%lu recording errors=%lu\n",
|
||||
(unsigned long)failedReads_, (unsigned long)droppedSamples_, (unsigned long)recordingErrors_);
|
||||
delay(10);
|
||||
continue;
|
||||
}
|
||||
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];
|
||||
}
|
||||
processMonoBlock(mono, AUDIO_FRAMES_PER_BLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
void BoomAudio::updateWaveform(const int16_t* mono, size_t frames) {
|
||||
int8_t points[BOOMCAST_WAVEFORM_POINTS] = {0};
|
||||
for (size_t p = 0; p < BOOMCAST_WAVEFORM_POINTS; ++p) {
|
||||
size_t start = (p * frames) / BOOMCAST_WAVEFORM_POINTS;
|
||||
size_t end = ((p + 1) * frames) / BOOMCAST_WAVEFORM_POINTS;
|
||||
if (end <= start) end = min(start + 1, frames);
|
||||
int32_t peak = 0;
|
||||
int sign = 1;
|
||||
for (size_t i = start; i < end; ++i) {
|
||||
int32_t v = mono[i];
|
||||
if (abs(v) > abs(peak)) { peak = v; sign = v < 0 ? -1 : 1; }
|
||||
}
|
||||
int scaled = constrain((abs(peak) * 100) / 32768, 0, 100);
|
||||
points[p] = (int8_t)(scaled * sign);
|
||||
}
|
||||
boomState.setWaveform(points, BOOMCAST_WAVEFORM_POINTS);
|
||||
}
|
||||
|
||||
bool BoomAudio::shouldTrigger(float rms, int32_t peak) const {
|
||||
float t = sensitivity_ / 100.0f;
|
||||
|
||||
// At ~55 this stays close to the Atom Echo prototype's 2.8x RMS / 8x peak
|
||||
// philosophy, while the slider gives useful room in both directions.
|
||||
float rmsMult = 4.2f - (2.4f * t); // 4.18 .. 1.80
|
||||
float peakMult = 10.0f - (5.0f * t); // 9.95 .. 5.00
|
||||
float rmsFloor = 1400.0f - (900.0f * t);// 1391 .. 500
|
||||
float peakFloor = 9000.0f - (5000.0f * t);// 8950 .. 4000
|
||||
|
||||
float rmsThreshold = max(rmsFloor, noiseRms_ * rmsMult);
|
||||
float peakThreshold = max(peakFloor, noisePeak_ * peakMult);
|
||||
return rms >= rmsThreshold || peak >= peakThreshold;
|
||||
}
|
||||
|
||||
void BoomAudio::processMonoBlock(const int16_t* mono, size_t frames) {
|
||||
updateWaveform(mono, frames);
|
||||
|
||||
double squareSum = 0.0;
|
||||
int32_t peak = 0;
|
||||
for (size_t i = 0; i < frames; ++i) {
|
||||
int32_t v = mono[i];
|
||||
int32_t av = abs(v);
|
||||
if (av > peak) peak = av;
|
||||
squareSum += double(v) * double(v);
|
||||
}
|
||||
float rms = sqrt(squareSum / (frames ? frames : 1));
|
||||
|
||||
if (capturing_) {
|
||||
appendCapture(mono, frames);
|
||||
return;
|
||||
}
|
||||
|
||||
bool warm = (millis() - startedMs_) >= AUDIO_WARMUP_MS;
|
||||
bool cooledDown = (millis() - lastTriggerMs_) >= TRIGGER_COOLDOWN_MS;
|
||||
bool trigger = warm && cooledDown && shouldTrigger(rms, peak);
|
||||
|
||||
if (trigger) {
|
||||
beginCapture(mono, frames);
|
||||
} else {
|
||||
// Learn normal ambient level slowly, but avoid teaching the detector that a
|
||||
// transient bang is the new normal.
|
||||
if (rms < noiseRms_ * 2.5f) noiseRms_ += (rms - noiseRms_) * NOISE_EMA_ALPHA;
|
||||
if (peak < noisePeak_ * 2.5f) noisePeak_ += (peak - noisePeak_) * NOISE_EMA_ALPHA;
|
||||
pushRing(mono, frames);
|
||||
}
|
||||
}
|
||||
|
||||
void BoomAudio::pushRing(const int16_t* mono, size_t frames) {
|
||||
for (size_t i = 0; i < frames; ++i) {
|
||||
ring_[ringWrite_] = mono[i];
|
||||
ringWrite_ = (ringWrite_ + 1) % PRE_EVENT_SAMPLES;
|
||||
if (ringFilled_ < PRE_EVENT_SAMPLES) ++ringFilled_;
|
||||
}
|
||||
}
|
||||
|
||||
void BoomAudio::beginCapture(const int16_t* current, size_t frames) {
|
||||
captureWrite_ = 0;
|
||||
captureTarget_ = min(CAPTURE_SAMPLES, ringFilled_ + size_t(AUDIO_SAMPLE_RATE * POST_EVENT_MS / 1000));
|
||||
struct timeval now; gettimeofday(&now, nullptr);
|
||||
triggeredMs_ = now.tv_sec > 1577836800 ? uint64_t(now.tv_sec) * 1000 + now.tv_usec / 1000 : 0;
|
||||
captureStartedMs_ = triggeredMs_ ? triggeredMs_ - (ringFilled_ * 1000 / AUDIO_SAMPLE_RATE) : 0;
|
||||
capturing_ = true;
|
||||
boomState.setCapturing(true);
|
||||
lastTriggerMs_ = millis();
|
||||
|
||||
// Copy the rolling pre-trigger buffer in chronological order.
|
||||
size_t count = ringFilled_;
|
||||
size_t start = (ringWrite_ + PRE_EVENT_SAMPLES - count) % PRE_EVENT_SAMPLES;
|
||||
for (size_t i = 0; i < count && captureWrite_ < captureTarget_; ++i) {
|
||||
capture_[captureWrite_++] = ring_[(start + i) % PRE_EVENT_SAMPLES];
|
||||
}
|
||||
appendCapture(current, frames);
|
||||
}
|
||||
|
||||
void BoomAudio::appendCapture(const int16_t* mono, size_t frames) {
|
||||
size_t room = captureTarget_ - captureWrite_;
|
||||
size_t take = min(room, frames);
|
||||
memcpy(capture_ + captureWrite_, mono, take * sizeof(int16_t));
|
||||
captureWrite_ += take;
|
||||
if (captureWrite_ >= captureTarget_) finishCapture();
|
||||
}
|
||||
|
||||
void BoomAudio::finishCapture() {
|
||||
String filename;
|
||||
bool saved = queue_ && queue_->saveWav(capture_, captureWrite_, "audio_spike", &filename, captureStartedMs_, triggeredMs_);
|
||||
if (saved) {
|
||||
boomState.incrementTodayEvents();
|
||||
Serial.printf("[Audio] captured %s\n", filename.c_str());
|
||||
} else {
|
||||
++recordingErrors_;
|
||||
boomState.setAudioDiagnostics(failedReads_, recordingErrors_);
|
||||
Serial.printf("[Audio] queue error; recording errors=%lu\n", (unsigned long)recordingErrors_);
|
||||
}
|
||||
|
||||
// Re-seed the rolling buffer with the tail of the just-finished capture so
|
||||
// the next trigger still has sensible pre-roll context.
|
||||
ringFilled_ = 0;
|
||||
ringWrite_ = 0;
|
||||
size_t start = captureWrite_ > PRE_EVENT_SAMPLES ? captureWrite_ - PRE_EVENT_SAMPLES : 0;
|
||||
pushRing(capture_ + start, captureWrite_ - start);
|
||||
|
||||
captureWrite_ = 0;
|
||||
capturing_ = false;
|
||||
boomState.setCapturing(false);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "boomcast_queue.h"
|
||||
|
||||
class BoomAudio {
|
||||
public:
|
||||
bool begin(BoomQueue* queue);
|
||||
void setSensitivity(uint8_t value);
|
||||
|
||||
private:
|
||||
BoomQueue* queue_ = nullptr;
|
||||
TaskHandle_t task_ = nullptr;
|
||||
int16_t* ring_ = nullptr;
|
||||
int16_t* capture_ = nullptr;
|
||||
size_t ringWrite_ = 0;
|
||||
size_t ringFilled_ = 0;
|
||||
size_t captureWrite_ = 0;
|
||||
size_t captureTarget_ = 0;
|
||||
uint64_t captureStartedMs_ = 0;
|
||||
uint64_t triggeredMs_ = 0;
|
||||
uint32_t failedReads_ = 0;
|
||||
uint32_t droppedSamples_ = 0;
|
||||
uint32_t recordingErrors_ = 0;
|
||||
bool capturing_ = false;
|
||||
uint32_t lastTriggerMs_ = 0;
|
||||
uint32_t startedMs_ = 0;
|
||||
float noiseRms_ = 500.0f;
|
||||
float noisePeak_ = 3000.0f;
|
||||
volatile uint8_t sensitivity_ = 55;
|
||||
|
||||
static void taskThunk(void* arg);
|
||||
void taskLoop();
|
||||
void processMonoBlock(const int16_t* mono, size_t frames);
|
||||
void pushRing(const int16_t* mono, size_t frames);
|
||||
void beginCapture(const int16_t* current, size_t frames);
|
||||
void appendCapture(const int16_t* mono, size_t frames);
|
||||
void finishCapture();
|
||||
bool shouldTrigger(float rms, int32_t peak) const;
|
||||
void updateWaveform(const int16_t* mono, size_t frames);
|
||||
};
|
||||
|
||||
extern BoomAudio boomAudio;
|
||||
@@ -0,0 +1,93 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// BoomCast firmware configuration
|
||||
// Target: Waveshare ESP32-S3-ePaper-1.54 V2 (non-touch)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
#define BOOMCAST_FIRMWARE_VERSION "0.1.0-concept"
|
||||
|
||||
// Set to 180 when the board is physically mounted upside-down.
|
||||
// Supported by this sketch: 0 or 180.
|
||||
constexpr uint16_t DISPLAY_ROTATION_DEG = 180;
|
||||
|
||||
// Passerby screen
|
||||
constexpr bool SHOW_TODAY_COUNT_ON_PUBLIC_SCREEN = true;
|
||||
constexpr const char* DEVICE_FRIENDLY_NAME = "BoomCast";
|
||||
|
||||
// Local management interface
|
||||
constexpr const char* AP_SSID_PREFIX = "BoomCast-Setup";
|
||||
constexpr const char* MDNS_HOSTNAME = "boomcast"; // http://boomcast.local/
|
||||
|
||||
// Each device generates unique AP and management passwords in NVS at first boot.
|
||||
constexpr const char* MANAGEMENT_USER = "admin";
|
||||
|
||||
// Deployment values live in an ignored local header or in NVS; no secrets here.
|
||||
#if __has_include("boomcast_config.local.h")
|
||||
#include "boomcast_config.local.h"
|
||||
#endif
|
||||
#ifndef BOOMCAST_SERVER_BASE_URL
|
||||
#define BOOMCAST_SERVER_BASE_URL "https://YOUR-BOOMCAST-SERVER"
|
||||
#endif
|
||||
#ifndef BOOMCAST_SENSOR_ID
|
||||
#define BOOMCAST_SENSOR_ID 0
|
||||
#endif
|
||||
#ifndef BOOMCAST_SENSOR_TOKEN
|
||||
#define BOOMCAST_SENSOR_TOKEN ""
|
||||
#endif
|
||||
#ifndef BOOMCAST_CA_CERT
|
||||
#define BOOMCAST_CA_CERT ""
|
||||
#endif
|
||||
constexpr const char* SERVER_BASE_URL = BOOMCAST_SERVER_BASE_URL;
|
||||
constexpr const char* SUBMIT_PATH = "/api/pending/";
|
||||
constexpr uint32_t SENSOR_ID = BOOMCAST_SENSOR_ID;
|
||||
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.
|
||||
constexpr uint32_t AUDIO_SAMPLE_RATE = 16000;
|
||||
constexpr uint8_t AUDIO_CODEC_CHANNELS = 2; // ES8311 example is opened stereo
|
||||
constexpr uint8_t AUDIO_BITS_PER_SAMPLE = 16;
|
||||
// Fixed codec slot. Verify this assignment with a real V2 recording before field use.
|
||||
constexpr uint8_t AUDIO_MIC_SLOT = 0;
|
||||
constexpr uint32_t AUDIO_RAW_BLOCK_BYTES = 1024;
|
||||
constexpr uint32_t AUDIO_FRAMES_PER_BLOCK = AUDIO_RAW_BLOCK_BYTES / 4; // 16-bit stereo
|
||||
|
||||
constexpr uint32_t PRE_EVENT_MS = 2500;
|
||||
constexpr uint32_t POST_EVENT_MS = 2500;
|
||||
constexpr uint32_t CAPTURE_MS = PRE_EVENT_MS + POST_EVENT_MS;
|
||||
constexpr size_t PRE_EVENT_SAMPLES = (AUDIO_SAMPLE_RATE * PRE_EVENT_MS) / 1000;
|
||||
constexpr size_t CAPTURE_SAMPLES = (AUDIO_SAMPLE_RATE * CAPTURE_MS) / 1000;
|
||||
|
||||
// Starting point inherited from the Atom Echo concept. The web slider modifies
|
||||
// software thresholds around these values rather than changing codec gain.
|
||||
constexpr uint8_t DEFAULT_SENSITIVITY = 55; // 1..100
|
||||
constexpr uint32_t TRIGGER_COOLDOWN_MS = 1500;
|
||||
constexpr uint32_t AUDIO_WARMUP_MS = 3000;
|
||||
constexpr float NOISE_EMA_ALPHA = 0.008f;
|
||||
|
||||
// Display behaviour. Dynamic text uses the panel's partial-refresh waveform.
|
||||
// A periodic full refresh reduces accumulated ghosting.
|
||||
constexpr uint16_t FULL_REFRESH_AFTER_PARTIALS = 40;
|
||||
constexpr bool FULL_REFRESH_ON_PAGE_SWITCH = false;
|
||||
constexpr uint32_t DISPLAY_STATUS_UPDATE_MS = 1500;
|
||||
|
||||
// Queue / SD
|
||||
constexpr const char* SD_MOUNT_POINT = "/sdcard";
|
||||
constexpr const char* QUEUE_DIR = "/sdcard/queue";
|
||||
constexpr size_t MAX_QUEUE_ITEMS_SHOWN = 40;
|
||||
constexpr size_t MAX_QUEUE_EVENTS = 1000;
|
||||
constexpr uint64_t MIN_SD_FREE_BYTES = 4ULL * 1024 * 1024;
|
||||
|
||||
// Network timing
|
||||
constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 12000;
|
||||
constexpr uint32_t WIFI_RETRY_INTERVAL_MS = 30000;
|
||||
|
||||
// Dutch / EU local time, including DST.
|
||||
constexpr const char* TZ_INFO = "CET-1CEST,M3.5.0,M10.5.0/3";
|
||||
constexpr const char* NTP_SERVER_1 = "pool.ntp.org";
|
||||
constexpr const char* NTP_SERVER_2 = "time.cloudflare.com";
|
||||
|
||||
static_assert(DISPLAY_ROTATION_DEG == 0 || DISPLAY_ROTATION_DEG == 180,
|
||||
"DISPLAY_ROTATION_DEG must be 0 or 180");
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
// Copy to boomcast_config.local.h, which is excluded from Git. Use a CA that
|
||||
// signs your server; ordinary leaf-certificate renewal then needs no reflash.
|
||||
#define BOOMCAST_SERVER_BASE_URL "https://boomcast.example.com"
|
||||
#define BOOMCAST_SENSOR_ID 1
|
||||
#define BOOMCAST_SENSOR_TOKEN "paste-once-token-here"
|
||||
#define BOOMCAST_CA_CERT R"PEM(-----BEGIN CERTIFICATE-----
|
||||
PASTE_TRUSTED_CA_CERTIFICATE_HERE
|
||||
-----END CERTIFICATE-----)PEM"
|
||||
@@ -0,0 +1,358 @@
|
||||
#include "boomcast_display.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "user_config.h"
|
||||
|
||||
#include "esp_heap_caps.h"
|
||||
#include "esp_timer.h"
|
||||
#include "driver/gpio.h"
|
||||
|
||||
BoomDisplay boomDisplay;
|
||||
BoomDisplay* BoomDisplay::instance_ = nullptr;
|
||||
|
||||
static lv_point_t fireworkRays[8][2] = {
|
||||
{{30, 28}, {30, 2}}, {{30, 32}, {30, 58}},
|
||||
{{28, 30}, {2, 30}}, {{32, 30}, {58, 30}},
|
||||
{{28, 28}, {8, 8}}, {{32, 32}, {52, 52}},
|
||||
{{32, 28}, {52, 8}}, {{28, 32}, {8, 52}}
|
||||
};
|
||||
|
||||
static void stylePlainScreen(lv_obj_t* screen) {
|
||||
lv_obj_set_style_bg_color(screen, lv_color_white(), 0);
|
||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
||||
lv_obj_set_style_text_color(screen, lv_color_black(), 0);
|
||||
lv_obj_clear_flag(screen, LV_OBJ_FLAG_SCROLLABLE);
|
||||
}
|
||||
|
||||
bool BoomDisplay::begin() {
|
||||
instance_ = this;
|
||||
lvglMutex_ = xSemaphoreCreateMutex();
|
||||
if (!lvglMutex_) return false;
|
||||
|
||||
// Power gates on this Waveshare board are active-low for EPD and audio.
|
||||
gpio_set_direction(EPD_PWR_PIN, GPIO_MODE_OUTPUT);
|
||||
gpio_set_level(EPD_PWR_PIN, 0);
|
||||
|
||||
custom_lcd_spi_t cfg = {};
|
||||
cfg.cs = EPD_CS_PIN;
|
||||
cfg.dc = EPD_DC_PIN;
|
||||
cfg.rst = EPD_RST_PIN;
|
||||
cfg.busy = EPD_BUSY_PIN;
|
||||
cfg.mosi = EPD_MOSI_PIN;
|
||||
cfg.scl = EPD_SCK_PIN;
|
||||
cfg.spi_host = EPD_SPI_NUM;
|
||||
cfg.buffer_len = 5000; // 200*200/8
|
||||
|
||||
epd_ = new epaper_driver_display(EPD_WIDTH, EPD_HEIGHT, cfg);
|
||||
if (!epd_) return false;
|
||||
epd_->EPD_Init();
|
||||
epd_->EPD_Clear();
|
||||
epd_->EPD_DisplayPartBaseImage();
|
||||
epd_->EPD_Init_Partial();
|
||||
|
||||
lv_init();
|
||||
static lv_disp_draw_buf_t drawBuf;
|
||||
lv_color_t* buffer = (lv_color_t*)heap_caps_malloc(
|
||||
EPD_WIDTH * EPD_HEIGHT * sizeof(lv_color_t), MALLOC_CAP_SPIRAM);
|
||||
if (!buffer) return false;
|
||||
lv_disp_draw_buf_init(&drawBuf, buffer, nullptr, EPD_WIDTH * EPD_HEIGHT);
|
||||
|
||||
static lv_disp_drv_t dispDrv;
|
||||
lv_disp_drv_init(&dispDrv);
|
||||
dispDrv.hor_res = EPD_WIDTH;
|
||||
dispDrv.ver_res = EPD_HEIGHT;
|
||||
dispDrv.flush_cb = flushCb;
|
||||
dispDrv.draw_buf = &drawBuf;
|
||||
dispDrv.full_refresh = 1;
|
||||
display_ = lv_disp_drv_register(&dispDrv);
|
||||
|
||||
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));
|
||||
|
||||
if (lock()) {
|
||||
createScreens();
|
||||
lv_scr_load(publicScreen_);
|
||||
requestFullRefresh();
|
||||
unlock();
|
||||
}
|
||||
|
||||
xTaskCreatePinnedToCore(lvglTaskThunk, "boom_lvgl", 8192, this, 3, nullptr, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BoomDisplay::lock(uint32_t timeoutMs) {
|
||||
TickType_t ticks = timeoutMs == portMAX_DELAY ? portMAX_DELAY : pdMS_TO_TICKS(timeoutMs);
|
||||
return xSemaphoreTake(lvglMutex_, ticks) == pdTRUE;
|
||||
}
|
||||
|
||||
void BoomDisplay::unlock() {
|
||||
xSemaphoreGive(lvglMutex_);
|
||||
}
|
||||
|
||||
void BoomDisplay::tickCb(void*) {
|
||||
lv_tick_inc(5);
|
||||
}
|
||||
|
||||
void BoomDisplay::lvglTaskThunk(void* arg) {
|
||||
static_cast<BoomDisplay*>(arg)->lvglTask();
|
||||
}
|
||||
|
||||
void BoomDisplay::lvglTask() {
|
||||
while (true) {
|
||||
uint32_t delayMs = 50;
|
||||
if (lock()) {
|
||||
delayMs = lv_timer_handler();
|
||||
unlock();
|
||||
}
|
||||
delayMs = constrain(delayMs, 20U, 250U);
|
||||
vTaskDelay(pdMS_TO_TICKS(delayMs));
|
||||
}
|
||||
}
|
||||
|
||||
void BoomDisplay::flushCb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* colorMap) {
|
||||
if (instance_) instance_->flushPixels(area, colorMap);
|
||||
lv_disp_flush_ready(drv);
|
||||
}
|
||||
|
||||
void BoomDisplay::flushPixels(const lv_area_t* area, lv_color_t* colorMap) {
|
||||
if (!epd_) return;
|
||||
epd_->EPD_Clear();
|
||||
|
||||
uint16_t* buffer = reinterpret_cast<uint16_t*>(colorMap);
|
||||
for (int y = area->y1; y <= area->y2; ++y) {
|
||||
for (int x = area->x1; x <= area->x2; ++x) {
|
||||
int px = x;
|
||||
int py = y;
|
||||
if (DISPLAY_ROTATION_DEG == 180) {
|
||||
px = EPD_WIDTH - 1 - x;
|
||||
py = EPD_HEIGHT - 1 - y;
|
||||
}
|
||||
uint8_t color = (*buffer < 0x7fff) ? DRIVER_COLOR_BLACK : DRIVER_COLOR_WHITE;
|
||||
epd_->EPD_DrawColorPixel(px, py, color);
|
||||
++buffer;
|
||||
}
|
||||
}
|
||||
|
||||
bool full = fullRefreshNext_ || partialCount_ >= FULL_REFRESH_AFTER_PARTIALS;
|
||||
if (full) {
|
||||
epd_->EPD_Init();
|
||||
epd_->EPD_DisplayPartBaseImage();
|
||||
epd_->EPD_Init_Partial();
|
||||
fullRefreshNext_ = false;
|
||||
partialCount_ = 0;
|
||||
} else {
|
||||
epd_->EPD_DisplayPart();
|
||||
++partialCount_;
|
||||
}
|
||||
}
|
||||
|
||||
lv_obj_t* BoomDisplay::makeStatusChip(lv_obj_t* parent, int x, const char* initial, bool wifiGlyph) {
|
||||
lv_obj_t* chip = lv_obj_create(parent);
|
||||
lv_obj_set_size(chip, 82, 24);
|
||||
lv_obj_set_pos(chip, x, 6);
|
||||
lv_obj_set_style_radius(chip, 12, 0);
|
||||
lv_obj_set_style_bg_color(chip, lv_color_black(), 0);
|
||||
lv_obj_set_style_bg_opa(chip, LV_OPA_COVER, 0);
|
||||
lv_obj_set_style_border_width(chip, 0, 0);
|
||||
lv_obj_set_style_pad_all(chip, 0, 0);
|
||||
lv_obj_clear_flag(chip, LV_OBJ_FLAG_SCROLLABLE);
|
||||
|
||||
// Tiny built-in vector glyphs instead of external SVG/font dependencies.
|
||||
// They remain crisp on a 1-bit panel and rotate with the whole framebuffer.
|
||||
if (wifiGlyph) {
|
||||
const int heights[3] = {4, 8, 12};
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
lv_obj_t* bar = lv_obj_create(chip);
|
||||
lv_obj_set_size(bar, 3, heights[i]);
|
||||
lv_obj_set_pos(bar, 7 + i * 5, 16 - heights[i]);
|
||||
lv_obj_set_style_bg_color(bar, lv_color_white(), 0);
|
||||
lv_obj_set_style_bg_opa(bar, LV_OPA_COVER, 0);
|
||||
lv_obj_set_style_border_width(bar, 0, 0);
|
||||
lv_obj_set_style_radius(bar, 1, 0);
|
||||
lv_obj_set_style_pad_all(bar, 0, 0);
|
||||
}
|
||||
} else {
|
||||
lv_obj_t* card = lv_obj_create(chip);
|
||||
lv_obj_set_size(card, 13, 15);
|
||||
lv_obj_set_pos(card, 7, 4);
|
||||
lv_obj_set_style_bg_opa(card, LV_OPA_TRANSP, 0);
|
||||
lv_obj_set_style_border_color(card, lv_color_white(), 0);
|
||||
lv_obj_set_style_border_width(card, 1, 0);
|
||||
lv_obj_set_style_radius(card, 1, 0);
|
||||
lv_obj_set_style_pad_all(card, 0, 0);
|
||||
lv_obj_t* notch = lv_obj_create(card);
|
||||
lv_obj_set_size(notch, 4, 3);
|
||||
lv_obj_set_pos(notch, 6, 1);
|
||||
lv_obj_set_style_bg_color(notch, lv_color_white(), 0);
|
||||
lv_obj_set_style_border_width(notch, 0, 0);
|
||||
lv_obj_set_style_pad_all(notch, 0, 0);
|
||||
}
|
||||
|
||||
lv_obj_t* label = lv_label_create(chip);
|
||||
lv_label_set_text(label, initial);
|
||||
lv_obj_set_style_text_color(label, lv_color_white(), 0);
|
||||
lv_obj_set_width(label, 52);
|
||||
lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_pos(label, 25, 4);
|
||||
return label;
|
||||
}
|
||||
|
||||
void BoomDisplay::createFireworkMark(lv_obj_t* parent) {
|
||||
lv_obj_t* mark = lv_obj_create(parent);
|
||||
lv_obj_set_size(mark, 60, 60);
|
||||
lv_obj_set_pos(mark, 70, 40);
|
||||
lv_obj_set_style_bg_opa(mark, LV_OPA_TRANSP, 0);
|
||||
lv_obj_set_style_border_width(mark, 0, 0);
|
||||
lv_obj_set_style_pad_all(mark, 0, 0);
|
||||
lv_obj_clear_flag(mark, LV_OBJ_FLAG_SCROLLABLE);
|
||||
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
lv_obj_t* line = lv_line_create(mark);
|
||||
lv_line_set_points(line, fireworkRays[i], 2);
|
||||
lv_obj_set_style_line_width(line, (i < 4) ? 2 : 1, 0);
|
||||
lv_obj_set_style_line_color(line, lv_color_black(), 0);
|
||||
}
|
||||
lv_obj_t* centre = lv_obj_create(mark);
|
||||
lv_obj_set_size(centre, 8, 8);
|
||||
lv_obj_set_pos(centre, 26, 26);
|
||||
lv_obj_set_style_radius(centre, LV_RADIUS_CIRCLE, 0);
|
||||
lv_obj_set_style_bg_color(centre, lv_color_black(), 0);
|
||||
lv_obj_set_style_border_width(centre, 0, 0);
|
||||
}
|
||||
|
||||
void BoomDisplay::createScreens() {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screen 1: passerby-facing privacy / purpose screen
|
||||
// ---------------------------------------------------------------------------
|
||||
publicScreen_ = lv_obj_create(nullptr);
|
||||
stylePlainScreen(publicScreen_);
|
||||
publicWifi_ = makeStatusChip(publicScreen_, 8, "--", true);
|
||||
publicSd_ = makeStatusChip(publicScreen_, 110, "--", false);
|
||||
createFireworkMark(publicScreen_);
|
||||
|
||||
lv_obj_t* title = lv_label_create(publicScreen_);
|
||||
lv_label_set_text(title, "Vuurwerkdetector");
|
||||
lv_obj_set_width(title, 190);
|
||||
lv_obj_set_style_text_align(title, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 102);
|
||||
|
||||
lv_obj_t* message = lv_label_create(publicScreen_);
|
||||
lv_label_set_text(message, "Luistert naar knallen,\nniet naar gesprekken.\nGeen continue opname.");
|
||||
lv_obj_set_width(message, 190);
|
||||
lv_obj_set_style_text_align(message, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_align(message, LV_ALIGN_TOP_MID, 0, 122);
|
||||
|
||||
publicCount_ = lv_label_create(publicScreen_);
|
||||
lv_label_set_text(publicCount_, "Vandaag: 0");
|
||||
lv_obj_align(publicCount_, LV_ALIGN_BOTTOM_LEFT, 8, -6);
|
||||
|
||||
publicCapture_ = lv_label_create(publicScreen_);
|
||||
lv_label_set_text(publicCapture_, "BOOT: details");
|
||||
lv_obj_align(publicCapture_, LV_ALIGN_BOTTOM_RIGHT, -8, -6);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Screen 2: owner / technical status
|
||||
// ---------------------------------------------------------------------------
|
||||
detailScreen_ = lv_obj_create(nullptr);
|
||||
stylePlainScreen(detailScreen_);
|
||||
detailWifi_ = makeStatusChip(detailScreen_, 8, "--", true);
|
||||
detailSd_ = makeStatusChip(detailScreen_, 110, "--", false);
|
||||
|
||||
lv_obj_t* statusTitle = lv_label_create(detailScreen_);
|
||||
lv_label_set_text(statusTitle, "BoomCast status");
|
||||
lv_obj_align(statusTitle, LV_ALIGN_TOP_LEFT, 10, 40);
|
||||
|
||||
detailToday_ = lv_label_create(detailScreen_);
|
||||
lv_obj_set_pos(detailToday_, 10, 66);
|
||||
detailQueue_ = lv_label_create(detailScreen_);
|
||||
lv_obj_set_pos(detailQueue_, 10, 88);
|
||||
detailSensitivity_ = lv_label_create(detailScreen_);
|
||||
lv_obj_set_pos(detailSensitivity_, 10, 110);
|
||||
detailMode_ = lv_label_create(detailScreen_);
|
||||
lv_obj_set_pos(detailMode_, 10, 132);
|
||||
detailCapture_ = lv_label_create(detailScreen_);
|
||||
lv_obj_set_pos(detailCapture_, 10, 154);
|
||||
|
||||
detailIp_ = lv_label_create(detailScreen_);
|
||||
lv_obj_set_width(detailIp_, 190);
|
||||
lv_obj_set_style_text_align(detailIp_, LV_TEXT_ALIGN_LEFT, 0);
|
||||
lv_obj_align(detailIp_, LV_ALIGN_BOTTOM_LEFT, 10, -8);
|
||||
}
|
||||
|
||||
void BoomDisplay::requestFullRefresh() {
|
||||
fullRefreshNext_ = true;
|
||||
if (display_) lv_obj_invalidate(lv_scr_act());
|
||||
}
|
||||
|
||||
void BoomDisplay::showPage(uint8_t page) {
|
||||
page_ = page % 2;
|
||||
if (!lock()) return;
|
||||
lv_scr_load(page_ == 0 ? publicScreen_ : detailScreen_);
|
||||
if (FULL_REFRESH_ON_PAGE_SWITCH) requestFullRefresh();
|
||||
unlock();
|
||||
}
|
||||
|
||||
void BoomDisplay::nextPage() {
|
||||
showPage((page_ + 1) % 2);
|
||||
}
|
||||
|
||||
void BoomDisplay::applySnapshot(const BoomStateSnapshot& s) {
|
||||
const char* wifiText = s.wifiConnected ? "OK" : (s.apMode ? "AP" : "--");
|
||||
const char* sdText = s.sdReady ? "OK" : "--";
|
||||
lv_label_set_text(publicWifi_, wifiText);
|
||||
lv_label_set_text(detailWifi_, wifiText);
|
||||
lv_label_set_text(publicSd_, sdText);
|
||||
lv_label_set_text(detailSd_, sdText);
|
||||
|
||||
if (SHOW_TODAY_COUNT_ON_PUBLIC_SCREEN) {
|
||||
lv_label_set_text_fmt(publicCount_, "Vandaag: %d", s.todayEvents);
|
||||
lv_obj_clear_flag(publicCount_, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag(publicCount_, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
|
||||
lv_label_set_text_fmt(detailToday_, "Vandaag gevangen: %d", s.todayEvents);
|
||||
lv_label_set_text_fmt(detailQueue_, "Nog te synchroniseren: %d", s.queueCount);
|
||||
lv_label_set_text_fmt(detailSensitivity_, "Gevoeligheid: %u%% E:%lu", s.sensitivity,
|
||||
(unsigned long)(s.audioReadErrors + s.recordingErrors));
|
||||
lv_label_set_text_fmt(detailMode_, "Netwerk: %s", s.apMode && !s.wifiConnected ? "setup-AP" : "WiFi");
|
||||
const char* state = s.capturing ? "Opname" : s.syncing ? "Uploaden" :
|
||||
s.lastSyncMessage.startsWith("Submitted") ? "Verzonden" :
|
||||
s.lastSyncMessage.startsWith("Upload failed") ? "Fout / herproberen" :
|
||||
!s.wifiConnected && s.queueCount ? "Offline / wachtrij" : "Luisteren";
|
||||
lv_label_set_text(detailCapture_, state);
|
||||
lv_label_set_text_fmt(detailIp_, "Beheer: http://%s", s.ip.length() ? s.ip.c_str() : "-");
|
||||
|
||||
lv_label_set_text(publicCapture_, s.capturing ? "Knal gezien..." : "BOOT: details");
|
||||
}
|
||||
|
||||
void BoomDisplay::update() {
|
||||
if (millis() - lastStatusUpdateMs_ < DISPLAY_STATUS_UPDATE_MS) return;
|
||||
lastStatusUpdateMs_ = millis();
|
||||
|
||||
BoomStateSnapshot current = boomState.snapshot();
|
||||
bool changed = !haveLast_ ||
|
||||
current.wifiConnected != last_.wifiConnected ||
|
||||
current.apMode != last_.apMode ||
|
||||
current.sdReady != last_.sdReady ||
|
||||
current.capturing != last_.capturing ||
|
||||
current.queueCount != last_.queueCount ||
|
||||
current.syncing != last_.syncing ||
|
||||
current.lastSyncMessage != last_.lastSyncMessage ||
|
||||
current.audioReadErrors != last_.audioReadErrors ||
|
||||
current.recordingErrors != last_.recordingErrors ||
|
||||
current.todayEvents != last_.todayEvents ||
|
||||
current.sensitivity != last_.sensitivity ||
|
||||
current.ip != last_.ip;
|
||||
|
||||
if (!changed) return;
|
||||
if (lock()) {
|
||||
applySnapshot(current);
|
||||
unlock();
|
||||
}
|
||||
last_ = current;
|
||||
haveLast_ = true;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "boomcast_state.h"
|
||||
#include "lvgl.h"
|
||||
#include "src/display/epaper_driver_bsp.h"
|
||||
|
||||
class BoomDisplay {
|
||||
public:
|
||||
bool begin();
|
||||
void update();
|
||||
void nextPage();
|
||||
void showPage(uint8_t page);
|
||||
uint8_t page() const { return page_; }
|
||||
void requestFullRefresh();
|
||||
|
||||
private:
|
||||
static BoomDisplay* instance_;
|
||||
epaper_driver_display* epd_ = nullptr;
|
||||
SemaphoreHandle_t lvglMutex_ = nullptr;
|
||||
lv_disp_t* display_ = nullptr;
|
||||
uint8_t page_ = 0;
|
||||
bool fullRefreshNext_ = false;
|
||||
uint16_t partialCount_ = 0;
|
||||
uint32_t lastStatusUpdateMs_ = 0;
|
||||
|
||||
lv_obj_t* publicScreen_ = nullptr;
|
||||
lv_obj_t* detailScreen_ = nullptr;
|
||||
|
||||
lv_obj_t* publicWifi_ = nullptr;
|
||||
lv_obj_t* publicSd_ = nullptr;
|
||||
lv_obj_t* publicCount_ = nullptr;
|
||||
lv_obj_t* publicCapture_ = nullptr;
|
||||
|
||||
lv_obj_t* detailWifi_ = nullptr;
|
||||
lv_obj_t* detailSd_ = nullptr;
|
||||
lv_obj_t* detailToday_ = nullptr;
|
||||
lv_obj_t* detailQueue_ = nullptr;
|
||||
lv_obj_t* detailSensitivity_ = nullptr;
|
||||
lv_obj_t* detailIp_ = nullptr;
|
||||
lv_obj_t* detailMode_ = nullptr;
|
||||
lv_obj_t* detailCapture_ = nullptr;
|
||||
|
||||
BoomStateSnapshot last_;
|
||||
bool haveLast_ = false;
|
||||
|
||||
static void flushCb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* colorMap);
|
||||
static void tickCb(void* arg);
|
||||
static void lvglTaskThunk(void* arg);
|
||||
void lvglTask();
|
||||
bool lock(uint32_t timeoutMs = portMAX_DELAY);
|
||||
void unlock();
|
||||
|
||||
void createScreens();
|
||||
lv_obj_t* makeStatusChip(lv_obj_t* parent, int x, const char* initial, bool wifiGlyph);
|
||||
void createFireworkMark(lv_obj_t* parent);
|
||||
void applySnapshot(const BoomStateSnapshot& s);
|
||||
void flushPixels(const lv_area_t* area, lv_color_t* colorMap);
|
||||
};
|
||||
|
||||
extern BoomDisplay boomDisplay;
|
||||
@@ -0,0 +1,160 @@
|
||||
#include "boomcast_network.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "boomcast_state.h"
|
||||
|
||||
#include <WiFi.h>
|
||||
#include <ESPmDNS.h>
|
||||
#include <time.h>
|
||||
|
||||
BoomNetwork boomNetwork;
|
||||
|
||||
void BoomNetwork::begin() {
|
||||
WiFi.persistent(false);
|
||||
WiFi.setAutoReconnect(true);
|
||||
WiFi.setSleep(false); // detector + web UI prioritise responsiveness for now
|
||||
|
||||
configuredSsid_ = boomState.prefs().getString("ssid", "");
|
||||
configuredPassword_ = boomState.prefs().getString("wpass", "");
|
||||
|
||||
if (configuredSsid_.length() && tryStation(WIFI_CONNECT_TIMEOUT_MS)) {
|
||||
apMode_ = false;
|
||||
configureTimeAndMdns();
|
||||
} else {
|
||||
startFallbackAp();
|
||||
}
|
||||
updateState();
|
||||
}
|
||||
|
||||
bool BoomNetwork::tryStation(uint32_t timeoutMs) {
|
||||
if (!configuredSsid_.length()) return false;
|
||||
|
||||
Serial.printf("[WiFi] connecting to %s\n", configuredSsid_.c_str());
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(configuredSsid_.c_str(), configuredPassword_.c_str());
|
||||
uint32_t start = millis();
|
||||
while (WiFi.status() != WL_CONNECTED && millis() - start < timeoutMs) {
|
||||
delay(100);
|
||||
}
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.printf("[WiFi] connected: %s\n", WiFi.localIP().toString().c_str());
|
||||
return true;
|
||||
}
|
||||
WiFi.disconnect(false, false);
|
||||
return false;
|
||||
}
|
||||
|
||||
void BoomNetwork::startFallbackAp() {
|
||||
apMode_ = true;
|
||||
WiFi.mode(WIFI_AP_STA);
|
||||
|
||||
uint64_t chip = ESP.getEfuseMac();
|
||||
char suffix[7];
|
||||
snprintf(suffix, sizeof(suffix), "%06llX", (unsigned long long)(chip & 0xFFFFFF));
|
||||
String apName = String(AP_SSID_PREFIX) + "-" + suffix;
|
||||
String apPassword = boomState.prefs().getString("ap_pass", "");
|
||||
bool ok = apPassword.length() >= 8 && WiFi.softAP(apName.c_str(), apPassword.c_str());
|
||||
Serial.printf("[WiFi] fallback AP %s (%s), IP %s\n",
|
||||
apName.c_str(), ok ? "ok" : "failed", WiFi.softAPIP().toString().c_str());
|
||||
}
|
||||
|
||||
void BoomNetwork::configureTimeAndMdns() {
|
||||
setenv("TZ", TZ_INFO, 1);
|
||||
tzset();
|
||||
configTime(0, 0, NTP_SERVER_1, NTP_SERVER_2);
|
||||
|
||||
if (MDNS.begin(MDNS_HOSTNAME)) {
|
||||
MDNS.addService("http", "tcp", 80);
|
||||
}
|
||||
}
|
||||
|
||||
void BoomNetwork::tick() {
|
||||
if (!configuredSsid_.length()) {
|
||||
updateState();
|
||||
return;
|
||||
}
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED && millis() - lastRetryMs_ >= WIFI_RETRY_INTERVAL_MS) {
|
||||
lastRetryMs_ = millis();
|
||||
Serial.println("[WiFi] retrying configured network");
|
||||
if (apMode_) {
|
||||
// Keep setup AP alive while trying station mode in parallel.
|
||||
WiFi.begin(configuredSsid_.c_str(), configuredPassword_.c_str());
|
||||
} else {
|
||||
WiFi.reconnect();
|
||||
}
|
||||
}
|
||||
|
||||
static bool hadStation = false;
|
||||
bool hasStation = WiFi.status() == WL_CONNECTED;
|
||||
if (hasStation && !hadStation) {
|
||||
Serial.printf("[WiFi] station available: %s\n", WiFi.localIP().toString().c_str());
|
||||
if (apMode_) {
|
||||
// Do not leave the setup AP exposed once the configured LAN is back.
|
||||
WiFi.softAPdisconnect(true);
|
||||
WiFi.mode(WIFI_STA);
|
||||
apMode_ = false;
|
||||
}
|
||||
configureTimeAndMdns();
|
||||
}
|
||||
hadStation = hasStation;
|
||||
updateState();
|
||||
}
|
||||
|
||||
void BoomNetwork::updateState() {
|
||||
bool sta = WiFi.status() == WL_CONNECTED;
|
||||
String currentSsid = sta ? WiFi.SSID() : (apMode_ ? WiFi.softAPSSID() : "");
|
||||
String currentIp = sta ? WiFi.localIP().toString() : (apMode_ ? WiFi.softAPIP().toString() : "-");
|
||||
boomState.setWifi(sta, apMode_, currentSsid, currentIp);
|
||||
}
|
||||
|
||||
bool BoomNetwork::connected() const {
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
|
||||
String BoomNetwork::ip() const {
|
||||
if (connected()) return WiFi.localIP().toString();
|
||||
if (apMode_) return WiFi.softAPIP().toString();
|
||||
return "-";
|
||||
}
|
||||
|
||||
String BoomNetwork::ssid() const {
|
||||
if (connected()) return WiFi.SSID();
|
||||
if (apMode_) return WiFi.softAPSSID();
|
||||
return "";
|
||||
}
|
||||
|
||||
bool BoomNetwork::saveCredentials(const String& ssid, const String& password) {
|
||||
if (!ssid.length()) return false;
|
||||
configuredSsid_ = ssid;
|
||||
configuredPassword_ = password;
|
||||
boomState.prefs().putString("ssid", ssid);
|
||||
boomState.prefs().putString("wpass", password);
|
||||
return true;
|
||||
}
|
||||
|
||||
void BoomNetwork::clearCredentials() {
|
||||
configuredSsid_ = "";
|
||||
configuredPassword_ = "";
|
||||
boomState.prefs().remove("ssid");
|
||||
boomState.prefs().remove("wpass");
|
||||
}
|
||||
|
||||
static String escapeJson(String s) {
|
||||
s.replace("\\", "\\\\");
|
||||
s.replace("\"", "\\\"");
|
||||
return s;
|
||||
}
|
||||
|
||||
String BoomNetwork::scanJson() {
|
||||
int n = WiFi.scanNetworks(false, true);
|
||||
if (n < 0) return "[]";
|
||||
String json = "[";
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (i) json += ',';
|
||||
json += "{\"ssid\":\"" + escapeJson(WiFi.SSID(i)) + "\",\"rssi\":" + String(WiFi.RSSI(i));
|
||||
json += ",\"secure\":" + String(WiFi.encryptionType(i) == WIFI_AUTH_OPEN ? "false" : "true") + "}";
|
||||
}
|
||||
json += "]";
|
||||
WiFi.scanDelete();
|
||||
return json;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
class BoomNetwork {
|
||||
public:
|
||||
void begin();
|
||||
void tick();
|
||||
bool connected() const;
|
||||
bool apMode() const { return apMode_; }
|
||||
String ip() const;
|
||||
String ssid() const;
|
||||
|
||||
bool saveCredentials(const String& ssid, const String& password);
|
||||
void clearCredentials();
|
||||
String scanJson();
|
||||
|
||||
private:
|
||||
bool apMode_ = false;
|
||||
uint32_t lastRetryMs_ = 0;
|
||||
String configuredSsid_;
|
||||
String configuredPassword_;
|
||||
|
||||
bool tryStation(uint32_t timeoutMs);
|
||||
void startFallbackAp();
|
||||
void updateState();
|
||||
void configureTimeAndMdns();
|
||||
};
|
||||
|
||||
extern BoomNetwork boomNetwork;
|
||||
@@ -0,0 +1,253 @@
|
||||
#include "boomcast_queue.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "boomcast_state.h"
|
||||
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/unistd.h>
|
||||
#include <time.h>
|
||||
#include <sys/time.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "esp_vfs_fat.h"
|
||||
#include "sdmmc_cmd.h"
|
||||
#include "driver/sdmmc_host.h"
|
||||
|
||||
static constexpr gpio_num_t SD_D0_PIN = GPIO_NUM_40;
|
||||
static constexpr gpio_num_t SD_CLK_PIN = GPIO_NUM_39;
|
||||
static constexpr gpio_num_t SD_CMD_PIN = GPIO_NUM_41;
|
||||
BoomQueue boomQueue;
|
||||
|
||||
static uint32_t metaChecksum(const BoomEventMeta& meta) {
|
||||
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(&meta);
|
||||
uint32_t hash = 2166136261u;
|
||||
for (size_t i = 0; i < offsetof(BoomEventMeta, checksum); ++i) hash = (hash ^ bytes[i]) * 16777619u;
|
||||
return hash;
|
||||
}
|
||||
|
||||
static bool writeAll(FILE* f, const void* data, size_t bytes) {
|
||||
return fwrite(data, 1, bytes, f) == bytes;
|
||||
}
|
||||
|
||||
static void put16(uint8_t* p, uint16_t v) { p[0] = v & 255; p[1] = v >> 8; }
|
||||
static void put32(uint8_t* p, uint32_t v) {
|
||||
p[0] = v & 255; p[1] = (v >> 8) & 255; p[2] = (v >> 16) & 255; p[3] = v >> 24;
|
||||
}
|
||||
static uint32_t get32(const uint8_t* p) {
|
||||
return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24);
|
||||
}
|
||||
|
||||
bool BoomQueue::begin() {
|
||||
esp_vfs_fat_sdmmc_mount_config_t config = {};
|
||||
config.format_if_mount_failed = false;
|
||||
config.max_files = 8;
|
||||
config.allocation_unit_size = 16 * 1024;
|
||||
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
|
||||
host.max_freq_khz = SDMMC_FREQ_HIGHSPEED;
|
||||
sdmmc_slot_config_t slot = SDMMC_SLOT_CONFIG_DEFAULT();
|
||||
slot.width = 1; slot.clk = SD_CLK_PIN; slot.cmd = SD_CMD_PIN; slot.d0 = SD_D0_PIN;
|
||||
sdmmc_card_t* card = nullptr;
|
||||
esp_err_t error = esp_vfs_fat_sdmmc_mount(SD_MOUNT_POINT, &host, &slot, &config, &card);
|
||||
ready_ = error == ESP_OK && card != nullptr;
|
||||
if (!ready_) {
|
||||
Serial.printf("[SD] mount failed: %s\n", esp_err_to_name(error));
|
||||
boomState.setSdReady(false);
|
||||
return false;
|
||||
}
|
||||
if (!ensureQueueDir()) { ready_ = false; boomState.setSdReady(false); return false; }
|
||||
recoverInterruptedWrites();
|
||||
refreshCount();
|
||||
boomState.setSdReady(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool BoomQueue::ensureQueueDir() {
|
||||
struct stat st;
|
||||
if (stat(QUEUE_DIR, &st) == 0) return S_ISDIR(st.st_mode);
|
||||
return mkdir(QUEUE_DIR, 0775) == 0;
|
||||
}
|
||||
|
||||
String BoomQueue::makeFilename(const char* triggerType) {
|
||||
struct timeval now; gettimeofday(&now, nullptr);
|
||||
const uint32_t epoch = now.tv_sec > 1577836800 ? now.tv_sec : 0;
|
||||
// Fixed width epoch sorts synchronized events. A random suffix remains stable on SD.
|
||||
char name[80];
|
||||
snprintf(name, sizeof(name), "%010lu_%s_%08lX%08lX.wav", (unsigned long)epoch,
|
||||
triggerType && triggerType[0] == 'm' ? "manual" : "spike",
|
||||
(unsigned long)esp_random(), (unsigned long)esp_random());
|
||||
return String(name);
|
||||
}
|
||||
|
||||
bool BoomQueue::writeWavFile(const char* path, const int16_t* samples, size_t sampleCount) {
|
||||
FILE* f = fopen(path, "wb");
|
||||
if (!f) return false;
|
||||
const uint32_t bytes = sampleCount * 2;
|
||||
uint8_t h[44] = {};
|
||||
memcpy(h, "RIFF", 4); put32(h + 4, 36 + bytes); memcpy(h + 8, "WAVEfmt ", 8);
|
||||
put32(h + 16, 16); put16(h + 20, 1); put16(h + 22, 1);
|
||||
put32(h + 24, AUDIO_SAMPLE_RATE); put32(h + 28, AUDIO_SAMPLE_RATE * 2);
|
||||
put16(h + 32, 2); put16(h + 34, 16); memcpy(h + 36, "data", 4); put32(h + 40, bytes);
|
||||
bool ok = writeAll(f, h, sizeof(h)) && writeAll(f, samples, bytes);
|
||||
if (fflush(f) != 0 || fsync(fileno(f)) != 0) ok = false;
|
||||
if (fclose(f) != 0) ok = false;
|
||||
if (!ok) unlink(path);
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool BoomQueue::validWav(const String& filename, uint32_t samples) const {
|
||||
const String path = absolutePath(filename);
|
||||
struct stat st;
|
||||
if (stat(path.c_str(), &st) != 0 || st.st_size != 44 + size_t(samples) * 2) return false;
|
||||
FILE* f = fopen(path.c_str(), "rb");
|
||||
if (!f) return false;
|
||||
uint8_t h[44] = {};
|
||||
bool ok = fread(h, 1, sizeof(h), f) == sizeof(h);
|
||||
fclose(f);
|
||||
return ok && memcmp(h, "RIFF", 4) == 0 && memcmp(h + 8, "WAVEfmt ", 8) == 0 &&
|
||||
memcmp(h + 36, "data", 4) == 0 && get32(h + 4) == 36 + samples * 2 &&
|
||||
get32(h + 16) == 16 && h[20] == 1 && h[22] == 1 && h[34] == 16 &&
|
||||
get32(h + 24) == AUDIO_SAMPLE_RATE && get32(h + 40) == samples * 2;
|
||||
}
|
||||
|
||||
bool BoomQueue::readMeta(const String& filename, BoomEventMeta& meta) const {
|
||||
if (!filename.endsWith(".wav")) return false;
|
||||
String path = absolutePath(filename); path.remove(path.length() - 4); path += ".meta";
|
||||
FILE* f = fopen(path.c_str(), "rb");
|
||||
if (!f) return false;
|
||||
bool ok = fread(&meta, 1, sizeof(meta), f) == sizeof(meta) && fgetc(f) == EOF;
|
||||
fclose(f);
|
||||
return ok && meta.magic == 0x42434D31 && meta.checksum == metaChecksum(meta) &&
|
||||
meta.sampleCount > 0 && meta.sampleCount <= AUDIO_SAMPLE_RATE * 30 &&
|
||||
validWav(filename, meta.sampleCount);
|
||||
}
|
||||
|
||||
bool BoomQueue::saveWav(const int16_t* samples, size_t sampleCount, const char* triggerType,
|
||||
String* savedFilename, uint64_t captureStartedMs, uint64_t triggeredMs) {
|
||||
if (!ready_ || !samples || sampleCount < AUDIO_SAMPLE_RATE / 10 ||
|
||||
sampleCount > AUDIO_SAMPLE_RATE * 30 || refreshCount() >= MAX_QUEUE_EVENTS) return false;
|
||||
uint64_t totalBytes = 0, freeBytes = 0;
|
||||
if (esp_vfs_fat_info(SD_MOUNT_POINT, &totalBytes, &freeBytes) != ESP_OK ||
|
||||
freeBytes < MIN_SD_FREE_BYTES + sampleCount * 2 + 4096) {
|
||||
Serial.println("[SD] insufficient free space");
|
||||
return false;
|
||||
}
|
||||
const String name = makeFilename(triggerType);
|
||||
const String wav = absolutePath(name);
|
||||
String meta = wav; meta.remove(meta.length() - 4); meta += ".meta";
|
||||
if (access(wav.c_str(), F_OK) == 0 || access(meta.c_str(), F_OK) == 0) return false;
|
||||
const String wavTmp = wav + ".tmp", metaTmp = meta + ".tmp";
|
||||
if (!writeWavFile(wavTmp.c_str(), samples, sampleCount)) return false;
|
||||
BoomEventMeta record = {};
|
||||
record.magic = 0x42434D31;
|
||||
record.sampleCount = sampleCount;
|
||||
record.captureStartedMs = captureStartedMs;
|
||||
record.triggeredMs = triggeredMs;
|
||||
struct timeval now; gettimeofday(&now, nullptr);
|
||||
record.queuedMs = now.tv_sec > 1577836800 ? uint64_t(now.tv_sec) * 1000 + now.tv_usec / 1000 : 0;
|
||||
record.checksum = metaChecksum(record);
|
||||
FILE* f = fopen(metaTmp.c_str(), "wb");
|
||||
bool ok = f && writeAll(f, &record, sizeof(record));
|
||||
if (f) {
|
||||
if (fflush(f) != 0 || fsync(fileno(f)) != 0) ok = false;
|
||||
if (fclose(f) != 0) ok = false;
|
||||
}
|
||||
if (!ok || rename(wavTmp.c_str(), wav.c_str()) != 0 || rename(metaTmp.c_str(), meta.c_str()) != 0) {
|
||||
// Keep valid temporary files for recovery after a failed final rename.
|
||||
Serial.println("[SD] queue commit interrupted");
|
||||
return false;
|
||||
}
|
||||
if (savedFilename) *savedFilename = name;
|
||||
refreshCount();
|
||||
return true;
|
||||
}
|
||||
|
||||
void BoomQueue::recoverInterruptedWrites() {
|
||||
DIR* dir = opendir(QUEUE_DIR);
|
||||
if (!dir) return;
|
||||
dirent* item;
|
||||
while ((item = readdir(dir))) {
|
||||
String name(item->d_name);
|
||||
if (!name.endsWith(".meta.tmp")) continue;
|
||||
String base = name.substring(0, name.length() - 9);
|
||||
String wavName = base + ".wav";
|
||||
String wav = absolutePath(wavName);
|
||||
String wavTmp = wav + ".tmp";
|
||||
if (access(wav.c_str(), F_OK) != 0 && access(wavTmp.c_str(), F_OK) == 0) rename(wavTmp.c_str(), wav.c_str());
|
||||
String tmp = absolutePath(name);
|
||||
String final = absolutePath(base + ".meta");
|
||||
// Validate metadata and WAV before making the item eligible.
|
||||
BoomEventMeta meta = {};
|
||||
FILE* f = fopen(tmp.c_str(), "rb");
|
||||
bool valid = f && fread(&meta, 1, sizeof(meta), f) == sizeof(meta);
|
||||
if (f) fclose(f);
|
||||
if (valid && meta.magic == 0x42434D31 && meta.checksum == metaChecksum(meta) && validWav(wavName, meta.sampleCount)) {
|
||||
rename(tmp.c_str(), final.c_str());
|
||||
}
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
|
||||
String BoomQueue::absolutePath(const String& filename) const {
|
||||
String clean = filename; clean.replace("/", ""); clean.replace("\\", "");
|
||||
return String(QUEUE_DIR) + "/" + clean;
|
||||
}
|
||||
|
||||
bool BoomQueue::exists(const String& filename) const { BoomEventMeta meta; return readMeta(filename, meta); }
|
||||
size_t BoomQueue::fileSize(const String& filename) const {
|
||||
struct stat st; return stat(absolutePath(filename).c_str(), &st) == 0 ? st.st_size : 0;
|
||||
}
|
||||
|
||||
bool BoomQueue::remove(const String& filename) {
|
||||
if (!ready_ || !exists(filename)) return false;
|
||||
String meta = absolutePath(filename); meta.remove(meta.length() - 4); meta += ".meta";
|
||||
if (unlink(meta.c_str()) != 0) return false;
|
||||
bool ok = unlink(absolutePath(filename).c_str()) == 0;
|
||||
refreshCount();
|
||||
return ok;
|
||||
}
|
||||
|
||||
size_t BoomQueue::listNames(String* out, size_t maxItems) {
|
||||
if (!ready_ || !out || !maxItems) return 0;
|
||||
DIR* dir = opendir(QUEUE_DIR); if (!dir) return 0;
|
||||
size_t n = 0;
|
||||
dirent* item;
|
||||
while ((item = readdir(dir))) {
|
||||
String name(item->d_name);
|
||||
if (!name.endsWith(".wav") || !exists(name)) continue;
|
||||
size_t pos = 0;
|
||||
while (pos < n && out[pos] < name) ++pos;
|
||||
if (pos >= maxItems) continue;
|
||||
if (n < maxItems) ++n;
|
||||
for (size_t j = n - 1; j > pos; --j) out[j] = out[j - 1];
|
||||
out[pos] = name;
|
||||
}
|
||||
closedir(dir);
|
||||
return n;
|
||||
}
|
||||
|
||||
int BoomQueue::refreshCount() {
|
||||
if (!ready_) { count_ = 0; boomState.setQueueCount(0); return 0; }
|
||||
DIR* dir = opendir(QUEUE_DIR); int n = 0;
|
||||
if (dir) {
|
||||
dirent* item;
|
||||
while ((item = readdir(dir))) {
|
||||
String name(item->d_name);
|
||||
if (name.endsWith(".wav") && exists(name)) ++n;
|
||||
}
|
||||
closedir(dir);
|
||||
}
|
||||
count_ = n; boomState.setQueueCount(n); return n;
|
||||
}
|
||||
|
||||
static String jsonEscape(String value) { value.replace("\\", "\\\\"); value.replace("\"", "\\\""); return value; }
|
||||
String BoomQueue::listJson(size_t limit) {
|
||||
limit = min(limit, MAX_QUEUE_ITEMS_SHOWN);
|
||||
String* names = new String[limit]; if (!names) return "[]";
|
||||
size_t n = listNames(names, limit); String json = "[";
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
if (i) json += ',';
|
||||
json += "{\"name\":\"" + jsonEscape(names[i]) + "\",\"bytes\":";
|
||||
json += String((unsigned long)fileSize(names[i])); json += "}";
|
||||
}
|
||||
json += "]"; delete[] names; return json;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
// Stored beside each WAV. A valid .meta file is the queue commit marker.
|
||||
struct BoomEventMeta {
|
||||
uint32_t magic = 0x42434D31; // BCM1
|
||||
uint32_t sampleCount = 0;
|
||||
uint64_t captureStartedMs = 0;
|
||||
uint64_t triggeredMs = 0;
|
||||
uint64_t queuedMs = 0;
|
||||
uint32_t checksum = 0;
|
||||
};
|
||||
|
||||
class BoomQueue {
|
||||
public:
|
||||
bool begin();
|
||||
bool ready() const { return ready_; }
|
||||
int refreshCount();
|
||||
int count() const { return count_; }
|
||||
bool saveWav(const int16_t* samples, size_t sampleCount, const char* triggerType,
|
||||
String* savedFilename = nullptr, uint64_t captureStartedMs = 0,
|
||||
uint64_t triggeredMs = 0);
|
||||
bool readMeta(const String& filename, BoomEventMeta& meta) const;
|
||||
bool remove(const String& filename);
|
||||
bool exists(const String& filename) const;
|
||||
size_t fileSize(const String& filename) const;
|
||||
String absolutePath(const String& filename) const;
|
||||
String listJson(size_t limit = 40);
|
||||
size_t listNames(String* out, size_t maxItems);
|
||||
|
||||
private:
|
||||
bool ready_ = false;
|
||||
int count_ = 0;
|
||||
bool ensureQueueDir();
|
||||
String makeFilename(const char* triggerType);
|
||||
bool writeWavFile(const char* path, const int16_t* samples, size_t sampleCount);
|
||||
bool validWav(const String& filename, uint32_t samples) const;
|
||||
void recoverInterruptedWrites();
|
||||
};
|
||||
|
||||
extern BoomQueue boomQueue;
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "boomcast_state.h"
|
||||
#include "boomcast_config.h"
|
||||
#include <time.h>
|
||||
|
||||
BoomState boomState;
|
||||
|
||||
void BoomState::begin() {
|
||||
mutex_ = xSemaphoreCreateMutex();
|
||||
preferences_.begin("boomcast", false);
|
||||
const char alphabet[] = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
|
||||
auto makeSecret = [&]() {
|
||||
String value;
|
||||
for (int i = 0; i < 16; ++i) value += alphabet[esp_random() % (sizeof(alphabet) - 1)];
|
||||
return value;
|
||||
};
|
||||
if (!preferences_.getString("ap_pass", "").length()) preferences_.putString("ap_pass", makeSecret());
|
||||
if (!preferences_.getString("mgmt_pass", "").length()) preferences_.putString("mgmt_pass", makeSecret());
|
||||
Serial.printf("[Provision] setup AP password: %s\n", preferences_.getString("ap_pass", "").c_str());
|
||||
Serial.printf("[Provision] management user: admin; password: %s\n", preferences_.getString("mgmt_pass", "").c_str());
|
||||
state_.sensitivity = preferences_.getUChar("sens", DEFAULT_SENSITIVITY);
|
||||
state_.sensitivity = constrain(state_.sensitivity, 1, 100);
|
||||
dayKey_ = preferences_.getString("day", "");
|
||||
state_.todayEvents = preferences_.getInt("today", 0);
|
||||
}
|
||||
|
||||
BoomStateSnapshot BoomState::snapshot() {
|
||||
BoomStateSnapshot copy;
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
copy = state_;
|
||||
xSemaphoreGive(mutex_);
|
||||
return copy;
|
||||
}
|
||||
|
||||
void BoomState::setWifi(bool connected, bool apMode, const String& ssid, const String& ip) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.wifiConnected = connected;
|
||||
state_.apMode = apMode;
|
||||
state_.ssid = ssid;
|
||||
state_.ip = ip;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
void BoomState::setSdReady(bool ready) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.sdReady = ready;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
void BoomState::setQueueCount(int count) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.queueCount = count;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
void BoomState::setCapturing(bool value) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.capturing = value;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
void BoomState::setAudioDiagnostics(uint32_t readErrors, uint32_t recordingErrors) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.audioReadErrors = readErrors;
|
||||
state_.recordingErrors = recordingErrors;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
void BoomState::setSyncing(bool value, const String& message) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.syncing = value;
|
||||
if (message.length()) state_.lastSyncMessage = message;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
void BoomState::setWaveform(const int8_t* points, size_t count) {
|
||||
if (!points) return;
|
||||
count = min(count, BOOMCAST_WAVEFORM_POINTS);
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
memcpy(state_.waveform, points, count);
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
uint8_t BoomState::sensitivity() {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
uint8_t v = state_.sensitivity;
|
||||
xSemaphoreGive(mutex_);
|
||||
return v;
|
||||
}
|
||||
|
||||
void BoomState::setSensitivity(uint8_t value, bool persist) {
|
||||
value = constrain(value, 1, 100);
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
state_.sensitivity = value;
|
||||
xSemaphoreGive(mutex_);
|
||||
if (persist) preferences_.putUChar("sens", value);
|
||||
}
|
||||
|
||||
String BoomState::currentDayKey() {
|
||||
struct tm now;
|
||||
if (!getLocalTime(&now, 5)) return "";
|
||||
char buf[11];
|
||||
strftime(buf, sizeof(buf), "%Y-%m-%d", &now);
|
||||
return String(buf);
|
||||
}
|
||||
|
||||
void BoomState::rollDayIfNeeded() {
|
||||
String current = currentDayKey();
|
||||
if (!current.length()) return;
|
||||
|
||||
bool changed = false;
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
if (dayKey_ != current) {
|
||||
dayKey_ = current;
|
||||
state_.todayEvents = 0;
|
||||
changed = true;
|
||||
}
|
||||
xSemaphoreGive(mutex_);
|
||||
|
||||
if (changed) {
|
||||
preferences_.putString("day", current);
|
||||
preferences_.putInt("today", 0);
|
||||
}
|
||||
}
|
||||
|
||||
void BoomState::incrementTodayEvents() {
|
||||
rollDayIfNeeded();
|
||||
int value;
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
value = ++state_.todayEvents;
|
||||
xSemaphoreGive(mutex_);
|
||||
preferences_.putInt("today", value);
|
||||
}
|
||||
|
||||
void BoomState::requestSync(const String& filename) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
syncRequested_ = true;
|
||||
syncFilename_ = filename;
|
||||
xSemaphoreGive(mutex_);
|
||||
}
|
||||
|
||||
bool BoomState::takeSyncRequest(String& filename) {
|
||||
xSemaphoreTake(mutex_, portMAX_DELAY);
|
||||
bool requested = syncRequested_;
|
||||
if (requested) {
|
||||
filename = syncFilename_;
|
||||
syncFilename_ = "";
|
||||
syncRequested_ = false;
|
||||
}
|
||||
xSemaphoreGive(mutex_);
|
||||
return requested;
|
||||
}
|
||||
|
||||
void BoomState::requestReboot(uint32_t delayMs) {
|
||||
rebootAtMs_ = millis() + delayMs;
|
||||
}
|
||||
|
||||
bool BoomState::rebootDue() const {
|
||||
return rebootAtMs_ != 0 && (int32_t)(millis() - rebootAtMs_) >= 0;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <Preferences.h>
|
||||
|
||||
constexpr size_t BOOMCAST_WAVEFORM_POINTS = 64;
|
||||
|
||||
struct BoomStateSnapshot {
|
||||
bool wifiConnected = false;
|
||||
bool apMode = false;
|
||||
bool sdReady = false;
|
||||
bool capturing = false;
|
||||
bool syncing = false;
|
||||
String ip;
|
||||
String ssid;
|
||||
String lastSyncMessage;
|
||||
int queueCount = 0;
|
||||
int todayEvents = 0;
|
||||
uint32_t audioReadErrors = 0;
|
||||
uint32_t recordingErrors = 0;
|
||||
uint8_t sensitivity = 55;
|
||||
int8_t waveform[BOOMCAST_WAVEFORM_POINTS] = {0};
|
||||
};
|
||||
|
||||
class BoomState {
|
||||
public:
|
||||
void begin();
|
||||
BoomStateSnapshot snapshot();
|
||||
|
||||
void setWifi(bool connected, bool apMode, const String& ssid, const String& ip);
|
||||
void setSdReady(bool ready);
|
||||
void setQueueCount(int count);
|
||||
void setCapturing(bool value);
|
||||
void setAudioDiagnostics(uint32_t readErrors, uint32_t recordingErrors);
|
||||
void setSyncing(bool value, const String& message = "");
|
||||
void setWaveform(const int8_t* points, size_t count);
|
||||
|
||||
uint8_t sensitivity();
|
||||
void setSensitivity(uint8_t value, bool persist = true);
|
||||
|
||||
void rollDayIfNeeded();
|
||||
void incrementTodayEvents();
|
||||
|
||||
void requestSync(const String& filename = "");
|
||||
bool takeSyncRequest(String& filename);
|
||||
|
||||
void requestReboot(uint32_t delayMs = 750);
|
||||
bool rebootDue() const;
|
||||
|
||||
Preferences& prefs() { return preferences_; }
|
||||
|
||||
private:
|
||||
SemaphoreHandle_t mutex_ = nullptr;
|
||||
Preferences preferences_;
|
||||
BoomStateSnapshot state_;
|
||||
String dayKey_;
|
||||
bool syncRequested_ = false;
|
||||
String syncFilename_;
|
||||
uint32_t rebootAtMs_ = 0;
|
||||
|
||||
String currentDayKey();
|
||||
};
|
||||
|
||||
extern BoomState boomState;
|
||||
@@ -0,0 +1,195 @@
|
||||
#include "boomcast_uploader.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "boomcast_network.h"
|
||||
#include "boomcast_state.h"
|
||||
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
#include "esp_heap_caps.h"
|
||||
|
||||
BoomUploader boomUploader;
|
||||
|
||||
static String eventIdFromFilename(String name) {
|
||||
if (name.endsWith(".wav")) name.remove(name.length() - 4);
|
||||
return name;
|
||||
}
|
||||
|
||||
static String isoUtc(uint64_t epochMs) {
|
||||
if (!epochMs) return "";
|
||||
time_t seconds = epochMs / 1000;
|
||||
struct tm utc;
|
||||
if (!gmtime_r(&seconds, &utc)) return "";
|
||||
char text[30];
|
||||
snprintf(text, sizeof(text), "%04d-%02d-%02dT%02d:%02d:%02d.%03uZ",
|
||||
utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
|
||||
utc.tm_hour, utc.tm_min, utc.tm_sec, unsigned(epochMs % 1000));
|
||||
return String(text);
|
||||
}
|
||||
|
||||
static bool writeAll(WiFiClientSecure& client, const uint8_t* bytes, size_t size) {
|
||||
size_t done = 0;
|
||||
while (done < size && client.connected()) {
|
||||
size_t n = client.write(bytes + done, size - done);
|
||||
if (!n) return false;
|
||||
done += n;
|
||||
}
|
||||
return done == size;
|
||||
}
|
||||
static bool writeAll(WiFiClientSecure& client, const String& value) {
|
||||
return writeAll(client, reinterpret_cast<const uint8_t*>(value.c_str()), value.length());
|
||||
}
|
||||
static void addPart(String& body, const String& boundary, const char* name, const String& value) {
|
||||
body += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n";
|
||||
}
|
||||
|
||||
bool BoomUploader::submitOne(const String& filename) {
|
||||
if (!queue_ || !queue_->ready() || !boomNetwork.connected() || !queue_->exists(filename)) return false;
|
||||
boomState.setSyncing(true, "Uploading " + filename);
|
||||
bool ok = doPost(filename, queue_->absolutePath(filename));
|
||||
if (ok && !queue_->remove(filename)) {
|
||||
boomState.setSyncing(false, "Receipt received; local cleanup failed");
|
||||
return false;
|
||||
}
|
||||
boomState.setSyncing(false, ok ? "Submitted " + filename : "Upload failed; queued for retry");
|
||||
return ok;
|
||||
}
|
||||
|
||||
int BoomUploader::submitAll() {
|
||||
if (!queue_ || !boomNetwork.connected()) return 0;
|
||||
int sent = 0;
|
||||
while (sent < 500) {
|
||||
String first[1];
|
||||
if (!queue_->listNames(first, 1) || !submitOne(first[0])) break;
|
||||
++sent;
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
void BoomUploader::tick() {
|
||||
if (!queue_ || !queue_->ready() || !boomNetwork.connected() || !queue_->count()) return;
|
||||
if ((int32_t)(millis() - nextAttemptMs_) < 0) return;
|
||||
String first[1];
|
||||
if (!queue_->listNames(first, 1)) return;
|
||||
if (submitOne(first[0])) {
|
||||
failures_ = 0;
|
||||
permanentFailure_ = false;
|
||||
nextAttemptMs_ = millis() + 1000;
|
||||
} else {
|
||||
failures_ = min(uint8_t(failures_ + 1), uint8_t(8));
|
||||
uint32_t base = permanentFailure_ ? 3600000UL : min(900000UL, 5000UL << failures_);
|
||||
nextAttemptMs_ = millis() + base + (esp_random() % 5000);
|
||||
}
|
||||
}
|
||||
|
||||
bool BoomUploader::doPost(const String& filename, const String& path) {
|
||||
permanentFailure_ = false;
|
||||
BoomEventMeta meta;
|
||||
if (!queue_->readMeta(filename, meta)) return false;
|
||||
String token = boomState.prefs().getString("token", SENSOR_TOKEN);
|
||||
if (!token.length() || !SENSOR_ID || !strlen(SERVER_CA_CERT)) {
|
||||
Serial.println("[Upload] sensor ID, token or CA certificate missing");
|
||||
permanentFailure_ = true;
|
||||
return false;
|
||||
}
|
||||
String origin(SERVER_BASE_URL);
|
||||
if (!origin.startsWith("https://")) {
|
||||
Serial.println("[Upload] HTTPS required");
|
||||
permanentFailure_ = true;
|
||||
return false;
|
||||
}
|
||||
String host = origin.substring(8);
|
||||
int slash = host.indexOf('/'); if (slash >= 0) host = host.substring(0, slash);
|
||||
uint16_t port = 443;
|
||||
int colon = host.lastIndexOf(':');
|
||||
if (colon >= 0) { port = host.substring(colon + 1).toInt(); host = host.substring(0, colon); }
|
||||
if (!host.length() || !port) return false;
|
||||
|
||||
FILE* file = fopen(path.c_str(), "rb");
|
||||
if (!file) return false;
|
||||
const size_t fileBytes = queue_->fileSize(filename);
|
||||
const String boundary = "BoomCast" + String(esp_random(), HEX);
|
||||
const String eventId = eventIdFromFilename(filename);
|
||||
String preamble; preamble.reserve(700);
|
||||
addPart(preamble, boundary, "sensor_id", String(SENSOR_ID));
|
||||
addPart(preamble, boundary, "event_id", eventId);
|
||||
if (meta.captureStartedMs) {
|
||||
addPart(preamble, boundary, "captured_at", isoUtc(meta.captureStartedMs));
|
||||
addPart(preamble, boundary, "capture_started_at", isoUtc(meta.captureStartedMs));
|
||||
} else addPart(preamble, boundary, "time_state", "unknown");
|
||||
if (meta.triggeredMs) addPart(preamble, boundary, "triggered_at", isoUtc(meta.triggeredMs));
|
||||
if (meta.queuedMs) addPart(preamble, boundary, "queued_at", isoUtc(meta.queuedMs));
|
||||
addPart(preamble, boundary, "duration_seconds", String(meta.sampleCount / float(AUDIO_SAMPLE_RATE), 4));
|
||||
addPart(preamble, boundary, "firmware_version", BOOMCAST_FIRMWARE_VERSION);
|
||||
addPart(preamble, boundary, "trigger_type", filename.indexOf("_manual_") >= 0 ? "manual" : "audio_spike");
|
||||
preamble += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\nContent-Type: audio/wav\r\n\r\n";
|
||||
const String trailer = "\r\n--" + boundary + "--\r\n";
|
||||
const size_t length = preamble.length() + fileBytes + trailer.length();
|
||||
|
||||
WiFiClientSecure client;
|
||||
client.setCACert(SERVER_CA_CERT);
|
||||
client.setTimeout(60);
|
||||
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; }
|
||||
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";
|
||||
header += "Content-Length: " + String(length) + "\r\nAccept: application/json\r\nConnection: close\r\n\r\n";
|
||||
bool sent = writeAll(client, header) && writeAll(client, preamble);
|
||||
uint8_t chunk[1024];
|
||||
size_t fileSent = 0;
|
||||
while (sent && fileSent < fileBytes) {
|
||||
size_t n = fread(chunk, 1, min(sizeof(chunk), fileBytes - fileSent), file);
|
||||
if (n == 0) { sent = false; break; }
|
||||
sent = writeAll(client, chunk, n);
|
||||
fileSent += n;
|
||||
}
|
||||
if (ferror(file) || fileSent != fileBytes) sent = false;
|
||||
fclose(file);
|
||||
if (sent) sent = writeAll(client, trailer);
|
||||
if (!sent) { client.stop(); return false; }
|
||||
|
||||
String statusLine = client.readStringUntil('\n');
|
||||
int status = 0;
|
||||
if (statusLine.startsWith("HTTP/1.")) {
|
||||
int firstSpace = statusLine.indexOf(' ');
|
||||
if (firstSpace > 0) status = statusLine.substring(firstSpace + 1).toInt();
|
||||
}
|
||||
// Django returns an ordinary Content-Length response; do not accept redirects.
|
||||
int contentLength = -1;
|
||||
while (client.connected()) {
|
||||
String line = client.readStringUntil('\n'); 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 (client.available() && body.length() < size_t(contentLength)) body += char(client.read());
|
||||
delay(1);
|
||||
}
|
||||
client.stop();
|
||||
Serial.printf("[Upload] HTTP %d, response bytes=%u\n", status, unsigned(body.length()));
|
||||
if (body.length() != size_t(contentLength)) return false;
|
||||
if (status != 200 && status != 201) {
|
||||
permanentFailure_ = status >= 400 && status < 500 && status != 408 && status != 429;
|
||||
return false;
|
||||
}
|
||||
JsonDocument receipt;
|
||||
if (deserializeJson(receipt, body)) return false;
|
||||
const char* returnedEvent = receipt["event_id"] | "";
|
||||
const char* submission = receipt["submission_id"] | "";
|
||||
const char* state = receipt["status"] | "";
|
||||
if (eventId != returnedEvent || strlen(submission) != 36 ||
|
||||
(strcmp(state, "pending") && strcmp(state, "reviewed")) ||
|
||||
(status == 200 && !receipt["duplicate"].as<bool>())) return false;
|
||||
Serial.printf("[Upload] accepted event %s; free heap=%u PSRAM=%u largest PSRAM=%u\n",
|
||||
eventId.c_str(), unsigned(ESP.getFreeHeap()), unsigned(ESP.getFreePsram()),
|
||||
unsigned(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)));
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include "boomcast_queue.h"
|
||||
|
||||
class BoomUploader {
|
||||
public:
|
||||
void begin(BoomQueue* queue) { queue_ = queue; }
|
||||
bool submitOne(const String& filename);
|
||||
int submitAll();
|
||||
void tick();
|
||||
|
||||
private:
|
||||
BoomQueue* queue_ = nullptr;
|
||||
bool doPost(const String& filename, const String& path);
|
||||
uint32_t nextAttemptMs_ = 0;
|
||||
uint8_t failures_ = 0;
|
||||
bool permanentFailure_ = false;
|
||||
};
|
||||
|
||||
extern BoomUploader boomUploader;
|
||||
@@ -0,0 +1,239 @@
|
||||
#include "boomcast_web.h"
|
||||
#include "boomcast_audio.h"
|
||||
#include "boomcast_config.h"
|
||||
#include "boomcast_network.h"
|
||||
#include "boomcast_queue.h"
|
||||
#include "boomcast_state.h"
|
||||
|
||||
BoomWeb boomWeb;
|
||||
|
||||
static String webJsonEscape(String value) {
|
||||
value.replace("\\", "\\\\");
|
||||
value.replace("\"", "\\\"");
|
||||
value.replace("\r", "\\r");
|
||||
value.replace("\n", "\\n");
|
||||
return value;
|
||||
}
|
||||
|
||||
static const char MANAGEMENT_HTML[] PROGMEM = R"BOOMHTML(
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<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%}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<div class="brand"><div class="logo">✦</div><div><h1>BoomCast</h1><p>Firework sensor · local management</p></div></div>
|
||||
<div class="pill"><span id="netDot" class="statusdot"></span><span id="networkTop">Loading…</span></div>
|
||||
</header>
|
||||
|
||||
<section class="grid">
|
||||
<div class="metric"><span>Today</span><b id="today">—</b></div>
|
||||
<div class="metric"><span>Queued</span><b id="queued">—</b></div>
|
||||
<div class="metric"><span>Microphone</span><b id="mic">—</b></div>
|
||||
<div class="metric"><span>Storage</span><b id="sd">—</b></div>
|
||||
</section>
|
||||
|
||||
<div class="cards">
|
||||
<section class="card full">
|
||||
<h2>Live microphone shape</h2>
|
||||
<p class="sub">A low-resolution level preview. This graph is generated locally from the current sample block; it is not an audio stream.</p>
|
||||
<canvas id="wave" width="840" height="128" aria-label="Live microphone waveform"></canvas>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Detection sensitivity</h2>
|
||||
<p class="sub">Higher means easier to trigger. This changes BoomCast's software thresholds, not microphone gain.</p>
|
||||
<div class="sliderline"><input id="sensitivity" type="range" min="1" max="100" value="55"><div class="sens"><span id="sensValue">55</span>%</div></div>
|
||||
<div class="message" id="sensMessage"></div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Device</h2>
|
||||
<p class="sub">Open this page again from the address shown on the e-paper status screen.</p>
|
||||
<div class="privacy"><b>Listening for bangs, not conversations.</b><br>BoomCast keeps a rolling RAM buffer and writes a short clip to SD only around a detected event.</div>
|
||||
<p class="mono" id="deviceAddress">IP: —</p>
|
||||
<p class="mono" id="ssidLine">Wi-Fi: —</p>
|
||||
</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.</p></div><button id="sendAll">Send all</button></div>
|
||||
<div class="queue" id="eventList"><div class="empty">Loading queue…</div></div>
|
||||
<div class="message" id="syncMessage"></div>
|
||||
</section>
|
||||
|
||||
<section class="card full">
|
||||
<div class="row" style="justify-content:space-between"><div><h2>Wi-Fi setup</h2><p class="sub">Scan nearby networks, save credentials, and reboot into station mode.</p></div><button class="secondary" id="scanWifi">Scan</button></div>
|
||||
<div class="wifi-form">
|
||||
<div class="field wide"><label for="wifiSelect">Nearby networks</label><select id="wifiSelect"><option value="">Choose a network or type it below</option></select></div>
|
||||
<div class="field"><label for="ssidInput">SSID</label><input id="ssidInput" type="text" autocomplete="off"></div>
|
||||
<div class="field"><label for="passwordInput">Password</label><input id="passwordInput" type="password" autocomplete="new-password"></div>
|
||||
<div class="row wide"><button id="saveWifi">Save & reboot</button><button class="secondary" id="forgetWifi">Forget saved Wi-Fi</button><button class="secondary" id="reboot">Reboot</button></div>
|
||||
</div>
|
||||
<div class="message" id="wifiMessage"></div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
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 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;$('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}}
|
||||
$('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}};
|
||||
$('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};
|
||||
$('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}};
|
||||
refreshStatus();refreshQueue();setInterval(refreshStatus,1000);setInterval(refreshQueue,4000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
)BOOMHTML";
|
||||
|
||||
bool BoomWeb::authorise() {
|
||||
String password = boomState.prefs().getString("mgmt_pass", "");
|
||||
if (password.length() && server_.authenticate(MANAGEMENT_USER, password.c_str())) return true;
|
||||
server_.requestAuthentication(BASIC_AUTH, "BoomCast");
|
||||
return false;
|
||||
}
|
||||
|
||||
void BoomWeb::addNoCache() {
|
||||
server_.sendHeader("Cache-Control", "no-store, max-age=0");
|
||||
server_.sendHeader("Pragma", "no-cache");
|
||||
}
|
||||
|
||||
void BoomWeb::sendJson(int code, const String& json) {
|
||||
addNoCache();
|
||||
server_.send(code, "application/json; charset=utf-8", json);
|
||||
}
|
||||
|
||||
void BoomWeb::begin() {
|
||||
server_.on("/", HTTP_GET, [this]() { handleRoot(); });
|
||||
server_.on("/api/status", HTTP_GET, [this]() { handleStatus(); });
|
||||
server_.on("/api/events", HTTP_GET, [this]() { handleEvents(); });
|
||||
server_.on("/api/wifi/scan", HTTP_GET, [this]() { handleWifiScan(); });
|
||||
server_.on("/api/wifi", HTTP_POST, [this]() { handleWifiSave(); });
|
||||
server_.on("/api/wifi/forget", HTTP_POST, [this]() { handleWifiForget(); });
|
||||
server_.on("/api/sensitivity", HTTP_POST, [this]() { handleSensitivity(); });
|
||||
server_.on("/api/sync", HTTP_POST, [this]() { handleSync(); });
|
||||
server_.on("/api/reboot", HTTP_POST, [this]() { handleReboot(); });
|
||||
server_.onNotFound([this]() {
|
||||
if (!authorise()) return;
|
||||
sendJson(404, "{\"error\":\"Not found\"}");
|
||||
});
|
||||
server_.begin();
|
||||
Serial.println("[Web] management interface listening on port 80");
|
||||
}
|
||||
|
||||
void BoomWeb::handle() {
|
||||
server_.handleClient();
|
||||
}
|
||||
|
||||
void BoomWeb::handleRoot() {
|
||||
if (!authorise()) return;
|
||||
addNoCache();
|
||||
server_.send_P(200, "text/html; charset=utf-8", MANAGEMENT_HTML);
|
||||
}
|
||||
|
||||
void BoomWeb::handleStatus() {
|
||||
if (!authorise()) return;
|
||||
BoomStateSnapshot s = boomState.snapshot();
|
||||
String json;
|
||||
json.reserve(900);
|
||||
json += "{\"version\":\"" + String(BOOMCAST_FIRMWARE_VERSION) + "\"";
|
||||
json += ",\"wifi\":" + String(s.wifiConnected ? "true" : "false");
|
||||
json += ",\"ap\":" + String(s.apMode ? "true" : "false");
|
||||
json += ",\"sd\":" + String(s.sdReady ? "true" : "false");
|
||||
json += ",\"capturing\":" + String(s.capturing ? "true" : "false");
|
||||
json += ",\"syncing\":" + String(s.syncing ? "true" : "false");
|
||||
json += ",\"ip\":\"" + webJsonEscape(s.ip) + "\"";
|
||||
json += ",\"ssid\":\"" + webJsonEscape(s.ssid) + "\"";
|
||||
json += ",\"queue\":" + String(s.queueCount);
|
||||
json += ",\"today\":" + String(s.todayEvents);
|
||||
json += ",\"sensitivity\":" + String(s.sensitivity);
|
||||
json += ",\"syncMessage\":\"" + webJsonEscape(s.lastSyncMessage) + "\"";
|
||||
json += ",\"waveform\":[";
|
||||
for (size_t i = 0; i < BOOMCAST_WAVEFORM_POINTS; ++i) {
|
||||
if (i) json += ',';
|
||||
json += String((int)s.waveform[i]);
|
||||
}
|
||||
json += "]}";
|
||||
sendJson(200, json);
|
||||
}
|
||||
|
||||
void BoomWeb::handleEvents() {
|
||||
if (!authorise()) return;
|
||||
sendJson(200, boomQueue.listJson(MAX_QUEUE_ITEMS_SHOWN));
|
||||
}
|
||||
|
||||
void BoomWeb::handleWifiScan() {
|
||||
if (!authorise()) return;
|
||||
sendJson(200, boomNetwork.scanJson());
|
||||
}
|
||||
|
||||
void BoomWeb::handleWifiSave() {
|
||||
if (!authorise()) return;
|
||||
String ssid = server_.arg("ssid");
|
||||
String password = server_.arg("password");
|
||||
ssid.trim();
|
||||
if (!ssid.length()) {
|
||||
sendJson(400, "{\"error\":\"SSID is required\"}");
|
||||
return;
|
||||
}
|
||||
if (!boomNetwork.saveCredentials(ssid, password)) {
|
||||
sendJson(500, "{\"error\":\"Could not save Wi-Fi credentials\"}");
|
||||
return;
|
||||
}
|
||||
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
|
||||
boomState.requestReboot(1200);
|
||||
}
|
||||
|
||||
void BoomWeb::handleWifiForget() {
|
||||
if (!authorise()) return;
|
||||
boomNetwork.clearCredentials();
|
||||
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
|
||||
boomState.requestReboot(1200);
|
||||
}
|
||||
|
||||
void BoomWeb::handleSensitivity() {
|
||||
if (!authorise()) return;
|
||||
if (!server_.hasArg("value")) {
|
||||
sendJson(400, "{\"error\":\"value is required\"}");
|
||||
return;
|
||||
}
|
||||
int value = constrain(server_.arg("value").toInt(), 1, 100);
|
||||
boomState.setSensitivity((uint8_t)value, true);
|
||||
boomAudio.setSensitivity((uint8_t)value);
|
||||
sendJson(200, "{\"ok\":true,\"value\":" + String(value) + "}");
|
||||
}
|
||||
|
||||
void BoomWeb::handleSync() {
|
||||
if (!authorise()) return;
|
||||
if (!boomNetwork.connected()) {
|
||||
sendJson(409, "{\"error\":\"No station Wi-Fi connection; upload unavailable in setup-AP-only mode\"}");
|
||||
return;
|
||||
}
|
||||
String file = server_.arg("file");
|
||||
if (file.length() && !boomQueue.exists(file)) {
|
||||
sendJson(404, "{\"error\":\"Queued file not found\"}");
|
||||
return;
|
||||
}
|
||||
boomState.requestSync(file);
|
||||
sendJson(202, "{\"ok\":true,\"queued\":true}");
|
||||
}
|
||||
|
||||
void BoomWeb::handleReboot() {
|
||||
if (!authorise()) return;
|
||||
sendJson(200, "{\"ok\":true,\"rebooting\":true}");
|
||||
boomState.requestReboot(900);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <WebServer.h>
|
||||
|
||||
class BoomWeb {
|
||||
public:
|
||||
void begin();
|
||||
void handle();
|
||||
|
||||
private:
|
||||
WebServer server_{80};
|
||||
|
||||
bool authorise();
|
||||
void addNoCache();
|
||||
void sendJson(int code, const String& json);
|
||||
void handleRoot();
|
||||
void handleStatus();
|
||||
void handleEvents();
|
||||
void handleWifiScan();
|
||||
void handleWifiSave();
|
||||
void handleWifiForget();
|
||||
void handleSensitivity();
|
||||
void handleSync();
|
||||
void handleReboot();
|
||||
};
|
||||
|
||||
extern BoomWeb boomWeb;
|
||||
@@ -0,0 +1,5 @@
|
||||
# BoomCast sensor upload contract
|
||||
|
||||
See `../../../django/SENSOR_SUBMISSION_API.md` for the authoritative backend contract. The firmware sends HTTPS `POST /api/pending/` with `Authorization: Bearer <sensor token>` and multipart fields `sensor_id`, stable filename-derived `event_id`, `duration_seconds`, `firmware_version`, `trigger_type`, and `file` (16 kHz, mono, signed 16-bit PCM WAV). It sends UTC ISO 8601 `captured_at` for the start of the actual WAV, plus optional `capture_started_at`, `triggered_at`, and `queued_at`. Without a synchronized clock it sends `time_state=unknown`, and the server stores a null capture time.
|
||||
|
||||
HTTP 201 is the first durable Pending Review submission. HTTP 200 with `duplicate: true` acknowledges an existing submission. Both must return the exact `event_id`, a 36-character `submission_id`, and `status` of `pending` or `reviewed`; the firmware retains the WAV on any missing, malformed, or mismatched receipt. HTTP 401/403/409 and most other 4xx indicate configuration or validation failures and trigger a slow retry; 408/429, 5xx, timeouts, and TLS errors retry with bounded exponential backoff. The sensor token determines identity and owner, and an untrusted device location never becomes a trusted location.
|
||||
@@ -0,0 +1,11 @@
|
||||
# Waveshare non-touch V2 hardware
|
||||
|
||||
Target: ESP32-S3-ePaper-1.54 V2 (owner confirmed). Waveshare says V2 uses ESP32-S3-PICO-1-N8R8 with 8 MB flash and 8 MB PSRAM and that V1/V2 examples are not interchangeable. Source: https://docs.waveshare.com/ESP32-S3-ePaper-1.54
|
||||
|
||||
The pinned official support commit is `aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956`. Its Arduino `08_Audio_Test` board configuration selects ES8311 with I2C SDA/SCL 47/48 and I2S BCLK 15, WS 38, DOUT 45, DIN 16, MCLK 14, PA 46. The official `04_SD_Card` example uses SDMMC CLK 39, D0 40, CMD 41. The sketch's `user_config.h` matches the official Arduino example for ePaper SPI and power gates. Do not copy M5Stack Atom Echo pins.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Physical V2 acceptance checklist — pending
|
||||
|
||||
- [ ] 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.
|
||||
- [ ] 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.
|
||||
- [ ] Verify CA-backed HTTPS certificate and hostname validation, including an invalid certificate rejection.
|
||||
- [ ] Send a real recording to Django; confirm correct sensor ownership, playback, classification, and Pending Review moderation.
|
||||
- [ ] Retry the same event ID and verify only one submission; reject wrong tokens and malformed WAV files.
|
||||
- [ ] 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.
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Fetch only the pinned official Arduino support needed by this sketch.
|
||||
# Optional argument: a local checkout at the same commit.
|
||||
UPSTREAM=https://github.com/waveshareteam/ESP32-S3-ePaper-1.54.git
|
||||
COMMIT=aaf395c1bbd86f7c5b7a2f9f0401241ff5c44956
|
||||
HERE="$(cd "$(dirname "$0")" && pwd)"
|
||||
TEMP=""
|
||||
cleanup() { if [[ -n "$TEMP" ]]; then rm -rf "$TEMP"; fi; }
|
||||
trap cleanup EXIT
|
||||
if [[ $# -gt 1 ]]; then echo "Usage: $0 [pinned Waveshare checkout]" >&2; exit 2; fi
|
||||
if [[ $# -eq 1 ]]; then
|
||||
ROOT="$(cd "$1" && pwd)"
|
||||
else
|
||||
TEMP="$(mktemp -d)"
|
||||
git clone --quiet --filter=blob:none --no-checkout "$UPSTREAM" "$TEMP/repo"
|
||||
git -C "$TEMP/repo" sparse-checkout init --cone
|
||||
git -C "$TEMP/repo" sparse-checkout set 02_Example/Arduino/08_Audio_Test
|
||||
git -C "$TEMP/repo" checkout --quiet "$COMMIT"
|
||||
ROOT="$TEMP/repo"
|
||||
fi
|
||||
ACTUAL="$(git -C "$ROOT" rev-parse HEAD)"
|
||||
if [[ "$ACTUAL" != "$COMMIT" ]]; then
|
||||
echo "Expected Waveshare commit $COMMIT; got $ACTUAL" >&2
|
||||
exit 1
|
||||
fi
|
||||
SOURCE="$ROOT/02_Example/Arduino/08_Audio_Test"
|
||||
for path in src/codec_board src/esp_codec_dev src/display src/i2c_bsp audio_bsp.c audio_bsp.h; do
|
||||
if [[ ! -e "$SOURCE/$path" ]]; then echo "Missing $SOURCE/$path" >&2; exit 1; fi
|
||||
done
|
||||
mkdir -p "$HERE/src"
|
||||
for name in codec_board esp_codec_dev display i2c_bsp; do
|
||||
rm -rf "$HERE/src/$name"
|
||||
cp -R "$SOURCE/src/$name" "$HERE/src/$name"
|
||||
done
|
||||
cp "$SOURCE/audio_bsp.c" "$HERE/audio_bsp.c"
|
||||
cp "$SOURCE/audio_bsp.h" "$HERE/audio_bsp.h"
|
||||
echo "Prepared official Waveshare support at $COMMIT."
|
||||
echo "Install the same commit's 01_Arduino_Libraries/lvgl8/lvgl as Arduino library lvgl."
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include "driver/gpio.h"
|
||||
#include "driver/spi_master.h"
|
||||
#include "driver/i2c_master.h"
|
||||
|
||||
// Compatibility header for the Waveshare Arduino support files copied from
|
||||
// their official 08_Audio_Test example.
|
||||
|
||||
#define EPD_SPI_NUM SPI2_HOST
|
||||
#define ESP32_I2C_DEV_NUM I2C_NUM_0
|
||||
|
||||
#define EPD_WIDTH 200
|
||||
#define EPD_HEIGHT 200
|
||||
#define LVGL_SPIRAM_BUFF_LEN (EPD_WIDTH * EPD_HEIGHT * 2)
|
||||
|
||||
#define EPD_DC_PIN GPIO_NUM_10
|
||||
#define EPD_CS_PIN GPIO_NUM_11
|
||||
#define EPD_SCK_PIN GPIO_NUM_12
|
||||
#define EPD_MOSI_PIN GPIO_NUM_13
|
||||
#define EPD_RST_PIN GPIO_NUM_9
|
||||
#define EPD_BUSY_PIN GPIO_NUM_8
|
||||
|
||||
#define EPD_PWR_PIN GPIO_NUM_6
|
||||
#define Audio_PWR_PIN GPIO_NUM_42
|
||||
#define VBAT_PWR_PIN GPIO_NUM_17
|
||||
|
||||
#define BOOT_BUTTON_PIN GPIO_NUM_0
|
||||
#define PWR_BUTTON_PIN GPIO_NUM_18
|
||||
|
||||
#define ESP32_I2C_SDA_PIN GPIO_NUM_47
|
||||
#define ESP32_I2C_SCL_PIN GPIO_NUM_48
|
||||
|
||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 5
|
||||
#define EXAMPLE_LVGL_TASK_MAX_DELAY_MS 500
|
||||
#define EXAMPLE_LVGL_TASK_MIN_DELAY_MS 20
|
||||
|
||||
#define I2C_RTC_DEV_Address 0x51
|
||||
#define I2C_SHTC3_DEV_Address 0x70
|
||||
Reference in New Issue
Block a user