bolar_2 backup

This commit is contained in:
2026-11-27 16:38:11 +08:00
commit e96d6d19df
305 changed files with 43350 additions and 0 deletions

View File

@@ -0,0 +1,308 @@
#include "diagnostics/audio_tap.h"
#include <algorithm>
#include <cstring>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_netif.h>
#include <freertos/idf_additions.h>
#include <lwip/sockets.h>
namespace borla {
namespace {
constexpr const char* kTag = "AudioTap2";
//constexpr uint32_t kTaskStackBytes = 6 * 1024;
constexpr unsigned kTaskPriority = 3;
constexpr uint32_t kBindRetryMs = 2000;
constexpr uint32_t kSampleRateHz = 48000;//24000;
constexpr uint32_t kUplinkRateHz = 16000;
} // namespace
bool AudioTap::Initialize()
{
if (initialized_) {
return true;
}
input_.data = static_cast<uint8_t*>(heap_caps_malloc(
kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
output_.data = static_cast<uint8_t*>(heap_caps_malloc(
kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
uplink_.data = static_cast<uint8_t*>(heap_caps_malloc(
kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
if (input_.data == nullptr || output_.data == nullptr ||
uplink_.data == nullptr) {
ESP_LOGE(kTag, "ring allocation failed");
heap_caps_free(input_.data);
heap_caps_free(output_.data);
heap_caps_free(uplink_.data);
input_.data = nullptr;
output_.data = nullptr;
uplink_.data = nullptr;
return false;
}
input_.capacity = kRingBytes;
output_.capacity = kRingBytes;
uplink_.capacity = kRingBytes;
//const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
task_ = xTaskCreateStaticPinnedToCore(
&AudioTap::TaskEntry,
"audio_tap2",
//kTaskStackBytes,
sizeof(task_stack_),
this,
kTaskPriority,
// &task_,
// tskNO_AFFINITY,
// MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
// if (created != pdPASS) {
task_stack_,
&task_control_,
0);
if (task_ == nullptr) {
ESP_LOGE(kTag, "task creation failed");
heap_caps_free(input_.data);
heap_caps_free(output_.data);
heap_caps_free(uplink_.data);
input_.data = nullptr;
output_.data = nullptr;
uplink_.data = nullptr;
return false;
}
initialized_ = true;
ESP_LOGI(kTag,
"recording rings armed: 3 x %u KB PSRAM, TCP port %u",
static_cast<unsigned>(kRingBytes / 1024),
static_cast<unsigned>(kPort));
return true;
}
void AudioTap::PushInput(const int16_t* samples, size_t sample_count)
{
Push(input_,
reinterpret_cast<const uint8_t*>(samples),
sample_count * sizeof(int16_t));
}
void AudioTap::PushOutput(const int16_t* samples, size_t sample_count)
{
if (samples == nullptr) {
// Gap marker: the DAC starved between writes. Recording the silence
// keeps spk.wav on the same timeline the microphone heard — without
// it, late frames concatenate seamlessly and playout gaps become
// invisible in the file, which misread as "spk clean, mic stutters".
static const int16_t kZeroChunk[240] = {};
size_t remaining = sample_count;
while (remaining > 0) {
const size_t chunk =
remaining < sizeof(kZeroChunk) / sizeof(kZeroChunk[0])
? remaining
: sizeof(kZeroChunk) / sizeof(kZeroChunk[0]);
Push(output_,
reinterpret_cast<const uint8_t*>(kZeroChunk),
chunk * sizeof(int16_t));
remaining -= chunk;
}
return;
}
Push(output_,
reinterpret_cast<const uint8_t*>(samples),
sample_count * sizeof(int16_t));
}
void AudioTap::PushUplink(const int16_t* samples, size_t sample_count)
{
if (samples != nullptr) {
Push(uplink_,
reinterpret_cast<const uint8_t*>(samples),
sample_count * sizeof(int16_t));
return;
}
// Suppressed or idle frame: silence keeps the uplink channel's timeline
// aligned with mic/spk so "what did the server hear at second N" is a
// direct A/B listen.
static const int16_t kZeroChunk[240] = {};
size_t remaining = sample_count;
while (remaining > 0) {
const size_t chunk =
remaining < sizeof(kZeroChunk) / sizeof(kZeroChunk[0])
? remaining
: sizeof(kZeroChunk) / sizeof(kZeroChunk[0]);
Push(uplink_,
reinterpret_cast<const uint8_t*>(kZeroChunk),
chunk * sizeof(int16_t));
remaining -= chunk;
}
}
void AudioTap::Push(Ring& ring, const uint8_t* bytes, size_t size)
{
if (ring.data == nullptr || bytes == nullptr || size == 0) {
return;
}
const size_t head = ring.head.load(std::memory_order_relaxed);
const size_t tail = ring.tail.load(std::memory_order_acquire);
const size_t space = ring.capacity - (head - tail);
if (size > space) {
// Drop the NEW audio, keep the old: while no host is attached the
// ring must preserve the earliest sound after boot, not the latest.
ring.dropped_bytes.fetch_add(
static_cast<uint32_t>(size), std::memory_order_relaxed);
return;
}
const size_t offset = head % ring.capacity;
const size_t first = std::min(size, ring.capacity - offset);
std::memcpy(ring.data + offset, bytes, first);
std::memcpy(ring.data, bytes + first, size - first);
ring.head.store(head + size, std::memory_order_release);
}
void AudioTap::TaskEntry(void* context)
{
static_cast<AudioTap*>(context)->Run();
}
[[noreturn]] void AudioTap::Run()
{
// lwIP's TCP/IP thread is created by esp_netif_init(), which the WiFi
// transport calls well after this task starts. Touching the socket API
// before that is not an error return but an assert ("Invalid mbox") and
// a boot loop. A netif existing proves esp_netif_init() has completed.
// The rings keep buffering while we wait, so no boot audio is lost.
while (esp_netif_get_nr_of_ifs() == 0) {
vTaskDelay(pdMS_TO_TICKS(kBindRetryMs));
}
int listen_fd = -1;
while (true) {
listen_fd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_fd >= 0) {
const int reuse = 1;
::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR,
&reuse, sizeof(reuse));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_ANY);
address.sin_port = htons(kPort);
if (::bind(listen_fd,
reinterpret_cast<sockaddr*>(&address),
sizeof(address)) == 0 &&
::listen(listen_fd, 1) == 0) {
break;
}
::close(listen_fd);
}
vTaskDelay(pdMS_TO_TICKS(kBindRetryMs));
}
ESP_LOGI(kTag, "listening on port %u",
static_cast<unsigned>(kPort));
while (true) {
const int client_fd = ::accept(listen_fd, nullptr, nullptr);
if (client_fd < 0) {
vTaskDelay(pdMS_TO_TICKS(kBindRetryMs));
continue;
}
ESP_LOGI(kTag, "recorder attached");
ServeClient(client_fd);
::close(client_fd);
ESP_LOGI(kTag,
"recorder detached dropped_in=%lu dropped_out=%lu",
static_cast<unsigned long>(
input_.dropped_bytes.load()),
static_cast<unsigned long>(
output_.dropped_bytes.load()));
}
}
void AudioTap::ServeClient(int client_fd)
{
// Hello v2: magic, version, channel count, pad, mic/spk rate, uplink
// rate. The host validates this before trusting the frame stream.
uint8_t hello[16] = {'B', 'T', 'A', 'P', 2, 3, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0};
hello[8] = static_cast<uint8_t>(kSampleRateHz & 0xFFU);
hello[9] = static_cast<uint8_t>((kSampleRateHz >> 8U) & 0xFFU);
hello[10] = static_cast<uint8_t>((kSampleRateHz >> 16U) & 0xFFU);
hello[11] = static_cast<uint8_t>((kSampleRateHz >> 24U) & 0xFFU);
hello[12] = static_cast<uint8_t>(kUplinkRateHz & 0xFFU);
hello[13] = static_cast<uint8_t>((kUplinkRateHz >> 8U) & 0xFFU);
hello[14] = static_cast<uint8_t>((kUplinkRateHz >> 16U) & 0xFFU);
hello[15] = static_cast<uint8_t>((kUplinkRateHz >> 24U) & 0xFFU);
if (!SendAll(client_fd, hello, sizeof(hello))) {
return;
}
while (true) {
if (!DrainAndSend(client_fd, input_, 0) ||
!DrainAndSend(client_fd, output_, 1) ||
!DrainAndSend(client_fd, uplink_, 2)) {
return;
}
const bool input_empty =
input_.head.load(std::memory_order_acquire) ==
input_.tail.load(std::memory_order_relaxed);
const bool output_empty =
output_.head.load(std::memory_order_acquire) ==
output_.tail.load(std::memory_order_relaxed);
const bool uplink_empty =
uplink_.head.load(std::memory_order_acquire) ==
uplink_.tail.load(std::memory_order_relaxed);
if (input_empty && output_empty && uplink_empty) {
vTaskDelay(pdMS_TO_TICKS(kIdlePollMs));
}
}
}
bool AudioTap::DrainAndSend(
int socket_fd,
Ring& ring,
uint8_t channel)
{
uint8_t record[4 + kSendChunkBytes];
while (true) {
const size_t head = ring.head.load(std::memory_order_acquire);
const size_t tail = ring.tail.load(std::memory_order_relaxed);
const size_t available = head - tail;
if (available == 0) {
return true;
}
const size_t take = std::min(available, kSendChunkBytes);
const size_t offset = tail % ring.capacity;
const size_t first = std::min(take, ring.capacity - offset);
std::memcpy(record + 4, ring.data + offset, first);
std::memcpy(record + 4 + first, ring.data, take - first);
record[0] = channel;
record[1] = 0;
record[2] = static_cast<uint8_t>(take & 0xFFU);
record[3] = static_cast<uint8_t>((take >> 8U) & 0xFFU);
if (!SendAll(socket_fd, record, 4 + take)) {
return false;
}
// Advance only after the bytes are on the wire so a mid-record send
// failure re-sends the same audio to the next recorder instead of
// losing it.
ring.tail.store(tail + take, std::memory_order_release);
}
}
bool AudioTap::SendAll(int socket_fd, const void* data, size_t size)
{
const uint8_t* cursor = static_cast<const uint8_t*>(data);
size_t remaining = size;
while (remaining > 0) {
const ssize_t sent =
::send(socket_fd, cursor, remaining, 0);
if (sent <= 0) {
return false;
}
cursor += static_cast<size_t>(sent);
remaining -= static_cast<size_t>(sent);
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,84 @@
#pragma once
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
namespace borla {
// Debug-only boot-to-shutdown audio recorder.
//
// The device has nowhere to store an hour of PCM (no SD card, and flash is
// both too small and too slow to write from the audio path), so the tap keeps
// two ring buffers in PSRAM — everything the microphone captured and
// everything that reached the DAC, both 24 kHz mono s16 at the hardware
// boundary — and streams them over a plain TCP socket to
// tools/audio_tap_dump.py, which writes the pair of WAV files. ~32 s of
// pre-buffer per channel covers the gap between the boot prompt and the host
// connecting, so a capture started before power-on is gapless from boot; the
// files end when the device powers off and the socket dies.
//
// The push side is called from the capture and playback tasks and must never
// block or lock: each ring is single-producer/single-consumer with monotonic
// indices, and a full ring drops the NEWEST audio (keeping the oldest, which
// is what preserves the boot prompt while no host is attached).
//
// This is an open microphone on an unauthenticated LAN port. It exists behind
// CONFIG_BORLA_AUDIO_TAP for debugging sessions only and must never ship
// enabled.
class AudioTap final {
public:
bool Initialize();
// Capture task: raw ADC output, before any DSP.
void PushInput(const int16_t* samples, size_t sample_count);
// Playback task: volume-scaled PCM, exactly what the DAC received.
void PushOutput(const int16_t* samples, size_t sample_count);
// Capture task: the server's-ear channel — post-AEC, post-gate 16 kHz
// PCM exactly as it goes to the Opus encoder. nullptr pushes silence so
// suppressed/idle frames keep the timeline aligned with the other two
// channels.
void PushUplink(const int16_t* samples, size_t sample_count);
private:
struct Ring {
uint8_t* data = nullptr;
size_t capacity = 0;
// Monotonic byte counters; unsigned wraparound keeps head - tail
// correct. Producer owns head, the tap task owns tail.
std::atomic<size_t> head{0};
std::atomic<size_t> tail{0};
std::atomic<uint32_t> dropped_bytes{0};
};
static constexpr uint16_t kPort = 3401;
// 1.5 MB per channel = ~32 s at 24 kHz mono s16 (48 KB/s).
static constexpr size_t kRingBytes = 1536 * 1024;
// One 60 ms frame per TCP record keeps the on-stack scratch small.
static constexpr size_t kSendChunkBytes = 2880;
static constexpr uint32_t kIdlePollMs = 20;
//2026-9-23 ckkj debug for wifi mem fail
static constexpr size_t kTaskStackBytes = 6 * 1024;
static void TaskEntry(void* context);
[[noreturn]] void Run();
void ServeClient(int client_fd);
void Push(Ring& ring, const uint8_t* bytes, size_t size);
// Sends everything currently in the ring as [channel u8, 0 u8,
// size u16 LE, payload] records. Returns false when the socket died.
bool DrainAndSend(int socket_fd, Ring& ring, uint8_t channel);
bool SendAll(int socket_fd, const void* data, size_t size);
Ring input_;
Ring output_;
Ring uplink_;
//2026-9-23 ckkj debug for wifi mem fail
StackType_t task_stack_[kTaskStackBytes] = {};
StaticTask_t task_control_ {};
//
TaskHandle_t task_ = nullptr;
bool initialized_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,177 @@
#include "diagnostics/device_log_formatter.h"
#include "diagnostics/trace_context.h"
#include <esp_log.h>
#include <esp_log_timestamp.h>
#include <esp_mac.h>
#include <atomic>
#include <cinttypes>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <sys/time.h>
namespace borla {
namespace {
constexpr char kStandardHeaderEnd[] = ") %s: ";
char g_device_mac[18] = "MAC-UNAVAILABLE";
bool g_initialized = false;
bool g_mac_available = false;
bool g_at_line_start = true;
std::atomic<bool> g_clock_synchronized{false};
void FormatTimestamp(char* output, size_t capacity)
{
if (output == nullptr || capacity == 0) {
return;
}
timeval now{};
gettimeofday(&now, nullptr);
if (g_clock_synchronized.load(std::memory_order_acquire) &&
now.tv_sec >= 1700000000LL) {
tm local{};
const time_t seconds = static_cast<time_t>(now.tv_sec);
if (localtime_r(&seconds, &local) != nullptr) {
const size_t calendar_size = std::strftime(
output,
capacity,
"%Y-%m-%d %H:%M:%S",
&local);
if (calendar_size != 0 &&
capacity >= calendar_size + 5) {
const unsigned milliseconds =
static_cast<unsigned>(now.tv_usec / 1000) % 1000;
output[calendar_size] = '.';
output[calendar_size + 1] = static_cast<char>(
'0' + milliseconds / 100);
output[calendar_size + 2] = static_cast<char>(
'0' + (milliseconds / 10) % 10);
output[calendar_size + 3] = static_cast<char>(
'0' + milliseconds % 10);
output[calendar_size + 4] = '\0';
return;
}
}
}
std::snprintf(
output,
capacity,
"TIME-UNSYNCED+%" PRIu32 "ms",
esp_log_timestamp());
}
int SumPrinted(int first, int second)
{
if (first < 0 || second < 0) {
return -1;
}
return first + second;
}
bool FormatEndsLine(const char* format)
{
const size_t size = std::strlen(format);
return size != 0 && format[size - 1] == '\n';
}
} // namespace
bool DeviceLogFormatter::Initialize()
{
if (g_initialized) {
return g_mac_available;
}
uint8_t mac[6]{};
if (esp_read_mac(mac, ESP_MAC_WIFI_STA) == ESP_OK) {
std::snprintf(
g_device_mac,
sizeof(g_device_mac),
// Lower case to match the identity MAC and the previous firmware's
// prefix (main.cc), so one grep finds both the log lines and the
// device_id the server knows this board by.
"%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
g_mac_available = true;
}
TraceContext::Initialize(g_device_mac);
g_initialized = true;
esp_log_set_vprintf(&DeviceLogFormatter::Print);
return g_mac_available;
}
void DeviceLogFormatter::MarkClockSynchronized()
{
g_clock_synchronized.store(true, std::memory_order_release);
}
int DeviceLogFormatter::Print(
const char* format,
va_list arguments)
{
if (format == nullptr) {
return -1;
}
#if CONFIG_LOG_TIMESTAMP_SOURCE_RTOS
const char* const level_marker = std::strstr(format, " (");
const char* const header_end =
std::strstr(format, kStandardHeaderEnd);
if (level_marker != nullptr && level_marker != format &&
header_end != nullptr && level_marker < header_end) {
va_list message_arguments;
va_copy(message_arguments, arguments);
(void)va_arg(message_arguments, uint32_t);
const char* const tag =
va_arg(message_arguments, const char*);
const char level = *(level_marker - 1);
const char* const message_format =
header_end + sizeof(kStandardHeaderEnd) - 1;
char timestamp[40]{};
FormatTimestamp(timestamp, sizeof(timestamp));
flockfile(stdout);
const int prefix_size = std::fprintf(
stdout,
"[%s][%s][%s] %c %s: ",
g_device_mac,
timestamp,
TraceContext::TraceId(),
level,
tag == nullptr ? "unknown" : tag);
const int message_size = std::vfprintf(
stdout, message_format, message_arguments);
g_at_line_start = FormatEndsLine(message_format);
funlockfile(stdout);
va_end(message_arguments);
return SumPrinted(prefix_size, message_size);
}
#endif
// Some binary components emit one logical line through several vprintf
// calls. Prefix only the first fragment; prefixing every callback corrupts
// WiFi logs into several apparent lines.
flockfile(stdout);
int prefix_size = 0;
if (g_at_line_start) {
char timestamp[40]{};
FormatTimestamp(timestamp, sizeof(timestamp));
prefix_size = std::fprintf(
stdout,
"[%s][%s][%s] ",
g_device_mac,
timestamp,
TraceContext::TraceId());
}
const int message_size = std::vfprintf(stdout, format, arguments);
g_at_line_start = FormatEndsLine(format);
funlockfile(stdout);
return SumPrinted(prefix_size, message_size);
}
} // namespace borla

View File

@@ -0,0 +1,20 @@
#pragma once
#include <cstdarg>
namespace borla {
// Installs a process-wide ESP_LOG output formatter. Runtime log lines become:
// [AA:BB:CC:DD:EE:FF][2026-07-21 14:23:09.962] I Tag: message
// Before the server synchronizes the clock, the time field explicitly reports
// TIME-UNSYNCED plus monotonic milliseconds instead of a misleading 1970 date.
class DeviceLogFormatter final {
public:
static bool Initialize();
static void MarkClockSynchronized();
private:
static int Print(const char* format, va_list arguments);
};
} // namespace borla

View File

@@ -0,0 +1,206 @@
#include "diagnostics/runtime_diagnostics_service.h"
#include <cstring>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <freertos/idf_additions.h>
namespace borla {
namespace {
constexpr const char* kTag = "RuntimeDiagnostics2";
constexpr UBaseType_t kLowStackWarningBytes = 512;
constexpr UBaseType_t kIpcLowStackWarningBytes = 384;
bool IsIpcTask(const char* name)
{
return name != nullptr &&
(std::strcmp(name, "ipc0") == 0 ||
std::strcmp(name, "ipc1") == 0);
}
} // namespace
RuntimeDiagnosticsService::~RuntimeDiagnosticsService()
{
running_.store(false);
if (task_ != nullptr) {
vTaskDeleteWithCaps(task_);
task_ = nullptr;
}
heap_caps_free(task_statuses_);
task_statuses_ = nullptr;
}
bool RuntimeDiagnosticsService::Initialize()
{
if (task_ != nullptr && task_statuses_ != nullptr) {
return true;
}
task_statuses_ = static_cast<TaskStatus_t*>(heap_caps_calloc(kMaximumTasks,
sizeof(TaskStatus_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
if (task_statuses_ == nullptr) {
ESP_LOGE(kTag, "task snapshot buffer allocation failed");
return false;
}
running_.store(true);
const BaseType_t result = xTaskCreateWithCaps(
&RuntimeDiagnosticsService::TaskEntry,
"runtime_diag2",
task_stack_budget::kRuntimeDiagnosticsBytes,
this,
2,
&task_,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (result != pdPASS) {
running_.store(false);
task_ = nullptr;
heap_caps_free(task_statuses_);
task_statuses_ = nullptr;
ESP_LOGE(kTag, "diagnostics worker creation failed");
return false;
}
ESP_LOGI(kTag, "worker started stack_bytes=%u memory=PSRAM",
static_cast<unsigned>(
task_stack_budget::kRuntimeDiagnosticsBytes));
return true;
}
void RuntimeDiagnosticsService::TaskEntry(void* context)
{
static_cast<RuntimeDiagnosticsService*>(context)->Run();
}
[[noreturn]] void RuntimeDiagnosticsService::Run()
{
uint32_t snapshot_due_ms = kInitialDelayMs;
while (running_.load()) {
vTaskDelay(pdMS_TO_TICKS(kFrameStatsPeriodMs));
if (!running_.load()) {
break;
}
IAudioEngine* audio = audio_.load();
if (audio != nullptr) {
// Returns false and logs nothing while the microphone is off.
audio->LogAudioFrameStats();
}
elapsed_since_snapshot_ms_ += kFrameStatsPeriodMs;
if (elapsed_since_snapshot_ms_ < snapshot_due_ms) {
continue;
}
elapsed_since_snapshot_ms_ = 0;
LogSnapshot();
++snapshots_logged_;
snapshot_due_ms = snapshots_logged_ == 1
? kSecondSnapshotDelayMs
: kSnapshotPeriodMs;
}
for (;;) {
vTaskSuspend(nullptr);
}
}
void RuntimeDiagnosticsService::SetAudioEngine(IAudioEngine* audio)
{
audio_.store(audio);
}
void RuntimeDiagnosticsService::LogSnapshot()
{
IAudioEngine* audio = audio_.load();
if (audio != nullptr &&
esp_log_level_get(kTag) >= ESP_LOG_DEBUG) {
// Cumulative capture/voice counters. Steady-state they repeat the
// per-window "duplex window closed" line, so they are debug-only; the
// dynamic level check keeps them one menuconfig switch away.
audio->LogAudioMetrics("periodic");
}
const size_t internal_free
= heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
const size_t internal_minimum = heap_caps_get_minimum_free_size(
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
const size_t internal_largest = heap_caps_get_largest_free_block(
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
const size_t psram_free
= heap_caps_get_free_size(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
const size_t psram_minimum
= heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
const size_t psram_largest
= heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
// A heap that is holding steady is not news. INFO is reserved for the two
// states that demand eyes: the internal low-water mark just sank (a new
// worst case happened since the last report), or free space is inside the
// zone where lwIP/TLS allocations start failing — the exact failure that
// once dropped the WebSocket mid-conversation (free=4415/min=531).
constexpr size_t kInternalFreeAlarmBytes = 20 * 1024;
const bool degraded =
internal_minimum < reported_internal_minimum_ ||
internal_free < kInternalFreeAlarmBytes;
if (degraded) {
reported_internal_minimum_ = internal_minimum;
ESP_LOGI(kTag,
"heap internal free=%u min=%u largest=%u; "
"psram free=%u min=%u largest=%u",
static_cast<unsigned>(internal_free),
static_cast<unsigned>(internal_minimum),
static_cast<unsigned>(internal_largest),
static_cast<unsigned>(psram_free),
static_cast<unsigned>(psram_minimum),
static_cast<unsigned>(psram_largest));
} else {
ESP_LOGD(kTag,
"heap internal free=%u min=%u largest=%u; "
"psram free=%u min=%u largest=%u",
static_cast<unsigned>(internal_free),
static_cast<unsigned>(internal_minimum),
static_cast<unsigned>(internal_largest),
static_cast<unsigned>(psram_free),
static_cast<unsigned>(psram_minimum),
static_cast<unsigned>(psram_largest));
}
const UBaseType_t expected = uxTaskGetNumberOfTasks();
if (expected > kMaximumTasks) {
ESP_LOGW(kTag, "task snapshot skipped: tasks=%u capacity=%u",
static_cast<unsigned>(expected),
static_cast<unsigned>(kMaximumTasks));
return;
}
const UBaseType_t count
= uxTaskGetSystemState(task_statuses_, kMaximumTasks, nullptr);
// The stack budgets were tuned from these lines and have been stable
// since; ~30 healthy rows per snapshot were drowning the conversation
// log. Healthy tasks report at DEBUG now — only a LOW watermark, the one
// thing that demands action, stays visible by default.
ESP_LOGD(kTag, "task snapshot count=%u", static_cast<unsigned>(count));
for (UBaseType_t index = 0; index < count; ++index) {
const TaskStatus_t& status = task_statuses_[index];
const UBaseType_t warning_threshold =
IsIpcTask(status.pcTaskName)
? kIpcLowStackWarningBytes
: kLowStackWarningBytes;
const bool low =
status.usStackHighWaterMark < warning_threshold;
if (low) {
ESP_LOGW(kTag,
"task=%s state=%u priority=%u stack_free_bytes=%u LOW",
status.pcTaskName, static_cast<unsigned>(status.eCurrentState),
static_cast<unsigned>(status.uxCurrentPriority),
static_cast<unsigned>(status.usStackHighWaterMark));
} else {
ESP_LOGD(kTag, "task=%s state=%u priority=%u stack_free_bytes=%u",
status.pcTaskName, static_cast<unsigned>(status.eCurrentState),
static_cast<unsigned>(status.uxCurrentPriority),
static_cast<unsigned>(status.usStackHighWaterMark));
}
}
}
} // namespace borla

View File

@@ -0,0 +1,59 @@
#pragma once
#include "core/task_stack_budget.h"
#include "ports/audio_engine.h"
#include <atomic>
#include <cstddef>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
namespace borla {
// Periodically reports heap health and every FreeRTOS task's remaining stack.
// The snapshot buffer and worker stack live in PSRAM so diagnostics do not run
// heavy task enumeration/logging on the shared esp_timer task.
class RuntimeDiagnosticsService final {
public:
RuntimeDiagnosticsService() = default;
~RuntimeDiagnosticsService();
RuntimeDiagnosticsService(const RuntimeDiagnosticsService&) = delete;
RuntimeDiagnosticsService& operator=(const RuntimeDiagnosticsService&)
= delete;
bool Initialize();
// Optional. When set, each snapshot also emits the voice frontend
// counters, which are the only way to see AEC reference misses.
void SetAudioEngine(IAudioEngine* audio);
void LogSnapshot();
private:
static constexpr size_t kMaximumTasks = 64;
static constexpr uint32_t kInitialDelayMs = 5 * 1000;
static constexpr uint32_t kSecondSnapshotDelayMs = 25 * 1000;
static constexpr uint32_t kSnapshotPeriodMs = 5 * 60 * 1000;
// The worker now ticks fast and emits the audio frame statistics on every
// tick, because the capture DSP chain has to be watched while a
// conversation is happening, not once every five minutes. The tick is
// silent whenever the microphone is off, so an idle device stays quiet.
// The heavy heap/task snapshot keeps its original cadence.
static constexpr uint32_t kFrameStatsPeriodMs = 2 * 1000;
static void TaskEntry(void* context);
[[noreturn]] void Run();
std::atomic<IAudioEngine*> audio_{nullptr};
TaskHandle_t task_ = nullptr;
TaskStatus_t* task_statuses_ = nullptr;
size_t snapshots_logged_ = 0;
uint32_t elapsed_since_snapshot_ms_ = 0;
// Low-water mark of the internal heap at the last INFO-level heap report.
// The heap line only earns INFO when this drops (or free space is
// critically low); a steady heap reports at DEBUG.
size_t reported_internal_minimum_ = SIZE_MAX;
std::atomic<bool> running_{false};
};
} // namespace borla

View File

@@ -0,0 +1,142 @@
#include "diagnostics/trace_context.h"
#include <cstdio>
#include <cstring>
#if __has_include(<esp_timer.h>)
#include <esp_timer.h>
#define BORLA_TRACE_HAS_ESP_TIMER 1
#else
#include <chrono>
#define BORLA_TRACE_HAS_ESP_TIMER 0
#endif
namespace borla {
namespace {
constexpr const char kUnset[] = "-";
char g_device_id[TraceContext::kIdCapacity] = "dev";
char g_trace_id[TraceContext::kIdCapacity] = "-";
char g_session_id[TraceContext::kIdCapacity] = "-";
char g_request_id[TraceContext::kIdCapacity] = "-";
uint64_t MonotonicMs()
{
#if BORLA_TRACE_HAS_ESP_TIMER
return static_cast<uint64_t>(esp_timer_get_time() / 1000LL);
#else
using namespace std::chrono;
return static_cast<uint64_t>(
duration_cast<milliseconds>(
steady_clock::now().time_since_epoch())
.count());
#endif
}
} // namespace
size_t TraceContext::FormatId(
const char* prefix,
const char* device_id,
uint64_t monotonic_ms,
char* output,
size_t capacity)
{
if (output == nullptr || capacity == 0) {
return 0;
}
const char* safe_prefix =
prefix != nullptr && prefix[0] != '\0' ? prefix : "dev";
const char* safe_device =
device_id != nullptr && device_id[0] != '\0' ? device_id : "dev";
const int written = std::snprintf(
output,
capacity,
"%s-%s-%llu",
safe_prefix,
safe_device,
static_cast<unsigned long long>(monotonic_ms));
if (written < 0) {
output[0] = '\0';
return 0;
}
// snprintf already truncated and terminated; report what actually fits so
// callers never see a length past the buffer.
return static_cast<size_t>(written) < capacity
? static_cast<size_t>(written)
: capacity - 1;
}
void TraceContext::Assign(
const char* value,
char* output,
size_t capacity)
{
if (output == nullptr || capacity == 0) {
return;
}
if (value == nullptr || value[0] == '\0') {
std::snprintf(output, capacity, "%s", kUnset);
return;
}
std::snprintf(output, capacity, "%s", value);
}
void TraceContext::Initialize(const char* device_id)
{
// MAC colons would collide with the "field=value" log grammar the server
// greps, so they are folded to dashes here once.
char sanitized[kIdCapacity]{};
std::snprintf(
sanitized,
sizeof(sanitized),
"%s",
device_id != nullptr && device_id[0] != '\0' ? device_id : "dev");
for (size_t index = 0; sanitized[index] != '\0'; ++index) {
if (sanitized[index] == ':' || sanitized[index] == ' ') {
sanitized[index] = '-';
}
}
std::memcpy(g_device_id, sanitized, sizeof(g_device_id));
g_device_id[sizeof(g_device_id) - 1] = '\0';
}
void TraceContext::RefreshTrace(const char* prefix)
{
FormatId(
prefix, g_device_id, MonotonicMs(),
g_trace_id, sizeof(g_trace_id));
}
const char* TraceContext::NewRequestId()
{
FormatId(
"req", g_device_id, MonotonicMs(),
g_request_id, sizeof(g_request_id));
return g_request_id;
}
const char* TraceContext::RefreshSession()
{
FormatId(
"s", g_device_id, MonotonicMs(),
g_session_id, sizeof(g_session_id));
return g_session_id;
}
void TraceContext::SetSession(const char* session_id)
{
Assign(session_id, g_session_id, sizeof(g_session_id));
}
void TraceContext::SetTrace(const char* trace_id)
{
Assign(trace_id, g_trace_id, sizeof(g_trace_id));
}
const char* TraceContext::TraceId() { return g_trace_id; }
const char* TraceContext::SessionId() { return g_session_id; }
const char* TraceContext::RequestId() { return g_request_id; }
} // namespace borla

View File

@@ -0,0 +1,66 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
// Correlation ids shared with server and backend (see docs/0019 §10.1).
//
// session connection scope · refreshed on every realtime session
// trace turn scope · refreshed when the device starts an exchange
// request call scope · refreshed per HTTP/OTA call
//
// Every id is a fixed-capacity C string with no allocation, so it is safe to
// read from a log formatter that runs on any task. Values are written only by
// the owning subsystem and read everywhere; readers may observe a value that
// is one refresh stale, which is acceptable for correlation.
class TraceContext final {
public:
static constexpr size_t kIdCapacity = 64;
// Never null; "-" when nothing has been set yet.
static const char* TraceId();
static const char* SessionId();
static const char* RequestId();
// Seeds the device-side portion of every generated id. Called once with
// the device MAC so ids are globally attributable without a UUID library.
static void Initialize(const char* device_id);
// Generates "<prefix>-<device>-<monotonic ms>" and installs it.
static void RefreshTrace(const char* prefix);
// Returns the freshly generated id so the caller can put it in a header.
static const char* NewRequestId();
// Mints a session id for the connection that is about to be opened, and
// returns it for the handshake header.
//
// Required because the session is connection-scoped. Without it the id is
// still "-" on the first connect (which the server would adopt verbatim,
// since "-" is a non-empty string) and is the *previous* connection's id on
// every reconnect, merging two unrelated sessions under one id. The server
// overwrites this with its own id in ServerHello, so this is a proposal,
// not a decision.
static const char* RefreshSession();
// Adopts an id handed down by the server (ServerHello session id).
static void SetSession(const char* session_id);
static void SetTrace(const char* trace_id);
// Pure formatter, exposed for tests: "<prefix>-<device>-<ms>", truncated
// to fit and always NUL-terminated. Returns the written length.
static size_t FormatId(
const char* prefix,
const char* device_id,
uint64_t monotonic_ms,
char* output,
size_t capacity);
private:
static void Assign(
const char* value,
char* output,
size_t capacity);
};
} // namespace borla