Files
WaveShare_ESP32_BoomCast_FW/BoomCast_Waveshare_Arduino/boomcast_queue.cpp
T
2026-10-09 19:10:42 +02:00

301 lines
11 KiB
C++

#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 queuedToday(const BoomEventMeta& meta) {
// queuedMs records when the clip was saved and the "today" count increased.
// Older recordings without a valid clock cannot be dated reliably; the
// owner can use the explicit counter reset for those legacy clips.
if (!meta.queuedMs) return false;
time_t recordedAt = meta.queuedMs / 1000;
time_t now = time(nullptr);
struct tm recorded = {}, current = {};
return localtime_r(&recordedAt, &recorded) && localtime_r(&now, &current) &&
recorded.tm_year == current.tm_year && recorded.tm_yday == current.tm_yday;
}
static bool writeAll(FILE* f, const void* data, size_t bytes) {
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;
bool ok = removeFiles(filename);
refreshCount();
return ok;
}
bool BoomQueue::discard(const String& filename) {
BoomEventMeta meta;
if (!ready_ || !readMeta(filename, meta)) return false;
bool today = queuedToday(meta);
bool ok = removeFiles(filename);
refreshCount();
if (ok && today) boomState.discardTodayEvents(1);
return ok;
}
bool BoomQueue::removeFiles(const String& filename) {
String meta = absolutePath(filename); meta.remove(meta.length() - 4); meta += ".meta";
if (unlink(meta.c_str()) != 0) return false;
return unlink(absolutePath(filename).c_str()) == 0;
}
int BoomQueue::clearAll() {
if (!ready_) return -1;
int removed = 0;
int todayRemoved = 0;
String batch[MAX_QUEUE_ITEMS_SHOWN];
size_t found;
while ((found = listNames(batch, MAX_QUEUE_ITEMS_SHOWN)) != 0) {
for (size_t i = 0; i < found; ++i) {
BoomEventMeta meta;
if (!readMeta(batch[i], meta)) { refreshCount(); boomState.discardTodayEvents(todayRemoved); return -1; }
bool today = queuedToday(meta);
if (!removeFiles(batch[i])) { refreshCount(); boomState.discardTodayEvents(todayRemoved); return -1; }
++removed;
if (today) ++todayRemoved;
}
}
refreshCount();
boomState.discardTodayEvents(todayRemoved);
return removed;
}
size_t BoomQueue::listNames(String* out, size_t maxItems) {
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;
}