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

183
main/CMakeLists.txt Normal file
View File

@@ -0,0 +1,183 @@
set(SRCS
"main.cc"
"activation/activation_replay_service.cc"
"app/application.cc"
"app/composition_root.cc"
"audio/capture_pipeline.cc"
"audio/embedded_prompt_catalog.cc"
"audio/local_prompt_player.cc"
"audio/packed_opus_reader.cc"
"audio/playback_controller.cc"
"audio/playback_pipeline.cc"
"audio/opus_frame_decoder.cc"
"audio/opus_frame_encoder.cc"
"audio/pcm_rate_converter.cc"
"audio/voice_activity_detector.cc"
"audio/voice_dsp.cc"
"audio/voice_frontend.cc"
"audio/wake_word_detector.cc"
"connectivity/connectivity_manager.cc"
"connectivity/connectivity_policy.cc"
"connectivity/dual_network_policy.cc"
"connectivity/dual_network_transport.cc"
"connectivity/ml307_at_parser.cc"
"connectivity/reconnect_backoff.cc"
"connectivity/wifi_credential_store.cc"
"configuration/remote_behavior_config.cc"
"diagnostics/audio_tap.cc"
"diagnostics/runtime_diagnostics_service.cc"
"diagnostics/device_log_formatter.cc"
"diagnostics/trace_context.cc"
"core/app_effect.cc"
"core/app_event.cc"
"core/playback_types.cc"
"core/remote_behavior.cc"
"core/runtime_state.cc"
"core/state_reducer.cc"
"friend/friend_service.cc"
"friend/friend_store.cc"
"friend/friend_types.cc"
"memory/memory_cache.cc"
"memory/memory_types.cc"
"adapters/effect_router.cc"
"adapters/esp_audio_engine.cc"
"platform/borla_s3/borla_s3_platform.cc"
"platform/borla_s3/battery_monitor.cc"
"platform/borla_s3/ble_friend_exchange.cc"
"platform/borla_s3/ble_provisioning_gatt.cc"
"platform/borla_s3/bmi270_sensor.cc"
"platform/borla_s3/button_input.cc"
"platform/borla_s3/capacitive_touch_input.cc"
"platform/borla_s3/es8311_audio_output.cc"
"platform/borla_s3/esp_websocket_transport.cc"
"platform/borla_s3/esp_wifi_transport.cc"
"platform/borla_s3/i2c_bus.cc"
"platform/borla_s3/ml307_transport.cc"
"platform/borla_s3/ws2812_led.cc"
"ota/ota_endpoint.cc"
"ota/ota_response_parser.cc"
"ota/ota_service.cc"
"ota/ota_types.cc"
"protocol/binary_audio_protocol.cc"
"protocol/protocol_message_builder.cc"
"protocol/realtime_config.cc"
"protocol/realtime_protocol.cc"
"protocol/server_message_dispatcher.cc"
"protocol/websocket_uri.cc"
"provisioning/ble_provisioning_codec.cc"
"provisioning/ble_provisioning_service.cc"
"power/idle_service.cc"
"power/power_service.cc"
"schedule/alarm_schedule.cc"
"schedule/alarm_service.cc"
"schedule/alarm_store.cc"
"schedule/alert_ringer.cc"
"schedule/reminder_schedule.cc"
"schedule/reminder_service.cc"
"schedule/schedule_coordinator.cc"
"sensor/battery_estimator.cc"
"sensor/imu_processor.cc"
"sensor/sensor_message_codec.cc"
"sensor/sensor_service.cc"
"sensor/sensor_types.cc"
"sensor/touch_channel.cc"
"platform/borla_s3/tca9555.cc"
)
idf_component_register(
SRCS ${SRCS}
INCLUDE_DIRS "."
REQUIRES
button
bt
driver
app_update
esp-opus
espressif__esp-dsp
esp_adc
esp_app_format
esp_codec_dev
esp_driver_gpio
esp_driver_i2c
esp_driver_i2s
esp_event
esp_http_client
esp_hw_support
esp_netif
esp_system
esp_timer
esp_wifi
esp-sr
freertos
json
led_strip
mbedtls
nvs_flash
tcp_transport
)
# Reuse Espressif's Apache-2.0 BMI270 context image from the explicitly
# versioned esp-dsp component. Only the immutable sensor configuration blob is
# compiled here; firmware2 has its own I2C driver and does not link old code.
idf_component_get_property(
ESP_DSP_COMPONENT_DIR espressif__esp-dsp COMPONENT_DIR)
target_sources(
${COMPONENT_LIB}
PRIVATE
"${ESP_DSP_COMPONENT_DIR}/applications/m5stack_core_s3/apps/kalman_filter/main/bmi270_context.c"
)
if(NOT CMAKE_BUILD_EARLY_EXPANSION)
idf_build_get_property(python PYTHON)
set(PROMPT_GENERATOR
"${CMAKE_CURRENT_LIST_DIR}/../assets/gen_audio_prompts.py")
set(PROMPT_ASSET_DIR
"${CMAKE_CURRENT_LIST_DIR}/../assets/prompts")
file(
GLOB PROMPT_ASSETS
"${PROMPT_ASSET_DIR}/*.ogg"
"${PROMPT_ASSET_DIR}/*.opus"
)
set(GENERATED_PROMPT_DIR
"${CMAKE_CURRENT_BINARY_DIR}/generated")
set(GENERATED_PROMPT_HEADER
"${GENERATED_PROMPT_DIR}/audio_prompts_data.h")
add_custom_command(
OUTPUT "${GENERATED_PROMPT_HEADER}"
COMMAND
"${python}" "${PROMPT_GENERATOR}"
"${PROMPT_ASSET_DIR}" "${GENERATED_PROMPT_HEADER}"
DEPENDS
"${PROMPT_GENERATOR}"
${PROMPT_ASSETS}
COMMENT "Validating and packing local Ogg/Opus prompts"
VERBATIM
)
add_custom_target(
firmware2_prompt_data
DEPENDS "${GENERATED_PROMPT_HEADER}"
)
add_dependencies(${COMPONENT_LIB} firmware2_prompt_data)
target_include_directories(
${COMPONENT_LIB}
PRIVATE "${GENERATED_PROMPT_DIR}"
)
endif()
# ESP-IDF 5.4 defaults chip targets to its newest supported C++ dialect.
# Keep firmware2 on the project-wide C++17 contract explicitly.
target_compile_options(
${COMPONENT_LIB}
PRIVATE
$<$<COMPILE_LANGUAGE:CXX>:-std=gnu++17>
)
# ServerCommand intentionally lives in PSRAM and is currently several KB.
# Keep every production parser frame small so a future field cannot silently
# recreate a task-stack copy of the whole command.
set_source_files_properties(
"protocol/server_message_dispatcher.cc"
PROPERTIES
COMPILE_OPTIONS "-Wframe-larger-than=1024;-Werror"
)

38
main/Kconfig.projbuild Normal file
View File

@@ -0,0 +1,38 @@
menu "Borla firmware2"
config BORLA_OTA_URL
string "OTA version-check URL"
default "https://borla-ota.lkall.com/xiaozhi/ota/"
help
HTTPS endpoint implementing protocols/ota_protocol.md.
config BORLA_OTA_ALLOW_INSECURE_HTTP
bool "Allow insecure HTTP for OTA development"
default n
help
Development-only escape hatch for isolated LAN testing. Production
builds must keep this disabled so manifests and binaries require HTTPS.
config BORLA_ML307_APN
string "ML307 cellular APN"
default ""
help
SIM operator APN. Empty lets the operator/modem select its default.
config BORLA_ML307_DIAL_COMMAND
string "ML307 PPP dial command"
default "ATD*99#"
help
Command used after LTE registration to enter PPP data mode.
config BORLA_AUDIO_TAP
bool "Debug audio tap (stream mic + speaker PCM over TCP)"
default n
help
Streams everything the microphone captured and everything the DAC
played (24 kHz mono s16, boot to shutdown) over an unauthenticated
TCP socket on port 3401, so tools/audio_tap_dump.py on the same LAN
can write the pair of timestamped WAV files. This is an open
microphone: debugging builds only, never ship with it enabled.
endmenu

View File

@@ -0,0 +1,241 @@
#include "activation/activation_replay_service.h"
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "ActivationReplay2";
} // namespace
bool ActivationReplayService::Initialize(IEventPublisher& publisher)
{
if (timer_ != nullptr) {
publisher_ = &publisher;
return true;
}
const esp_timer_create_args_t arguments = {
.callback = &ActivationReplayService::TimerCallback,
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "activation2",
.skip_unhandled_events = true,
};
if (esp_timer_create(&arguments, &timer_) != ESP_OK) {
return false;
}
publisher_ = &publisher;
return true;
}
bool ActivationReplayService::StartLocalSequence(
const LocalPromptSequence& sequence)
{
if (publisher_ == nullptr || sequence.Empty() ||
sequence.count > kMaxLocalPromptSequenceItems) {
return false;
}
uint32_t generation = 0;
PlaybackSessionId previous_session = 0;
bool repeating = false;
{
std::lock_guard<std::mutex> lock(mutex_);
esp_timer_stop(timer_);
previous_session = current_session_;
sequence_ = sequence;
current_session_ = 0;
repeating_ =
sequence.Contains(LocalPrompt::kActivationDevice);
repeating = repeating_;
active_ = true;
if (++generation_ == 0) {
++generation_;
}
generation = generation_;
}
if (previous_session != 0) {
audio_.CancelPlayback(previous_session);
}
if (!publisher_->Publish(AppEvent::Make(
AppEventType::kLocalSequenceRequested,
generation))) {
StopLocalSequence();
return false;
}
ESP_LOGI(kTag, "sequence queued items=%u repeat=%d generation=%lu",
static_cast<unsigned>(sequence.count),
repeating ? 1 : 0,
static_cast<unsigned long>(generation));
return true;
}
void ActivationReplayService::StopLocalSequence()
{
StopWithReason("handler request");
}
void ActivationReplayService::StopWithReason(const char* reason)
{
PlaybackSessionId session = 0;
bool was_active = false;
{
std::lock_guard<std::mutex> lock(mutex_);
was_active = active_;
StopLocked(&session);
}
if (session != 0) {
audio_.CancelPlayback(session);
}
if (was_active) {
ESP_LOGI(kTag, "replay stopped (%s)", reason);
}
}
void ActivationReplayService::OnApplicationEvent(
const AppEvent& event,
const RuntimeState& state)
{
if (event.type == AppEventType::kLocalSequenceRequested ||
event.type == AppEventType::kActivationReplayDue) {
PlayCurrent(state, event.correlation_id);
return;
}
PlaybackSessionId current_session = 0;
bool active = false;
{
std::lock_guard<std::mutex> lock(mutex_);
current_session = current_session_;
active = active_;
}
if (!active) {
return;
}
if (event.type == AppEventType::kPlaybackDrained &&
event.correlation_id == current_session) {
std::lock_guard<std::mutex> lock(mutex_);
current_session_ = 0;
if (active_ && repeating_ && CanPlay(state)) {
esp_timer_stop(timer_);
if (esp_timer_start_once(timer_, kReplayDelayUs) == ESP_OK) {
ESP_LOGI(kTag, "next activation replay in 6000 ms");
return;
}
}
active_ = false;
repeating_ = false;
sequence_ = {};
return;
}
if ((event.type == AppEventType::kPlaybackFailed &&
(event.correlation_id == 0 ||
event.correlation_id == current_session)) ||
(event.type == AppEventType::kPlaybackPreempted &&
event.correlation_id == current_session) ||
event.type == AppEventType::kTtsStarted ||
event.type == AppEventType::kLocalPromptRequested ||
event.type == AppEventType::kShutdownPromptRequested) {
StopWithReason(ToString(event.type));
} else if (!CanPlay(state)) {
StopWithReason("state no longer allows playback");
}
}
void ActivationReplayService::TimerCallback(void* context)
{
static_cast<ActivationReplayService*>(context)->OnTimer();
}
void ActivationReplayService::OnTimer()
{
IEventPublisher* publisher = nullptr;
uint32_t generation = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!active_ || !repeating_) {
return;
}
publisher = publisher_;
generation = generation_;
}
if (publisher != nullptr) {
publisher->Publish(AppEvent::Make(
AppEventType::kActivationReplayDue,
generation));
}
}
void ActivationReplayService::PlayCurrent(
const RuntimeState& state,
uint32_t generation)
{
LocalPromptSequence sequence;
bool should_stop = false;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!active_ || generation != generation_) {
return;
}
if (!CanPlay(state)) {
should_stop = true;
} else {
sequence = sequence_;
}
}
if (should_stop) {
StopLocalSequence();
return;
}
ESP_LOGI(kTag, "replay cycle items=%u generation=%lu",
static_cast<unsigned>(sequence.count),
static_cast<unsigned long>(generation));
const PlaybackSessionId session = audio_.PlayLocalSequence(
sequence, PlaybackPriority::kLocalPrompt);
bool cancel_stale_session = false;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!active_ || generation != generation_) {
cancel_stale_session = session != 0;
} else {
current_session_ = session;
if (session == 0) {
active_ = false;
repeating_ = false;
sequence_ = {};
}
}
}
if (cancel_stale_session) {
audio_.CancelPlayback(session);
}
}
bool ActivationReplayService::CanPlay(
const RuntimeState& state) const
{
return state.lifecycle == LifecycleState::kRunning &&
state.realtime == RealtimeState::kOpen &&
state.call == CallState::kInactive &&
!state.friend_mode &&
!state.alert_ringing &&
!state.idle_sleeping;
}
void ActivationReplayService::StopLocked(
PlaybackSessionId* session_to_cancel)
{
esp_timer_stop(timer_);
*session_to_cancel = current_session_;
current_session_ = 0;
active_ = false;
repeating_ = false;
sequence_ = {};
if (++generation_ == 0) {
++generation_;
}
}
} // namespace borla

View File

@@ -0,0 +1,60 @@
#pragma once
#include "ports/application_observer.h"
#include "ports/audio_engine.h"
#include "ports/event_publisher.h"
#include "ports/local_sequence_handler.h"
#include <cstdint>
#include <mutex>
#include <esp_timer.h>
namespace borla {
class ActivationReplayService final
: public ILocalSequenceHandler,
public IApplicationObserver {
public:
explicit ActivationReplayService(IAudioEngine& audio)
: audio_(audio)
{
}
bool Initialize(IEventPublisher& publisher);
bool StartLocalSequence(
const LocalPromptSequence& sequence) override;
void StopLocalSequence() override;
void OnApplicationEvent(
const AppEvent& event,
const RuntimeState& state) override;
private:
static constexpr uint64_t kReplayDelayUs =
6000ULL * 1000ULL;
static void TimerCallback(void* context);
void OnTimer();
void PlayCurrent(const RuntimeState& state, uint32_t generation);
bool CanPlay(const RuntimeState& state) const;
void StopLocked(PlaybackSessionId* session_to_cancel);
// The previous firmware logged every stop with its trigger
// (StopActivationReplay(reason)). Without it a device stuck reading
// the activation code cannot be told apart from one that simply never
// received the server's stop signal, which is the only thing that ends
// this loop — there is no device-side activation check in either
// firmware.
void StopWithReason(const char* reason);
IAudioEngine& audio_;
IEventPublisher* publisher_ = nullptr;
esp_timer_handle_t timer_ = nullptr;
mutable std::mutex mutex_;
LocalPromptSequence sequence_{};
PlaybackSessionId current_session_ = 0;
uint32_t generation_ = 0;
bool active_ = false;
bool repeating_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,164 @@
#include "adapters/effect_router.h"
namespace borla {
EffectRouter::EffectRouter(
IAudioEngine& audio,
IConnectivityManager& connectivity,
IRealtimeProtocol& realtime,
IDevicePlatform& platform,
IFriendService& friend_service,
IProvisioningService& provisioning,
IOtaService& ota,
IAlertRinger& alert_ringer,
IPowerService& power)
: audio_(audio),
connectivity_(connectivity),
realtime_(realtime),
platform_(platform),
friend_service_(friend_service),
provisioning_(provisioning),
ota_(ota),
alert_ringer_(alert_ringer),
power_(power)
{
}
void EffectRouter::Handle(const AppEffect& effect, const RuntimeState&)
{
switch (effect.type) {
case AppEffectType::kStartAudio:
audio_.Start();
return;
case AppEffectType::kStopAudio:
audio_.Stop();
return;
case AppEffectType::kStartConnectivity:
connectivity_.Start();
return;
case AppEffectType::kStopConnectivity:
connectivity_.Stop();
return;
case AppEffectType::kSwitchNetwork:
connectivity_.SwitchNetwork();
return;
case AppEffectType::kOpenRealtime:
realtime_.Open();
return;
case AppEffectType::kCloseRealtime:
realtime_.Close();
return;
case AppEffectType::kSendStartListening:
realtime_.SendStartListening();
return;
case AppEffectType::kSendStopListening:
realtime_.SendStopListening();
return;
case AppEffectType::kSendAbortSpeaking:
realtime_.SendAbortSpeaking(effect.interrupt_source);
return;
case AppEffectType::kSendGoodbye:
realtime_.SendGoodbye();
return;
case AppEffectType::kSendAcceptCall:
realtime_.SendAcceptCall();
return;
case AppEffectType::kSendHangupCall:
realtime_.SendHangupCall();
return;
case AppEffectType::kSendButtonClick:
realtime_.SendButtonClick(
static_cast<uint8_t>(effect.correlation_id));
return;
case AppEffectType::kSendLocalPlaybackStarted:
realtime_.SendLocalPlaybackState(
effect.local_prompt, true);
return;
case AppEffectType::kSendLocalPlaybackDone:
realtime_.SendLocalPlaybackState(
effect.local_prompt, false);
return;
case AppEffectType::kBeginRemotePlayback:
audio_.BeginRemotePlayback(
effect.correlation_id, effect.playback_priority);
return;
case AppEffectType::kEndPlaybackInput:
audio_.EndPlaybackInput(effect.correlation_id);
return;
case AppEffectType::kPlayLocalPrompt:
audio_.PlayLocalPrompt(
effect.local_prompt,
effect.playback_priority,
effect.prompt_selector);
return;
case AppEffectType::kPlayDetachedPrompt:
audio_.PlayDetachedPrompt(
effect.local_prompt, effect.playback_priority);
return;
case AppEffectType::kApplyAudioPolicy:
audio_.ApplyPolicy(effect.audio_policy);
return;
case AppEffectType::kSetAudioVolume:
audio_.SetVolume(
static_cast<uint8_t>(effect.correlation_id));
return;
case AppEffectType::kSetWakeWordEnabled:
audio_.SetWakeWordEnabled(effect.correlation_id != 0);
return;
case AppEffectType::kSetBargeInEnabled:
audio_.SetBargeInEnabled(effect.correlation_id != 0);
return;
case AppEffectType::kPausePlayback:
audio_.SetPlaybackPaused(true);
return;
case AppEffectType::kResumePlayback:
audio_.SetPlaybackPaused(false);
return;
case AppEffectType::kCancelPlayback:
audio_.CancelPlayback(effect.correlation_id);
return;
case AppEffectType::kSetLed:
platform_.SetLed(effect.led_pattern);
return;
case AppEffectType::kShowTemporaryLedAlert:
platform_.ShowTemporaryLedAlert(effect.correlation_id);
return;
case AppEffectType::kStartFriendMode:
friend_service_.Start();
return;
case AppEffectType::kStopFriendMode:
friend_service_.Stop();
return;
case AppEffectType::kEnterProvisioning:
// Free the WakeNet instance before NimBLE starts. The wake word is
// unused in provisioning and the device reboots out of it, while the
// BT controller needs ~53 KB of internal RAM. The previous firmware
// did the same thing (wifi_board.cc EnterBleConfigMode).
audio_.ReleaseWakeWord();
provisioning_.Start();
return;
case AppEffectType::kStartUpgrade:
ota_.StartUpgrade(effect.correlation_id);
return;
case AppEffectType::kReboot:
platform_.Reboot();
return;
case AppEffectType::kEnterSoftOff:
power_.EnterSoftOff();
return;
case AppEffectType::kStartAlert:
alert_ringer_.Start(effect.alert_kind);
return;
case AppEffectType::kStopAlert:
alert_ringer_.Stop();
return;
case AppEffectType::kRequestConnectionErrorPrompt:
realtime_.RequestConnectionErrorPrompt();
return;
case AppEffectType::kReportError:
platform_.ReportError(effect.correlation_id);
return;
}
}
} // namespace borla

View File

@@ -0,0 +1,47 @@
#pragma once
#include "ports/audio_engine.h"
#include "ports/alert_ringer.h"
#include "ports/connectivity_manager.h"
#include "ports/device_platform.h"
#include "ports/effect_sink.h"
#include "ports/friend_service.h"
#include "ports/ota_service.h"
#include "ports/provisioning_service.h"
#include "ports/power_service.h"
#include "ports/realtime_protocol.h"
namespace borla {
// Composition boundary between the pure state machine and concrete drivers.
// It intentionally contains no product decisions: every operation here must
// be the direct execution of an AppEffect already decided by ReduceState.
class EffectRouter final : public IEffectSink {
public:
EffectRouter(
IAudioEngine& audio,
IConnectivityManager& connectivity,
IRealtimeProtocol& realtime,
IDevicePlatform& platform,
IFriendService& friend_service,
IProvisioningService& provisioning,
IOtaService& ota,
IAlertRinger& alert_ringer,
IPowerService& power);
void Handle(const AppEffect& effect,
const RuntimeState& resulting_state) override;
private:
IAudioEngine& audio_;
IConnectivityManager& connectivity_;
IRealtimeProtocol& realtime_;
IDevicePlatform& platform_;
IFriendService& friend_service_;
IProvisioningService& provisioning_;
IOtaService& ota_;
IAlertRinger& alert_ringer_;
IPowerService& power_;
};
} // namespace borla

View File

@@ -0,0 +1,492 @@
#include "adapters/esp_audio_engine.h"
#include <cmath>
#include <new>
#include <esp_heap_caps.h>
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "EspAudioEngine2";
constexpr uint32_t kAudioOutputInitializationError = 2001;
constexpr uint32_t kPlaybackPipelineInitializationError = 2002;
constexpr uint32_t kPrerollAllocationError = 2003;
} // namespace
EspAudioEngine::EspAudioEngine(
IAudioOutput& output,
IAudioInput& input)
: output_(output),
input_(input),
playback_(output),
prompts_(playback_),
capture_(input)
{
capture_.SetProcessor(&voice_frontend_);
playback_.SetReferenceSink(&voice_frontend_);
}
void EspAudioEngine::SetUplinkSink(IEncodedAudioSink* sink)
{
capture_.SetSink(sink);
}
EspAudioEngine::~EspAudioEngine()
{
Stop();
if (preroll_ != nullptr) {
preroll_->~DownlinkPrerollBuffer();
heap_caps_free(preroll_);
preroll_ = nullptr;
}
}
void EspAudioEngine::SetEventPublisher(IEventPublisher* publisher)
{
publisher_ = publisher;
playback_.SetEventPublisher(publisher);
voice_frontend_.SetEventPublisher(publisher);
}
bool EspAudioEngine::Start()
{
if (started_) {
return true;
}
if (preroll_ == nullptr) {
void* storage = heap_caps_malloc(
sizeof(DownlinkPrerollBuffer),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (storage == nullptr) {
PublishFatalError(kPrerollAllocationError);
return false;
}
preroll_ = new (storage) DownlinkPrerollBuffer();
}
if (!output_.Initialize()) {
PublishFatalError(kAudioOutputInitializationError);
return false;
}
if (!playback_.Initialize() || !prompts_.Initialize() ||
!voice_frontend_.Initialize() ||
!capture_.Initialize() || !playback_.Start() ||
!capture_.Start()) {
capture_.Stop();
playback_.Stop();
output_.Shutdown();
PublishFatalError(kPlaybackPipelineInitializationError);
return false;
}
started_ = true;
ESP_LOGI(kTag, "audio output and playback pipeline started");
return true;
}
void EspAudioEngine::Stop()
{
if (!started_) {
return;
}
capture_.Stop();
{
std::lock_guard<std::mutex> lock(downlink_mutex_);
ClearPrerollLocked();
playback_.Stop();
}
output_.Shutdown();
started_ = false;
}
void EspAudioEngine::ApplyPolicy(AudioPolicy policy)
{
requested_policy_.store(policy);
RefreshEffectivePolicy();
}
void EspAudioEngine::SetVolume(uint8_t volume_percent)
{
output_.SetVolume(volume_percent);
}
void EspAudioEngine::SetWakeWordEnabled(bool enabled)
{
wake_word_enabled_.store(enabled);
RefreshEffectivePolicy();
}
void EspAudioEngine::SetBargeInEnabled(bool enabled)
{
barge_in_enabled_.store(enabled);
RefreshEffectivePolicy();
}
void EspAudioEngine::SetPlaybackPaused(bool paused)
{
playback_.SetPaused(paused);
}
void EspAudioEngine::RefreshEffectivePolicy()
{
const AudioPolicy requested = requested_policy_.load();
const bool wake_word = wake_word_enabled_.load();
const bool barge_in = barge_in_enabled_.load();
AudioPolicy effective = requested;
if (requested == AudioPolicy::kWakeWordOnly && !wake_word) {
effective = AudioPolicy::kOff;
} else if (
requested == AudioPolicy::kBargeInDuplex && !barge_in) {
effective = wake_word
? AudioPolicy::kWakeWordDuplex
: AudioPolicy::kPlaybackOnly;
}
voice_frontend_.SetWakeWordEnabled(wake_word);
capture_.ApplyPolicy(effective);
ESP_LOGI(
kTag,
"audio policy requested=%s effective=%s wake=%d barge=%d",
ToString(requested),
ToString(effective),
wake_word ? 1 : 0,
barge_in ? 1 : 0);
}
void EspAudioEngine::OnRealtimeBinary(
const uint8_t* data,
size_t size,
uint32_t playback_session_id)
{
if (!SubmitOpusFrame(playback_session_id, data, size)) {
ESP_LOGW(kTag,
"downlink Opus dropped session=%lu size=%u",
static_cast<unsigned long>(playback_session_id),
static_cast<unsigned>(size));
}
}
void EspAudioEngine::CancelPlayback(PlaybackSessionId session_id)
{
std::lock_guard<std::mutex> lock(downlink_mutex_);
ClearPrerollLocked();
playback_.Cancel(session_id);
}
void EspAudioEngine::BeginRemotePlayback(
PlaybackSessionId session_id,
PlaybackPriority priority)
{
std::lock_guard<std::mutex> lock(downlink_mutex_);
const PlaybackSource source =
priority == PlaybackPriority::kCall
? PlaybackSource::kCall
: PlaybackSource::kRemoteTts;
const PlaybackStartResult result = playback_.StartSession(
source, priority, session_id);
if (result.status != PlaybackStartStatus::kStarted &&
result.status != PlaybackStartStatus::kAlreadyActive) {
if (preroll_ != nullptr &&
preroll_->session_id() == session_id) {
ClearPrerollLocked();
}
ESP_LOGW(kTag,
"remote playback rejected status=%s session=%lu priority=%s",
ToString(result.status),
static_cast<unsigned long>(session_id),
ToString(priority));
return;
}
FlushPrerollLocked(session_id);
}
void EspAudioEngine::EndPlaybackInput(PlaybackSessionId session_id)
{
std::lock_guard<std::mutex> lock(downlink_mutex_);
if (!playback_.EndInput(session_id)) {
if (preroll_ != nullptr &&
preroll_->session_id() == session_id) {
ClearPrerollLocked();
}
ESP_LOGW(kTag, "ignored end input for stale session=%lu",
static_cast<unsigned long>(session_id));
}
}
bool EspAudioEngine::SubmitOpusFrame(
PlaybackSessionId session_id,
const uint8_t* data,
size_t size)
{
std::lock_guard<std::mutex> lock(downlink_mutex_);
if (playback_.SubmitOpus(session_id, data, size)) {
return true;
}
const PlaybackSessionSnapshot snapshot = playback_.Snapshot();
if ((snapshot.active && snapshot.id == session_id) ||
preroll_ == nullptr) {
return false;
}
return preroll_->Push(session_id, data, size);
}
void EspAudioEngine::ClearPrerollLocked()
{
if (preroll_ != nullptr) {
preroll_->Reset();
}
}
void EspAudioEngine::FlushPrerollLocked(PlaybackSessionId session_id)
{
if (preroll_ == nullptr ||
preroll_->session_id() != session_id) {
return;
}
const size_t frame_count = preroll_->frame_count();
size_t submitted = 0;
for (; submitted < frame_count; ++submitted) {
if (!playback_.SubmitOpus(
session_id,
preroll_->FrameData(submitted),
preroll_->FrameSize(submitted))) {
break;
}
}
preroll_->Reset();
if (submitted != frame_count) {
ESP_LOGW(
kTag,
"downlink pre-roll flush incomplete session=%lu submitted=%u total=%u",
static_cast<unsigned long>(session_id),
static_cast<unsigned>(submitted),
static_cast<unsigned>(frame_count));
} else if (frame_count != 0) {
ESP_LOGD(
kTag,
"downlink pre-roll flushed session=%lu frames=%u",
static_cast<unsigned long>(session_id),
static_cast<unsigned>(frame_count));
}
}
PlaybackSessionId EspAudioEngine::PlayLocalPrompt(
LocalPrompt prompt,
PlaybackPriority priority,
int16_t selector)
{
const PlaybackSessionId session_id =
prompts_.Play(prompt, priority, selector);
if (session_id == 0 && publisher_ != nullptr) {
publisher_->Publish(
AppEvent::Make(AppEventType::kPlaybackFailed));
} else if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kLocalPromptStarted,
session_id,
static_cast<int32_t>(prompt),
static_cast<uint32_t>(priority)));
}
return session_id;
}
PlaybackSessionId EspAudioEngine::PlayDetachedPrompt(
LocalPrompt prompt,
PlaybackPriority priority)
{
// Deliberately silent on the control plane: no kLocalPromptStarted, no
// kPlaybackFailed. The caller's conversation state must survive this
// prompt unchanged.
const PlaybackSessionId session_id =
prompts_.Play(prompt, priority, -1);
if (session_id == 0) {
ESP_LOGW(kTag, "detached prompt rejected prompt=%s",
ToString(prompt));
}
return session_id;
}
uint8_t EspAudioEngine::OutputVolumePercent() const
{
return output_.VolumePercent();
}
PlaybackSessionId EspAudioEngine::PlayLocalSequence(
const LocalPromptSequence& sequence,
PlaybackPriority priority)
{
const PlaybackSessionId session_id =
prompts_.PlaySequence(sequence, priority);
if (session_id == 0 && publisher_ != nullptr) {
publisher_->Publish(
AppEvent::Make(AppEventType::kPlaybackFailed));
} else if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kLocalSequenceStarted,
session_id,
static_cast<int32_t>(sequence.count),
static_cast<uint32_t>(priority)));
}
return session_id;
}
PlaybackSessionSnapshot EspAudioEngine::PlaybackSnapshot() const
{
return playback_.Snapshot();
}
PlaybackMetrics EspAudioEngine::PlaybackMetricsSnapshot() const
{
return playback_.Metrics();
}
CaptureMetrics EspAudioEngine::CaptureMetricsSnapshot() const
{
return capture_.Metrics();
}
VoiceFrontendMetrics EspAudioEngine::VoiceMetricsSnapshot() const
{
return voice_frontend_.Metrics();
}
void EspAudioEngine::ReleaseWakeWord()
{
voice_frontend_.ReleaseWakeWord();
}
bool EspAudioEngine::WaitForPlaybackIdle(uint32_t timeout_ms)
{
constexpr uint32_t kPollIntervalMs = 20;
uint32_t waited_ms = 0;
while (playback_.Active()) {
if (waited_ms >= timeout_ms) {
ESP_LOGW(kTag, "playback still active after %lums",
static_cast<unsigned long>(timeout_ms));
return false;
}
vTaskDelay(pdMS_TO_TICKS(kPollIntervalMs));
waited_ms += kPollIntervalMs;
}
return true;
}
void EspAudioEngine::LogAudioMetrics(const char* reason)
{
voice_frontend_.LogMetrics(reason);
// The capture counters answer the question the voice counters raise: when
// the reference ring keeps overrunning, it is because this task is not
// consuming one frame per 60 ms. read_failures and encode_failures say
// whether frames are being lost at the I2S read or in the DSP/encoder.
const CaptureMetrics capture = capture_.Metrics();
ESP_LOGI(kTag,
"capture metrics (%s) read=%lu encoded=%lu sent=%lu "
"read_fail=%lu encode_fail=%lu backpressure=%lu max_bytes=%lu",
reason,
static_cast<unsigned long>(capture.frames_read),
static_cast<unsigned long>(capture.frames_encoded),
static_cast<unsigned long>(capture.frames_sent),
static_cast<unsigned long>(capture.read_failures),
static_cast<unsigned long>(capture.encode_failures),
static_cast<unsigned long>(capture.backpressure_drops),
static_cast<unsigned long>(capture.maximum_encoded_bytes));
}
bool EspAudioEngine::LogAudioFrameStats()
{
const VoiceFrameStats stats = voice_frontend_.ConsumeFrameStats();
if (stats.frames == 0) {
return false;
}
// Only duplex windows carry information worth a log line: idle wake-word
// and quiet capture windows printed all-zero ERL/reference columns every
// two seconds and drowned the conversation log. The accumulators above
// are still consumed either way so a later interesting window reports
// only its own frames.
const bool duplex_window =
stats.policy == AudioPolicy::kBargeInDuplex ||
stats.policy == AudioPolicy::kCallDuplex ||
stats.reference_present_frames != 0;
if (!duplex_window) {
capture_.ConsumeTimings();
return false;
}
const uint32_t frames = stats.frames;
const uint32_t microphone_rms = stats.microphone_rms_sum / frames;
const uint32_t processed_rms = stats.processed_rms_sum / frames;
const uint32_t reference_rms = stats.reference_rms_sum / frames;
// Echo return loss: how much quieter the chain made the microphone. With a
// correctly aligned reference this is strongly positive while the speaker
// is playing; near 0 dB means the AEC is not cancelling and the device is
// about to hear itself.
float echo_return_loss_db = 0.0F;
if (microphone_rms > 0 && processed_rms > 0) {
echo_return_loss_db = 20.0F * std::log10(
static_cast<float>(microphone_rms) /
static_cast<float>(processed_rms));
}
const uint32_t period_us_avg = frames > 1
? static_cast<uint32_t>(stats.period_us_sum / (frames - 1))
: 0;
const CaptureTimings timings = capture_.ConsumeTimings();
if (timings.frames != 0) {
const uint32_t n = timings.frames;
ESP_LOGI(
kTag,
"capture timing n=%lu read=%lu/%lu convert=%lu process=%lu/%lu "
"encode=%lu/%lu submit=%lu/%lu (us, avg/max)",
static_cast<unsigned long>(n),
static_cast<unsigned long>(timings.read_us / n),
static_cast<unsigned long>(timings.read_us_max),
static_cast<unsigned long>(timings.convert_us / n),
static_cast<unsigned long>(timings.process_us / n),
static_cast<unsigned long>(timings.process_us_max),
static_cast<unsigned long>(timings.encode_us / n),
static_cast<unsigned long>(timings.encode_us_max),
static_cast<unsigned long>(timings.submit_us / n),
static_cast<unsigned long>(timings.submit_us_max));
}
ESP_LOGI(
kTag,
"frame stats policy=%s n=%lu mic_rms=%lu/%lu out_rms=%lu/%lu "
"erl=%.1fdB ref_rms=%lu/%lu ref_present=%lu ref_active=%lu "
"ref_depth=%.1f/%lu aec=%d ns=%d barge_profile=%d agc_gain=%.2f "
"vad_speech=%lu period_avg=%.1fms period_max=%.1fms",
ToString(stats.policy),
static_cast<unsigned long>(frames),
static_cast<unsigned long>(microphone_rms),
static_cast<unsigned long>(stats.microphone_rms_peak),
static_cast<unsigned long>(processed_rms),
static_cast<unsigned long>(stats.processed_rms_peak),
echo_return_loss_db,
static_cast<unsigned long>(reference_rms),
static_cast<unsigned long>(stats.reference_rms_peak),
static_cast<unsigned long>(stats.reference_present_frames),
static_cast<unsigned long>(stats.reference_active_frames),
static_cast<double>(stats.reference_depth_sum) /
static_cast<double>(frames),
static_cast<unsigned long>(stats.reference_depth_peak),
stats.aec_active ? 1 : 0,
stats.ns_active ? 1 : 0,
stats.barge_in_profile ? 1 : 0,
static_cast<double>(stats.agc_gain),
static_cast<unsigned long>(stats.vad_speech_frames),
static_cast<double>(period_us_avg) / 1000.0,
static_cast<double>(stats.period_us_max) / 1000.0);
return true;
}
void EspAudioEngine::PublishFatalError(uint32_t error_id)
{
ESP_LOGE(kTag, "fatal audio initialization error=%lu",
static_cast<unsigned long>(error_id));
if (publisher_ != nullptr) {
publisher_->Publish(
AppEvent::Make(AppEventType::kFatalError, error_id));
}
}
} // namespace borla

View File

@@ -0,0 +1,94 @@
#pragma once
#include "audio/audio_output.h"
#include "audio/audio_input.h"
#include "audio/capture_pipeline.h"
#include "audio/downlink_preroll_buffer.h"
#include "audio/local_prompt_player.h"
#include "audio/playback_pipeline.h"
#include "audio/voice_frontend.h"
#include "ports/audio_engine.h"
#include "ports/event_publisher.h"
#include "protocol/realtime_binary_sink.h"
#include <atomic>
#include <mutex>
namespace borla {
class EspAudioEngine final
: public IAudioEngine,
public IRealtimeBinarySink {
public:
EspAudioEngine(IAudioOutput& output, IAudioInput& input);
~EspAudioEngine();
void SetEventPublisher(IEventPublisher* publisher);
void SetUplinkSink(IEncodedAudioSink* sink);
// Debug recorder pass-through: the capture pipeline feeds the tap's
// "server's-ear" uplink channel.
void SetAudioTap(AudioTap* tap) { capture_.SetAudioTap(tap); }
bool Start() override;
void Stop() override;
void ApplyPolicy(AudioPolicy policy) override;
void SetVolume(uint8_t volume_percent) override;
void SetWakeWordEnabled(bool enabled) override;
void SetBargeInEnabled(bool enabled) override;
void SetPlaybackPaused(bool paused) override;
void ReleaseWakeWord() override;
bool WaitForPlaybackIdle(uint32_t timeout_ms) override;
void LogAudioMetrics(const char* reason) override;
bool LogAudioFrameStats() override;
void CancelPlayback(PlaybackSessionId session_id) override;
void BeginRemotePlayback(
PlaybackSessionId session_id,
PlaybackPriority priority) override;
void EndPlaybackInput(PlaybackSessionId session_id) override;
bool SubmitOpusFrame(
PlaybackSessionId session_id,
const uint8_t* data,
size_t size) override;
PlaybackSessionId PlayLocalPrompt(
LocalPrompt prompt,
PlaybackPriority priority,
int16_t selector = -1) override;
PlaybackSessionId PlayLocalSequence(
const LocalPromptSequence& sequence,
PlaybackPriority priority) override;
PlaybackSessionId PlayDetachedPrompt(
LocalPrompt prompt,
PlaybackPriority priority) override;
uint8_t OutputVolumePercent() const override;
void OnRealtimeBinary(
const uint8_t* data,
size_t size,
uint32_t playback_session_id) override;
PlaybackSessionSnapshot PlaybackSnapshot() const;
PlaybackMetrics PlaybackMetricsSnapshot() const;
CaptureMetrics CaptureMetricsSnapshot() const;
VoiceFrontendMetrics VoiceMetricsSnapshot() const;
private:
void PublishFatalError(uint32_t error_id);
void RefreshEffectivePolicy();
void ClearPrerollLocked();
void FlushPrerollLocked(PlaybackSessionId session_id);
IAudioOutput& output_;
IAudioInput& input_;
IEventPublisher* publisher_ = nullptr;
PlaybackPipeline playback_;
LocalPromptPlayer prompts_;
VoiceFrontend voice_frontend_;
CapturePipeline capture_;
std::mutex downlink_mutex_;
DownlinkPrerollBuffer* preroll_ = nullptr;
std::atomic<AudioPolicy> requested_policy_{AudioPolicy::kOff};
std::atomic<bool> wake_word_enabled_{true};
std::atomic<bool> barge_in_enabled_{false};
bool started_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,52 @@
#pragma once
#include "core/app_event.h"
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <cstddef>
#include <cstdint>
namespace borla {
class AppEventQueue {
public:
static constexpr size_t kCapacity = 32;
AppEventQueue()
{
queue_ = xQueueCreateStatic(
kCapacity,
sizeof(AppEvent),
storage_,
&queue_storage_);
}
bool Publish(const AppEvent& event, TickType_t wait_ticks = 0)
{
return xQueueSend(queue_, &event, wait_ticks) == pdTRUE;
}
bool PublishFromIsr(const AppEvent& event, BaseType_t* higher_priority_woken)
{
return xQueueSendFromISR(queue_, &event, higher_priority_woken) == pdTRUE;
}
bool Receive(AppEvent* event, TickType_t wait_ticks = portMAX_DELAY)
{
return xQueueReceive(queue_, event, wait_ticks) == pdTRUE;
}
size_t Pending() const
{
return static_cast<size_t>(uxQueueMessagesWaiting(queue_));
}
private:
StaticQueue_t queue_storage_{};
alignas(AppEvent) uint8_t storage_[kCapacity * sizeof(AppEvent)]{};
QueueHandle_t queue_ = nullptr;
};
} // namespace borla

92
main/app/application.cc Normal file
View File

@@ -0,0 +1,92 @@
#include "app/application.h"
#include "core/state_reducer.h"
#include <esp_log.h>
namespace borla
{
namespace
{
constexpr const char *kTag = "Application2";
} // namespace
Application::Application(IEffectSink &effects)
: effects_(effects)
{
}
[[noreturn]] void Application::Run()
{
ESP_LOGI(kTag, "control-plane event loop starting");
ProcessEvent(AppEvent::Make(AppEventType::kBootRequested));
while (true)
{
AppEvent event;
if (events_.Receive(&event))
{
ProcessEvent(event);
}
}
}
bool Application::Publish(const AppEvent &event)
{
if (events_.Publish(event))
{
return true;
}
ESP_LOGE(kTag, "event queue full, dropped event=%s pending=%u",
ToString(event.type),
static_cast<unsigned>(events_.Pending()));
return false;
}
void Application::ProcessEvent(const AppEvent &event)
{
const TransitionResult transition = ReduceState(state_, event);
const StateValidation validation = ValidateRuntimeState(transition.next);
if (!validation.valid)
{
ESP_LOGE(kTag, "rejected invalid transition event=%s reason=%s",
ToString(event.type), validation.reason);
return;
}
state_ = transition.next;
LogState(event);
for (size_t i = 0; i < transition.effect_count; ++i)
{
effects_.Handle(transition.effects[i], state_);
}
for (size_t i = 0; i < observer_count_; ++i)
{
observers_[i]->OnApplicationEvent(event, state_);
}
}
void Application::LogState(const AppEvent &event) const
{
ESP_LOGI(kTag,
"event=%s lifecycle=%s net=%s realtime=%s conversation=%s "
"call=%s playback=%s session=%lu pending_start=%d "
"pending_soft_off=%d",
ToString(event.type),
ToString(state_.lifecycle),
ToString(state_.connectivity),
ToString(state_.realtime),
ToString(state_.conversation),
ToString(state_.call),
ToString(state_.playback),
static_cast<unsigned long>(state_.playback_session_id),
state_.pending_conversation_start ? 1 : 0,
state_.pending_soft_off_after_playback ? 1 : 0);
}
} // namespace borla

41
main/app/application.h Normal file
View File

@@ -0,0 +1,41 @@
#pragma once
#include "app/app_event_queue.h"
#include "core/runtime_state.h"
#include "ports/effect_sink.h"
#include "ports/event_publisher.h"
#include "ports/application_observer.h"
#include <array>
namespace borla {
class Application final : public IEventPublisher {
public:
explicit Application(IEffectSink& effects);
[[noreturn]] void Run();
bool Publish(const AppEvent& event) override;
bool AddObserver(IApplicationObserver* observer)
{
if (observer == nullptr || observer_count_ >= observers_.size()) {
return false;
}
observers_[observer_count_++] = observer;
return true;
}
const RuntimeState& state() const { return state_; }
private:
void ProcessEvent(const AppEvent& event);
void LogState(const AppEvent& event) const;
IEffectSink& effects_;
AppEventQueue events_;
RuntimeState state_;
std::array<IApplicationObserver*, 4> observers_{};
size_t observer_count_ = 0;
};
} // namespace borla

View File

@@ -0,0 +1,401 @@
#include "app/composition_root.h"
#include "platform/borla_s3/board_config.h"
#include <esp_netif.h>
#include <esp_err.h>
#include <esp_event.h>
#include <esp_log.h>
#include <nvs_flash.h>
namespace borla
{
namespace
{
constexpr const char *kTag = "CompositionRoot2";
constexpr uint32_t kSystemServicesInitializationError = 1000;
constexpr uint32_t kPlatformInitializationError = 1001;
constexpr uint32_t kButtonInitializationError = 1002;
constexpr uint32_t kConnectivityInitializationError = 1003;
constexpr uint32_t kRealtimeInitializationError = 1004;
constexpr uint32_t kProvisioningInitializationError = 1005;
constexpr uint32_t kSensorInitializationError = 1006;
constexpr uint32_t kScheduleInitializationError = 1007;
constexpr uint32_t kPowerInitializationError = 1008;
constexpr uint32_t kIdleInitializationError = 1009;
constexpr uint32_t kOtaInitializationError = 1010;
constexpr uint32_t kFriendInitializationError = 1011;
constexpr uint32_t kMemoryInitializationError = 1012;
constexpr uint32_t kActivationInitializationError = 1013;
constexpr uint32_t kDiagnosticsInitializationError = 1014;
constexpr uint32_t kRemoteBehaviorInitializationError = 1015;
constexpr uint32_t kTca9555InitializationError = 1016;
} // namespace
CompositionRoot::CompositionRoot()
: i2c_bus_(),
tca9555_(i2c_bus_),
platform_(tca9555_),
// audio_output_(i2c_bus_),、
audio_output_(i2c_bus_, tca9555_),
audio_(audio_output_, audio_output_),
activation_replay_(audio_),
dual_network_transport_(
wifi_transport_,
cellular_transport_,
DualNetworkPolicyConfig{
board_config::kWifiDisconnectFailoverMs,
board_config::kWifiWeakRssiDbm,
board_config::kWifiWeakSampleCount,
board_config::kModemAbsentSampleCount,
board_config::kModemUnavailableRepeatMs,
}),
connectivity_(
dual_network_transport_,
wifi_credentials_,
ReconnectBackoffConfig{
board_config::kWifiRetryInitialDelayMs,
board_config::kWifiRetryMaximumDelayMs,
board_config::kWifiRetryMultiplier,
board_config::kWifiRetryJitterPercent,
}),
realtime_(websocket_transport_, realtime_config_),
friend_service_(
ble_friend_exchange_,
friend_store_,
realtime_,connectivity_),
imu_(i2c_bus_),
sensors_(touch_, imu_, battery_, realtime_),
alarms_(alarm_store_),
schedule_(reminders_, alarms_),
alert_ringer_(audio_, alarms_),
provisioning_(wifi_transport_, wifi_credentials_, platform_, audio_),
power_(sensors_, sensors_, alarms_, reminders_, platform_),
effect_router_(audio_, connectivity_, realtime_, platform_,
friend_service_, provisioning_, ota_,
alert_ringer_, power_),
application_(effect_router_),
//button_(application_, remote_behavior_config_)
idle_(),
button_(application_, remote_behavior_config_, tca9555_)//2026-9-4 ckkj add
{
audio_.SetEventPublisher(&application_);
connectivity_.SetEventPublisher(&application_);
connectivity_.SetRemoteBehaviorConfig(
&remote_behavior_config_);
realtime_.SetEventPublisher(&application_);
realtime_.SetBinarySink(&audio_);
realtime_.SetScheduleCommandHandler(&schedule_);
realtime_.SetBatteryStatusProvider(&sensors_);
realtime_.SetVolumeStatusProvider(&audio_);
realtime_.SetDeviceProfileSink(&friend_service_);
realtime_.SetLocalSequenceHandler(&activation_replay_);
realtime_.SetMemoryCache(&memory_cache_);
realtime_.SetRemoteBehaviorConfig(
&remote_behavior_config_);
audio_.SetUplinkSink(&realtime_);
ota_.SetRealtimeConfigStore(&realtime_config_);
ota_.SetRealtimeProtocol(&realtime_);
sensors_.SetEventPublisher(&application_);
provisioning_.SetEventPublisher(&application_);
diagnostics_.SetAudioEngine(&audio_);
alert_ringer_.SetEventPublisher(application_);
application_.AddObserver(&idle_);
application_.AddObserver(&ota_);
application_.AddObserver(&friend_service_);
application_.AddObserver(&activation_replay_);
}
bool CompositionRoot::Initialize()
{
if (!InitializeSystemServices())
{
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kSystemServicesInitializationError));
return false;
}
#if CONFIG_BORLA_AUDIO_TAP
// Armed before the audio engine starts so the boot prompt is already in
// the ring when the host recorder attaches. Failure is logged inside and
// never blocks boot — this is diagnostics, not product.
if (audio_tap_.Initialize())
{
audio_output_.SetAudioTap(&audio_tap_);
audio_.SetAudioTap(&audio_tap_);
}
#endif
bool valid = true;
if (!i2c_bus_.Initialize())
{
ESP_LOGE(kTag, "I2C bus initialization failed");
valid = false;
}
esp_err_t tca_ret = tca9555_.Init();
if (tca_ret != ESP_OK)
{
ESP_LOGE(kTag, "TCA9555 IO扩展芯片 init failed, err=%d", tca_ret);
valid = false;
}
else
{
ESP_LOGI(kTag, "TCA9555 IO扩展初始化成功");
//tca9555_.set_pin(V5_EN);//舵机,SD需要
cellular_transport_.SetPowerControl(
[this](bool on) {
if (on) {
tca9555_.set_pin(EN_4G);
} else {
tca9555_.clr_pin(EN_4G);// 4G模块断电
}
uint8_t out0 = 0;
if (tca9555_.read_reg(TCA9555_REG_OUT0, &out0) == ESP_OK) {
ESP_LOGI(kTag, "4G pwr on=%d OUT0=0x%02x EN_4G(P0.2)=%d", on, out0, (out0 >> TCA_P0_ADD_IO) & 1U);
}
});
}
if (!platform_.Initialize())
{
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kPlatformInitializationError));
valid = false;
}
else
{
// uint8_t val = 0;
// esp_err_t ret = tca9555_.read_p1_input(&val);
// ESP_LOGI(kTag,"val=%02X",val);
const DeviceIdentity &identity = platform_.Identity();
ESP_LOGI(kTag, "identity board=%s mac=%s version=%s chip=%s",
identity.board, identity.mac, identity.app_version,
identity.chip_model);
//#if CONFIG_BORLA_AUDIO_TAP
// I2C bus scan — verifies ES8389 (0x10) and TCA9555 (0x20) are present.
// Temporary debug aid, remove after hardware is validated.
{
i2c_master_bus_handle_t bus = i2c_bus_.Handle();
if (bus != nullptr) {
ESP_LOGI(kTag, "I2C scan start...");
int found2 = 0;
for (uint8_t addr7 = 0x08; addr7 < 0x78; ++addr7) {
i2c_master_dev_handle_t dev = nullptr;
i2c_device_config_t cfg = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = addr7,
.scl_speed_hz = 100000,
.scl_wait_us = 0,
.flags = {},
};
if (i2c_master_bus_add_device(bus, &cfg, &dev) == ESP_OK) {
uint8_t buf = 0;
if (i2c_master_transmit_receive(dev, &buf, 1, &buf, 1, pdMS_TO_TICKS(50)) == ESP_OK) {
ESP_LOGI(kTag, "I2C scan: found device at 0x%02x (7-bit) / 0x%02x (8-bit)",
addr7, addr7 << 1);
found2++;
}
i2c_master_bus_rm_device(dev);
}
}
ESP_LOGI(kTag, "I2C scan done (brute): %d device(s) found", found2);
// Restore Port1 to normal (only power rails)
}
}
//#endif
}
if (!valid)
{
platform_.ReportError(kTca9555InitializationError);
}
if (!dual_network_transport_.Initialize() ||
!connectivity_.Initialize())
{
platform_.ReportError(kConnectivityInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kConnectivityInitializationError));
valid = false;
}
if (!memory_cache_.Load())
{
platform_.ReportError(kMemoryInitializationError);
valid = false;
}
if (!remote_behavior_config_.Load())
{
platform_.ReportError(kRemoteBehaviorInitializationError);
application_.Publish(
AppEvent::Make(
AppEventType::kFatalError,
kRemoteBehaviorInitializationError));
valid = false;
}
if (!activation_replay_.Initialize(application_))
{
platform_.ReportError(kActivationInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kActivationInitializationError));
valid = false;
}
if (!diagnostics_.Initialize())
{
platform_.ReportError(kDiagnosticsInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kDiagnosticsInitializationError));
valid = false;
}
if (!realtime_.Initialize(platform_.Identity()))
{
platform_.ReportError(kRealtimeInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kRealtimeInitializationError));
valid = false;
}
if (!friend_service_.Initialize(
platform_.Identity(), application_))
{
platform_.ReportError(kFriendInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kFriendInitializationError));
valid = false;
}
if (!ota_.Initialize(platform_.Identity(), application_))
{
platform_.ReportError(kOtaInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kOtaInitializationError));
valid = false;
}
if (!provisioning_.Initialize())
{
platform_.ReportError(kProvisioningInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kProvisioningInitializationError));
valid = false;
}
if (!sensors_.Initialize())
{
platform_.ReportError(kSensorInitializationError);
ESP_LOGE(kTag, "sensor service initialization failed");
valid = false;
}
if (!reminders_.Initialize(application_) ||
!alarms_.Initialize(application_, realtime_))
{
platform_.ReportError(kScheduleInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kScheduleInitializationError));
valid = false;
}
//2026-9-4 ckkj add
if (!button_.Initialize())
{
platform_.ReportError(kButtonInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kButtonInitializationError));
valid = false;
}//////
if (!power_.Initialize(application_))
{
platform_.ReportError(kPowerInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kPowerInitializationError));
valid = false;
}
if (!idle_.Initialize(application_))
{
platform_.ReportError(kIdleInitializationError);
application_.Publish(
AppEvent::Make(AppEventType::kFatalError,
kIdleInitializationError));
valid = false;
}
// if (!button_.Initialize())
// {
// platform_.ReportError(kButtonInitializationError);
// application_.Publish(
// AppEvent::Make(AppEventType::kFatalError,
// kButtonInitializationError));
// valid = false;
// }
if (valid)
{
valid = ota_.ConfirmCurrentImage();
}
if (!valid)
{
ota_.RejectCurrentImageAndRollback();
}
return valid;
}
[[noreturn]] void CompositionRoot::Run()
{
application_.Run();
}
bool CompositionRoot::InitializeSystemServices()
{
esp_err_t result = nvs_flash_init();
if (result == ESP_ERR_NVS_NO_FREE_PAGES ||
result == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
result = nvs_flash_erase();
if (result == ESP_OK)
{
result = nvs_flash_init();
}
}
if (result != ESP_OK)
{
ESP_LOGE(kTag, "NVS initialization failed: %s",
esp_err_to_name(result));
return false;
}
result = esp_event_loop_create_default();
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE)
{
ESP_LOGE(kTag, "default event loop creation failed: %s",
esp_err_to_name(result));
return false;
}
// 2026-9-19 ckkj fix: esp_netif_init() 原本只在 WiFi 驱动初始化时调用。
// 强制 4G 路径下 WiFi 不启动,tcpip_init() 不执行,tcpip_mbox 未创建,
// AudioTap 的 socket() 触发 lwIP "Invalid mbox" 断言并启动循环。
// PPP 的 esp_netif_receive 也依赖 tcpip 线程。此处统一初始化。
result = esp_netif_init();
if (result != ESP_OK)
{
ESP_LOGE(kTag, "esp_netif_init failed: %s",
esp_err_to_name(result));
return false;
}/////////
return true;
}
} // namespace borla

View File

@@ -0,0 +1,90 @@
#pragma once
#include "activation/activation_replay_service.h"
#include "adapters/effect_router.h"
#include "adapters/esp_audio_engine.h"
#include "app/application.h"
#include "connectivity/connectivity_manager.h"
#include "connectivity/dual_network_transport.h"
#include "connectivity/wifi_credential_store.h"
#include "configuration/remote_behavior_config.h"
#include "diagnostics/audio_tap.h"
#include "diagnostics/runtime_diagnostics_service.h"
#include "friend/friend_service.h"
#include "friend/friend_store.h"
#include "memory/memory_cache.h"
#include "platform/borla_s3/borla_s3_platform.h"
#include "platform/borla_s3/battery_monitor.h"
#include "platform/borla_s3/ble_friend_exchange.h"
#include "platform/borla_s3/bmi270_sensor.h"
#include "platform/borla_s3/button_input.h"
#include "platform/borla_s3/capacitive_touch_input.h"
#include "platform/borla_s3/es8311_audio_output.h"
#include "platform/borla_s3/esp_websocket_transport.h"
#include "platform/borla_s3/esp_wifi_transport.h"
#include "platform/borla_s3/i2c_bus.h"
#include "platform/borla_s3/ml307_transport.h"
#include "ota/ota_service.h"
#include "provisioning/ble_provisioning_service.h"
#include "power/idle_service.h"
#include "power/power_service.h"
#include "protocol/realtime_config.h"
#include "protocol/realtime_protocol.h"
#include "sensor/sensor_service.h"
#include "schedule/alarm_service.h"
#include "schedule/alarm_store.h"
#include "schedule/alert_ringer.h"
#include "schedule/reminder_service.h"
#include "schedule/schedule_coordinator.h"
#include "platform/borla_s3/tca9555.h"
namespace borla {
class CompositionRoot final {
public:
CompositionRoot();
bool Initialize();
[[noreturn]] void Run();
private:
bool InitializeSystemServices();
BorlaS3I2cBus i2c_bus_;
TCA9555 tca9555_;
BorlaS3Platform platform_;
Es8311AudioOutput audio_output_;
EspAudioEngine audio_;
ActivationReplayService activation_replay_;
NvsMemoryCache memory_cache_;
NvsRemoteBehaviorConfig remote_behavior_config_;
RuntimeDiagnosticsService diagnostics_;
AudioTap audio_tap_;
NvsWifiCredentialStore wifi_credentials_;
EspWifiTransport wifi_transport_;
Ml307Transport cellular_transport_;
DualNetworkTransport dual_network_transport_;
ConnectivityManager connectivity_;
NvsRealtimeConfigStore realtime_config_;
EspWebsocketTransport websocket_transport_;
RealtimeProtocol realtime_;
BleFriendExchange ble_friend_exchange_;
NvsFriendStore friend_store_;
FriendService friend_service_;
CapacitiveTouchInput touch_;
Bmi270Sensor imu_;
BatteryMonitor battery_;
SensorService sensors_;
NvsAlarmStore alarm_store_;
ReminderService reminders_;
AlarmService alarms_;
ScheduleCoordinator schedule_;
AlertRinger alert_ringer_;
BleProvisioningService provisioning_;
OtaService ota_;
PowerService power_;
EffectRouter effect_router_;
Application application_;
IdleService idle_;
ButtonInput button_;
};
} // namespace borla

19
main/audio/audio_input.h Normal file
View File

@@ -0,0 +1,19 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class IAudioInput {
public:
virtual ~IAudioInput() = default;
virtual bool Read(
int16_t* samples,
size_t sample_count,
uint32_t timeout_ms) = 0;
virtual uint32_t InputSampleRate() const = 0;
};
} // namespace borla

20
main/audio/audio_output.h Normal file
View File

@@ -0,0 +1,20 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class IAudioOutput {
public:
virtual ~IAudioOutput() = default;
virtual bool Initialize() = 0;
virtual void Shutdown() = 0;
virtual bool Write(const int16_t* samples, size_t sample_count) = 0;
virtual void SetVolume(uint8_t volume_percent) = 0;
virtual uint8_t VolumePercent() const = 0;
virtual uint32_t SampleRate() const = 0;
};
} // namespace borla

View File

@@ -0,0 +1,483 @@
#include "audio/capture_pipeline.h"
#include "diagnostics/audio_tap.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/idf_additions.h>
#include <algorithm>
#include <cstring>
#include <cstdint>
namespace borla {
namespace {
constexpr const char* kTag = "CapturePipeline2";
constexpr uint32_t kOpusBitrate = 24000;
} // namespace
CapturePipeline::CapturePipeline(IAudioInput& input)
: input_(input)
{
}
CapturePipeline::~CapturePipeline()
{
Stop();
heap_caps_free(hardware_pcm_);
heap_caps_free(raw_protocol_pcm_);
heap_caps_free(processed_protocol_pcm_);
heap_caps_free(encoded_);
}
bool CapturePipeline::Initialize()
{
if (initialized_) {
return true;
}
if (input_.InputSampleRate() != kHardwareSampleRate
|| !encoder_.Initialize(kProtocolSampleRate, 1, kOpusBitrate)) {
ESP_LOGE(kTag, "input rate/encoder initialization failed");
return false;
}
// Internal RAM: these four are touched several times per frame by the
// resampler, the AEC and the encoder, and together they are only ~7 KB.
// The bulk storage that genuinely belongs in PSRAM is encode_slots_ below,
// which is written and read once per frame as a straight memcpy.
hardware_pcm_ = static_cast<int16_t*>(
//heap_caps_calloc(Pcm24kTo16kConverter::kInputSamples, sizeof(int16_t),
heap_caps_calloc(Pcm48kTo16kConverter::kInputSamples, sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));//2026-9-3 ckkj debug :wifi start fail
//MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
raw_protocol_pcm_ = static_cast<int16_t*>(
//heap_caps_calloc(Pcm24kTo16kConverter::kOutputSamples, sizeof(int16_t),
//MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT));
heap_caps_calloc(Pcm48kTo16kConverter::kOutputSamples, sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));//2026-9-3 ckkj debug :wifi start fail
processed_protocol_pcm_ = static_cast<int16_t*>(
//heap_caps_calloc(Pcm24kTo16kConverter::kOutputSamples, sizeof(int16_t),
heap_caps_calloc(Pcm48kTo16kConverter::kOutputSamples, sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
encoded_ = static_cast<uint8_t*>(
heap_caps_calloc(kBinaryAudioMaximumUplinkOpusBytes, sizeof(uint8_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
encode_slots_ = static_cast<int16_t*>(
//heap_caps_calloc(kEncodeSlots * Pcm24kTo16kConverter::kOutputSamples,
heap_caps_calloc(kEncodeSlots * Pcm48kTo16kConverter::kOutputSamples,
sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
stopped_signal_ = xSemaphoreCreateBinaryStatic(&stopped_signal_storage_);
encoder_stopped_signal_ =
xSemaphoreCreateBinaryStatic(&encoder_stopped_signal_storage_);
encode_ready_ = xQueueCreate(kEncodeSlots, sizeof(uint8_t));
encode_free_ = xQueueCreate(kEncodeSlots, sizeof(uint8_t));
if (hardware_pcm_ == nullptr || raw_protocol_pcm_ == nullptr
|| processed_protocol_pcm_ == nullptr
|| encoded_ == nullptr || stopped_signal_ == nullptr
|| encode_slots_ == nullptr || encode_ready_ == nullptr
|| encode_free_ == nullptr || encoder_stopped_signal_ == nullptr) {
ESP_LOGE(kTag, "capture buffers/signal allocation failed");
return false;
}
initialized_ = true;
ESP_LOGI(kTag,
"initialized hardware=48k protocol=16k frame=60ms bitrate=%lu",
static_cast<unsigned long>(kOpusBitrate));
return true;
}
// bool CapturePipeline::Start()
// {
// if (running_.load()) {
// return true;
// }
// if (!initialized_ && !Initialize()) {
// return false;
// }
// xSemaphoreTake(stopped_signal_, 0);
// xSemaphoreTake(encoder_stopped_signal_, 0);
// xQueueReset(encode_ready_);
// xQueueReset(encode_free_);
// for (uint8_t slot = 0; slot < kEncodeSlots; ++slot) {
// xQueueSend(encode_free_, &slot, 0);
// }
// running_.store(true);
// // Plain xTaskCreate: the stack comes from the internal heap and goes back
// // to it on Stop(), which is what BLE provisioning relies on when it
// // releases the audio engine to make room for the WiFi driver.
// const BaseType_t result
// = xTaskCreatePinnedToCore(&CapturePipeline::TaskEntry,
// "capture2", task_stack_budget::kCaptureBytes, this,
// task_priority::kCaptureLoop, &task_, 0);
// if (result != pdPASS) {
// running_.store(false);
// return false;
// }
// return true;
// }
bool CapturePipeline::Start()
{
if (running_.load()) {
return true;
}
if (!initialized_ && !Initialize()) {
return false;
}
xSemaphoreTake(stopped_signal_, 0);
xSemaphoreTake(encoder_stopped_signal_, 0);
xQueueReset(encode_ready_);
xQueueReset(encode_free_);
for (uint8_t slot = 0; slot < kEncodeSlots; ++slot) {
xQueueSend(encode_free_, &slot, 0);
}
running_.store(true);
// Plain xTaskCreate: the stack comes from the internal heap and goes back
// to it on Stop(), which is what BLE provisioning relies on when it
// releases the audio engine to make room for the WiFi driver.
const BaseType_t result
= xTaskCreatePinnedToCore(&CapturePipeline::TaskEntry,
"capture2", task_stack_budget::kCaptureBytes,
this,
task_priority::kCaptureLoop, &task_, 0);
if (result != pdPASS) {
running_.store(false);
task_ = nullptr;
ESP_LOGE(kTag, "capture task creation failed");
return false;
}
// Core 1: capture is pinned to core 0, so this is real parallelism.
const BaseType_t encoder_result
= xTaskCreatePinnedToCoreWithCaps(&CapturePipeline::EncoderTaskEntry,
"capture_enc2", task_stack_budget::kCaptureEncoderBytes, this,
task_priority::kAudioCodec, &encoder_task_, 1,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (encoder_result != pdPASS) {
running_.store(false);
encoder_task_ = nullptr;
// The capture task above was already created; without this it would
// park itself in vTaskSuspend forever and strand its internal-RAM
// stack — on the pool this whole exercise is trying to protect.
if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "capture task stop timed out");
}
vTaskDelete(task_);
task_ = nullptr;
ESP_LOGE(kTag, "capture encoder task creation failed");
return false;
}
ESP_LOGI(kTag, "task started stack_bytes=%u memory=internal prio=%u",
static_cast<unsigned>(task_stack_budget::kCaptureBytes),
static_cast<unsigned>(task_priority::kCaptureLoop));
return true;
}
void CapturePipeline::Stop()
{
if (!running_.exchange(false)) {
return;
}
policy_.store(AudioPolicy::kOff);
if (task_ != nullptr) {
if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "capture task stop timed out");
}
vTaskDelete(task_);
task_ = nullptr;
}
if (encoder_task_ != nullptr) {
if (xSemaphoreTake(
encoder_stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "capture encoder task stop timed out");
}
vTaskDeleteWithCaps(encoder_task_);
encoder_task_ = nullptr;
}
IEncodedAudioSink* sink = sink_.load();
if (sink != nullptr) {
sink->FlushEncodedAudio();
}
}
void CapturePipeline::SetSink(IEncodedAudioSink* sink) { sink_.store(sink); }
void CapturePipeline::SetAudioTap(AudioTap* tap)
{
audio_tap_.store(tap, std::memory_order_release);
}
void CapturePipeline::SetProcessor(IVoiceFrameProcessor* processor)
{
processor_.store(processor);
}
void CapturePipeline::ApplyPolicy(AudioPolicy policy)
{
const AudioPolicy previous = policy_.exchange(policy);
IVoiceFrameProcessor* processor = processor_.load();
if (processor != nullptr) {
processor->ApplyPolicy(policy);
}
if (CaptureEnabled(previous) && !CaptureEnabled(policy)) {
// The encoder state must be reset by the encoder task itself, not
// here: this runs on the application task while RunEncoder may be in
// the middle of encoder_.Encode() on core 1, and libopus state is not
// reentrant — a concurrent Reset() tears the state mid-frame. Every
// conversation turn ends by leaving a capture policy, so the race was
// armed constantly.
encoder_reset_pending_.store(true);
IEncodedAudioSink* sink = sink_.load();
if (sink != nullptr) {
sink->FlushEncodedAudio();
}
}
// Debug: the engine's one-line summary already reports every change.
ESP_LOGD(kTag, "policy=%s capture=%d", ToString(policy),
CaptureEnabled(policy) ? 1 : 0);
}
CaptureMetrics CapturePipeline::Metrics() const
{
portENTER_CRITICAL(&metrics_lock_);
const CaptureMetrics snapshot = metrics_;
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
void CapturePipeline::TaskEntry(void* context)
{
static_cast<CapturePipeline*>(context)->Run();
}
[[noreturn]] void CapturePipeline::Run()
{
ESP_LOGI(kTag, "capture owner task started");
while (running_.load()) {
const AudioPolicy policy = policy_.load();
if (!InputEnabled(policy)) {
vTaskDelay(pdMS_TO_TICKS(20));
continue;
}
const uint64_t read_start_us =
static_cast<uint64_t>(esp_timer_get_time());
if (!input_.Read(
//hardware_pcm_, Pcm24kTo16kConverter::kInputSamples, 100)) {
hardware_pcm_, Pcm48kTo16kConverter::kInputSamples, 100)) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.read_failures++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
const uint64_t convert_start_us =
static_cast<uint64_t>(esp_timer_get_time());
portENTER_CRITICAL(&metrics_lock_);
metrics_.frames_read++;
portEXIT_CRITICAL(&metrics_lock_);
if (!converter_.Convert(hardware_pcm_,
// Pcm24kTo16kConverter::kInputSamples, raw_protocol_pcm_,
// Pcm24kTo16kConverter::kOutputSamples)) {
Pcm48kTo16kConverter::kInputSamples, raw_protocol_pcm_,
Pcm48kTo16kConverter::kOutputSamples)) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.encode_failures++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
const uint64_t process_start_us =
static_cast<uint64_t>(esp_timer_get_time());
IVoiceFrameProcessor* processor = processor_.load();
const bool frame_passed = processor == nullptr
|| processor->Process(policy, raw_protocol_pcm_,
//Pcm24kTo16kConverter::kOutputSamples,
Pcm48kTo16kConverter::kOutputSamples,
processed_protocol_pcm_,
//Pcm24kTo16kConverter::kOutputSamples);
Pcm48kTo16kConverter::kOutputSamples);
const int16_t* upload_pcm = processor != nullptr
? processed_protocol_pcm_
: raw_protocol_pcm_;
// Server's-ear channel: exactly the PCM that goes to the encoder, or
// silence when this frame is suppressed/not uplinked — so listening
// to uplink.wav answers "what did the server hear at second N".
if (AudioTap* tap =
audio_tap_.load(std::memory_order_acquire)) {
const bool uplinked = frame_passed && CaptureEnabled(policy);
tap->PushUplink(uplinked ? upload_pcm : nullptr,
//Pcm24kTo16kConverter::kOutputSamples);
Pcm48kTo16kConverter::kOutputSamples);
}
if (!frame_passed) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.encode_failures++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
if (!CaptureEnabled(policy)) {
continue;
}
const uint64_t handoff_start_us =
static_cast<uint64_t>(esp_timer_get_time());
// Hand the frame to the encoder task instead of encoding here. A full
// free queue means the encoder is behind; dropping the newest frame is
// better than stalling capture, because a stalled capture loses the
// microphone stream itself and with it the AEC alignment.
uint8_t slot = 0;
if (xQueueReceive(encode_free_, &slot, 0) != pdTRUE) {
portENTER_CRITICAL(&metrics_lock_);
metrics_.backpressure_drops++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
std::memcpy(
//encode_slots_ + slot * Pcm24kTo16kConverter::kOutputSamples,
encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples,
upload_pcm,
//Pcm24kTo16kConverter::kOutputSamples * sizeof(int16_t));
Pcm48kTo16kConverter::kOutputSamples * sizeof(int16_t));
if (xQueueSend(encode_ready_, &slot, 0) != pdTRUE) {
xQueueSend(encode_free_, &slot, 0);
portENTER_CRITICAL(&metrics_lock_);
metrics_.backpressure_drops++;
portEXIT_CRITICAL(&metrics_lock_);
continue;
}
const uint64_t handoff_end_us =
static_cast<uint64_t>(esp_timer_get_time());
RecordTimings(
static_cast<uint32_t>(convert_start_us - read_start_us),
static_cast<uint32_t>(process_start_us - convert_start_us),
static_cast<uint32_t>(handoff_start_us - process_start_us),
0,
static_cast<uint32_t>(handoff_end_us - handoff_start_us));
}
xSemaphoreGive(stopped_signal_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void CapturePipeline::EncoderTaskEntry(void* context)
{
static_cast<CapturePipeline*>(context)->RunEncoder();
}
[[noreturn]] void CapturePipeline::RunEncoder()
{
ESP_LOGI(kTag, "capture encoder task started stack_bytes=%u memory=PSRAM",
static_cast<unsigned>(task_stack_budget::kCaptureEncoderBytes));
while (running_.load()) {
if (encoder_reset_pending_.exchange(false)) {
encoder_.Reset();
}
uint8_t slot = 0;
if (xQueueReceive(encode_ready_, &slot, pdMS_TO_TICKS(100))
!= pdTRUE) {
continue;
}
const int16_t* pcm =
//encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples;
encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples;
const uint64_t encode_start_us =
static_cast<uint64_t>(esp_timer_get_time());
size_t encoded_size = 0;
const bool encoded = encoder_.Encode(pcm,
//Pcm24kTo16kConverter::kOutputSamples, encoded_,
Pcm48kTo16kConverter::kOutputSamples, encoded_,
kBinaryAudioMaximumUplinkOpusBytes, &encoded_size);
const uint64_t encode_end_us =
static_cast<uint64_t>(esp_timer_get_time());
bool sent = false;
if (encoded) {
IEncodedAudioSink* sink = sink_.load();
sent = sink != nullptr
&& sink->SubmitEncodedAudio(encoded_, encoded_size);
}
const uint64_t submit_end_us =
static_cast<uint64_t>(esp_timer_get_time());
xQueueSend(encode_free_, &slot, 0);
portENTER_CRITICAL(&metrics_lock_);
if (!encoded) {
metrics_.encode_failures++;
} else {
metrics_.frames_encoded++;
metrics_.maximum_encoded_bytes
= std::max(metrics_.maximum_encoded_bytes,
static_cast<uint32_t>(encoded_size));
if (sent) {
metrics_.frames_sent++;
} else {
metrics_.backpressure_drops++;
}
}
timings_.encode_us += encode_end_us - encode_start_us;
timings_.encode_us_max = std::max(timings_.encode_us_max,
static_cast<uint32_t>(encode_end_us - encode_start_us));
timings_.submit_us += submit_end_us - encode_end_us;
portEXIT_CRITICAL(&metrics_lock_);
// One tick between frames so IDLE1 gets runtime while the slot queue
// is backlogged. A single opus_encode() call cannot yield internally,
// and when frames queue up the xQueueReceive above returns instantly,
// so without this the loop monopolises core 1 for as long as the
// backlog lasts and the task watchdog fires — every backtrace it
// printed ended inside silk_encode. Costs 1 ms per 60 ms frame.
vTaskDelay(1);
}
xSemaphoreGive(encoder_stopped_signal_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void CapturePipeline::RecordTimings(uint32_t read_us, uint32_t convert_us,
uint32_t process_us, uint32_t encode_us, uint32_t submit_us)
{
portENTER_CRITICAL(&metrics_lock_);
timings_.frames++;
timings_.read_us += read_us;
timings_.convert_us += convert_us;
timings_.process_us += process_us;
timings_.encode_us += encode_us;
timings_.submit_us += submit_us;
timings_.read_us_max = std::max(timings_.read_us_max, read_us);
timings_.process_us_max = std::max(timings_.process_us_max, process_us);
timings_.encode_us_max = std::max(timings_.encode_us_max, encode_us);
timings_.submit_us_max = std::max(timings_.submit_us_max, submit_us);
portEXIT_CRITICAL(&metrics_lock_);
}
CaptureTimings CapturePipeline::ConsumeTimings()
{
portENTER_CRITICAL(&metrics_lock_);
const CaptureTimings snapshot = timings_;
timings_ = CaptureTimings{};
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
bool CapturePipeline::CaptureEnabled(AudioPolicy policy) const
{
return policy == AudioPolicy::kConversationCapture
|| policy == AudioPolicy::kBargeInDuplex
|| policy == AudioPolicy::kCallDuplex;
}
bool CapturePipeline::InputEnabled(AudioPolicy policy) const
{
return policy == AudioPolicy::kWakeWordOnly ||
policy == AudioPolicy::kWakeWordDuplex ||
CaptureEnabled(policy);
}
} // namespace borla

View File

@@ -0,0 +1,133 @@
#pragma once
#include "audio/audio_input.h"
#include "audio/encoded_audio_sink.h"
#include "audio/opus_frame_encoder.h"
#include "audio/pcm_rate_converter.h"
#include "audio/voice_frame_processor.h"
#include "core/runtime_state.h"
#include "core/task_stack_budget.h"
#include <atomic>
#include <cstddef>
#include <cstdint>
namespace borla {
class AudioTap;
}
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
struct CaptureMetrics {
uint32_t frames_read = 0;
uint32_t frames_encoded = 0;
uint32_t frames_sent = 0;
uint32_t read_failures = 0;
uint32_t encode_failures = 0;
uint32_t backpressure_drops = 0;
uint32_t maximum_encoded_bytes = 0;
};
// Per-stage cost of the capture loop, accumulated by the capture task and
// drained by diagnostics. Added because the loop was measured at 94.6 ms per
// frame against a 60 ms budget while duplex was active — over budget means the
// I2S RX DMA overflows, frames are lost, and the AEC's microphone/reference
// alignment drifts, which is what capped echo cancellation at 13 dB and let the
// device's own TTS reach the server's ASR. Which stage is responsible was pure
// guesswork without these numbers.
struct CaptureTimings {
uint32_t frames = 0;
uint64_t read_us = 0;
uint64_t convert_us = 0;
uint64_t process_us = 0;
uint64_t encode_us = 0;
uint64_t submit_us = 0;
uint32_t read_us_max = 0;
uint32_t process_us_max = 0;
uint32_t encode_us_max = 0;
uint32_t submit_us_max = 0;
};
class CapturePipeline final {
public:
static constexpr uint32_t kHardwareSampleRate = 48000;//24000;
static constexpr uint32_t kProtocolSampleRate = 16000;
static constexpr uint32_t kFrameDurationMs = 60;
explicit CapturePipeline(IAudioInput& input);
~CapturePipeline();
bool Initialize();
bool Start();
void Stop();
void SetSink(IEncodedAudioSink* sink);
void SetProcessor(IVoiceFrameProcessor* processor);
// Debug recorder for the "what does the server actually hear" channel.
void SetAudioTap(AudioTap* tap);
void ApplyPolicy(AudioPolicy policy);
CaptureMetrics Metrics() const;
CaptureTimings ConsumeTimings();
private:
// Opus encoding costs ~42 ms per 60 ms frame on this board (measured), and
// it used to run inline on the capture task together with the ~56 ms of
// AEC + wake-word work. Total ~104 ms against a 60 ms budget meant the I2S
// RX DMA overflowed every frame: audio was lost, the AEC's microphone and
// reference streams drifted apart, echo cancellation collapsed to ~9 dB and
// the device's own TTS reached the server's ASR — it answered itself.
//
// The previous firmware never had this problem because encoding lived on a
// separate task (audio_service.cc "Task 3: Opus 编码/解码"). Same split
// here, pinned to the other core so it genuinely runs in parallel with
// capture rather than merely interleaving with it.
static constexpr size_t kEncodeSlots = 4;
static void TaskEntry(void* context);
[[noreturn]] void Run();
static void EncoderTaskEntry(void* context);
[[noreturn]] void RunEncoder();
void RecordTimings(uint32_t read_us, uint32_t convert_us,
uint32_t process_us, uint32_t encode_us, uint32_t submit_us);
bool CaptureEnabled(AudioPolicy policy) const;
bool InputEnabled(AudioPolicy policy) const;
IAudioInput& input_;
std::atomic<IEncodedAudioSink*> sink_ { nullptr };
std::atomic<IVoiceFrameProcessor*> processor_ { nullptr };
std::atomic<AudioTap*> audio_tap_ { nullptr };
std::atomic<AudioPolicy> policy_ { AudioPolicy::kOff };
OpusFrameEncoder encoder_;
//Pcm24kTo16kConverter converter_;
Pcm48kTo16kConverter converter_;
// Set by ApplyPolicy when leaving a capture policy; consumed by the
// encoder task, which is the only task allowed to touch encoder_ state.
std::atomic<bool> encoder_reset_pending_ { false };
int16_t* encode_slots_ = nullptr;
QueueHandle_t encode_ready_ = nullptr;
QueueHandle_t encode_free_ = nullptr;
TaskHandle_t encoder_task_ = nullptr;
SemaphoreHandle_t encoder_stopped_signal_ = nullptr;
StaticSemaphore_t encoder_stopped_signal_storage_ {};
int16_t* hardware_pcm_ = nullptr;
int16_t* raw_protocol_pcm_ = nullptr;
int16_t* processed_protocol_pcm_ = nullptr;
uint8_t* encoded_ = nullptr;
mutable portMUX_TYPE metrics_lock_ = portMUX_INITIALIZER_UNLOCKED;
CaptureMetrics metrics_ {};
CaptureTimings timings_ {};
TaskHandle_t task_ = nullptr;
SemaphoreHandle_t stopped_signal_ = nullptr;
StaticSemaphore_t stopped_signal_storage_ {};
bool initialized_ = false;
std::atomic<bool> running_ { false };
};
} // namespace borla

View File

@@ -0,0 +1,74 @@
#pragma once
#include "protocol/binary_audio_protocol.h"
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
namespace borla {
// Holds the small number of downlink frames that can arrive after the
// protocol has announced a TTS session but before Application has applied the
// corresponding BeginRemotePlayback effect. The object is allocated in
// PSRAM by EspAudioEngine so the fixed frame storage does not consume
// internal DRAM.
class DownlinkPrerollBuffer final {
public:
static constexpr size_t kCapacity = 8;
bool Push(
uint32_t session_id,
const uint8_t* data,
size_t size)
{
if (session_id == 0 || data == nullptr || size == 0 ||
size > kBinaryAudioMaximumOpusBytes) {
return false;
}
if (session_id_ != session_id) {
Reset(session_id);
}
if (frame_count_ >= frames_.size()) {
return false;
}
Frame& frame = frames_[frame_count_++];
frame.size = static_cast<uint16_t>(size);
std::memcpy(frame.payload.data(), data, size);
return true;
}
void Reset(uint32_t session_id = 0)
{
session_id_ = session_id;
frame_count_ = 0;
}
uint32_t session_id() const { return session_id_; }
size_t frame_count() const { return frame_count_; }
const uint8_t* FrameData(size_t index) const
{
return index < frame_count_
? frames_[index].payload.data()
: nullptr;
}
size_t FrameSize(size_t index) const
{
return index < frame_count_ ? frames_[index].size : 0;
}
private:
struct Frame {
uint16_t size = 0;
std::array<uint8_t, kBinaryAudioMaximumOpusBytes> payload{};
};
std::array<Frame, kCapacity> frames_{};
uint32_t session_id_ = 0;
size_t frame_count_ = 0;
};
} // namespace borla

View File

@@ -0,0 +1,143 @@
#include "audio/embedded_prompt_catalog.h"
#include "audio_prompts_data.h"
#include <cstring>
namespace borla {
namespace {
const char* AssetGroup(LocalPrompt prompt)
{
switch (prompt) {
case LocalPrompt::kActivationDevice:
return "activation_device";
case LocalPrompt::kDeviceAlreadyBound:
return "device_already_bound";
case LocalPrompt::kServerError:
return "server_error";
case LocalPrompt::kAlarmWake:
return "alarm_wake";
case LocalPrompt::kAlarmSet:
return "alarm_set";
case LocalPrompt::kNoNetwork:
return "no_network";
case LocalPrompt::kProvisioning:
return "wifi_config";
case LocalPrompt::kWakeResponse:
return "wake_response";
case LocalPrompt::kStoryExpired:
return "story_expired";
case LocalPrompt::kIdleCheck:
return "idle_check";
case LocalPrompt::kIdleGoodbye:
return "idle_goodbye";
case LocalPrompt::kSnoreLight:
return "snore_light";
case LocalPrompt::kWifiSuccess:
return "wifi_success";
case LocalPrompt::kWelcome:
return "welcome";
case LocalPrompt::kShutdown:
return "shutdown";
case LocalPrompt::kBoot:
return "boot";
case LocalPrompt::kError:
return "error";
case LocalPrompt::kLowBattery20:
return "low_battery_20";
case LocalPrompt::kLowBattery10:
return "low_battery_10";
case LocalPrompt::kNet4gBootOn:
return "net4g_boot_on";
case LocalPrompt::kNet4gOff:
return "net4g_off";
case LocalPrompt::kNet4gOn:
return "net4g_on";
case LocalPrompt::kNet4gNoWifi:
return "net4g_no_wifi";
case LocalPrompt::kCallWait:
// Explicit compatibility fallbacks until dedicated call assets exist.
return "wake_response";
case LocalPrompt::kCallRing:
return "alarm_wake";
case LocalPrompt::kCallConnected:
return "wifi_success";
case LocalPrompt::kCallEnded:
return "error";
case LocalPrompt::kDigit0:
return "digit_0";
case LocalPrompt::kDigit1:
return "digit_1";
case LocalPrompt::kDigit2:
return "digit_2";
case LocalPrompt::kDigit3:
return "digit_3";
case LocalPrompt::kDigit4:
return "digit_4";
case LocalPrompt::kDigit5:
return "digit_5";
case LocalPrompt::kDigit6:
return "digit_6";
case LocalPrompt::kDigit7:
return "digit_7";
case LocalPrompt::kDigit8:
return "digit_8";
case LocalPrompt::kDigit9:
return "digit_9";
}
return "";
}
} // namespace
size_t EmbeddedPromptCatalog::Count(LocalPrompt prompt)
{
const char* group = AssetGroup(prompt);
size_t count = 0;
for (size_t index = 0;
index < generated_prompts::kPromptBlobCount;
++index) {
if (std::strcmp(
generated_prompts::kPromptBlobs[index].group,
group) == 0) {
count++;
}
}
return count;
}
bool EmbeddedPromptCatalog::Select(
LocalPrompt prompt,
uint32_t selector,
EmbeddedPromptBlob* blob)
{
if (blob == nullptr) {
return false;
}
const char* group = AssetGroup(prompt);
const size_t count = Count(prompt);
if (count == 0) {
return false;
}
size_t desired = selector % count;
for (size_t index = 0;
index < generated_prompts::kPromptBlobCount;
++index) {
const auto& candidate =
generated_prompts::kPromptBlobs[index];
if (std::strcmp(candidate.group, group) != 0) {
continue;
}
if (desired-- == 0) {
blob->data = candidate.data;
blob->size = candidate.size;
blob->filename = candidate.filename;
return true;
}
}
return false;
}
} // namespace borla

View File

@@ -0,0 +1,25 @@
#pragma once
#include "core/playback_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
struct EmbeddedPromptBlob {
const uint8_t* data = nullptr;
size_t size = 0;
const char* filename = nullptr;
};
class EmbeddedPromptCatalog final {
public:
static bool Select(
LocalPrompt prompt,
uint32_t selector,
EmbeddedPromptBlob* blob);
static size_t Count(LocalPrompt prompt);
};
} // namespace borla

View File

@@ -0,0 +1,17 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class IEncodedAudioSink {
public:
virtual ~IEncodedAudioSink() = default;
virtual bool SubmitEncodedAudio(
const uint8_t* data,
size_t size) = 0;
virtual void FlushEncodedAudio() = 0;
};
} // namespace borla

View File

@@ -0,0 +1,588 @@
#include "audio/local_prompt_player.h"
#include "audio/packed_opus_reader.h"
#include "core/task_stack_budget.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_random.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/idf_additions.h>
#include <freertos/task.h>
#include <algorithm>
#include <array>
#include <cmath>
#include <new>
namespace borla {
namespace {
constexpr const char* kTag = "LocalPromptPlayer2";
constexpr float kPi = 3.14159265358979323846f;
constexpr uint32_t kQueueBackpressureTimeoutMs = 1500;
constexpr uint16_t kActivationIntroGapMs = 1000;
constexpr uint16_t kActivationDigitGapMs = 150;
constexpr std::array<
int16_t,
PlaybackPipeline::kSamplesPerFrame> kSilence{};
struct ToneSegment {
uint16_t frequency_hz;
uint16_t duration_ms;
uint8_t amplitude_percent;
};
constexpr std::array<ToneSegment, 2> kBootFallback = {{
{523, 150, 24},
{659, 200, 30},
}};
constexpr std::array<ToneSegment, 3> kProvisioningFallback = {{
{440, 100, 24},
{554, 100, 26},
{659, 150, 30},
}};
constexpr std::array<ToneSegment, 3> kErrorFallback = {{
{220, 200, 28},
{0, 80, 0},
{220, 200, 28},
}};
constexpr std::array<ToneSegment, 2> kShutdownFallback = {{
{659, 150, 24},
{262, 250, 20},
}};
uint64_t NowMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace
struct LocalPromptPlayer::ProducerContext {
LocalPromptPlayer* player = nullptr;
PlaybackSessionId session_id = 0;
std::array<
EmbeddedPromptBlob,
kMaxLocalPromptSequenceItems> blobs{};
std::array<
LocalPrompt,
kMaxLocalPromptSequenceItems> prompts{};
size_t count = 0;
bool activation_sequence = false;
};
LocalPromptPlayer::LocalPromptPlayer(PlaybackPipeline& pipeline)
: pipeline_(pipeline)
{
}
LocalPromptPlayer::~LocalPromptPlayer()
{
producer_running_.store(false, std::memory_order_release);
if (producer_task_ != nullptr) {
if (xSemaphoreTake(
producer_stopped_, pdMS_TO_TICKS(2000)) != pdTRUE) {
ESP_LOGE(kTag, "prompt worker stop timed out");
}
vTaskDeleteWithCaps(producer_task_);
producer_task_ = nullptr;
}
if (producer_queue_ != nullptr) {
ProducerContext* pending = nullptr;
while (xQueueReceive(producer_queue_, &pending, 0) == pdTRUE) {
DestroyProducerContext(pending);
}
}
if (pcm_buffer_ != nullptr) {
heap_caps_free(pcm_buffer_);
}
if (context_pool_ != nullptr) {
heap_caps_free(context_pool_);
context_pool_ = nullptr;
}
}
bool LocalPromptPlayer::Initialize()
{
if (pcm_buffer_ != nullptr && producer_task_ != nullptr) {
return true;
}
if (pcm_buffer_ == nullptr) {
pcm_buffer_ = static_cast<int16_t*>(heap_caps_calloc(
PlaybackPipeline::kSamplesPerFrame,
sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (pcm_buffer_ == nullptr) {
ESP_LOGE(kTag, "failed to allocate PSRAM fallback buffer");
return false;
}
if (producer_queue_ == nullptr) {
producer_queue_ = xQueueCreateStatic(
kProducerQueueDepth,
sizeof(ProducerContext*),
producer_queue_bytes_.data(),
&producer_queue_storage_);
}
if (producer_stopped_ == nullptr) {
producer_stopped_ = xSemaphoreCreateBinaryStatic(
&producer_stopped_storage_);
}
// if (producer_queue_ == nullptr || producer_stopped_ == nullptr) {
// ESP_LOGE(kTag, "failed to create prompt worker controls");
// return false;
// }
if (context_pool_ == nullptr) {
context_pool_ = static_cast<ProducerContext*>(
heap_caps_calloc(
kProducerQueueDepth,
sizeof(ProducerContext),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (free_slots_ == nullptr) {
free_slots_ = xQueueCreateStatic(
kProducerQueueDepth,
sizeof(uint8_t),
free_slots_bytes_.data(),
&free_slots_storage_);
if (free_slots_ != nullptr) {
for (uint8_t index = 0; index < kProducerQueueDepth; ++index) {
xQueueSend(free_slots_, &index, 0);
}
}
}
if (producer_queue_ == nullptr || producer_stopped_ == nullptr ||
context_pool_ == nullptr || free_slots_ == nullptr) {
ESP_LOGE(kTag, "failed to create prompt worker controls or pool");
return false;
}/////////
xSemaphoreTake(producer_stopped_, 0);
producer_running_.store(true, std::memory_order_release);
const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
&LocalPromptPlayer::ProducerTaskEntry,
"prompt_producer",
task_stack_budget::kLocalPromptProducerBytes,
this,
4,
&producer_task_,
0,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (created != pdPASS) {
producer_running_.store(false, std::memory_order_release);
producer_task_ = nullptr;
ESP_LOGE(kTag, "failed to create PSRAM prompt worker");
return false;
}
ESP_LOGI(kTag, "worker started stack_bytes=%u memory=PSRAM queue=%u",
static_cast<unsigned>(
task_stack_budget::kLocalPromptProducerBytes),
static_cast<unsigned>(kProducerQueueDepth));
return true;
}
PlaybackSessionId LocalPromptPlayer::Play(
LocalPrompt prompt,
PlaybackPriority priority,
int16_t selector)
{
EmbeddedPromptBlob blob;
const uint32_t selected =
selector < 0
? esp_random()
: static_cast<uint32_t>(selector);
if (!EmbeddedPromptCatalog::Select(prompt, selected, &blob)) {
ESP_LOGW(kTag, "no embedded asset prompt=%s; using tone fallback",
ToString(prompt));
return PlayProceduralFallback(prompt, priority);
}
auto* context = AllocateProducerContext();
if (context == nullptr) {
ESP_LOGE(kTag, "failed to allocate PSRAM prompt context");
return 0;
}
context->player = this;
context->blobs[0] = blob;
context->prompts[0] = prompt;
context->count = 1;
return StartProducer(context, priority);
}
PlaybackSessionId LocalPromptPlayer::PlaySequence(
const LocalPromptSequence& sequence,
PlaybackPriority priority)
{
if (sequence.Empty() ||
sequence.count > kMaxLocalPromptSequenceItems) {
return 0;
}
auto* context = AllocateProducerContext();
if (context == nullptr) {
return 0;
}
context->player = this;
context->activation_sequence =
sequence.Contains(LocalPrompt::kActivationDevice);
for (size_t index = 0; index < sequence.count; ++index) {
const LocalPromptSequenceItem& item = sequence.items[index];
const uint32_t selected = item.selector < 0
? esp_random()
: static_cast<uint32_t>(item.selector);
if (!EmbeddedPromptCatalog::Select(
item.prompt,
selected,
&context->blobs[context->count])) {
ESP_LOGW(kTag,
"sequence asset missing prompt=%s",
ToString(item.prompt));
DestroyProducerContext(context);
return 0;
}
context->prompts[context->count] = item.prompt;
context->count++;
}
return StartProducer(context, priority);
}
PlaybackSessionId LocalPromptPlayer::StartProducer(
ProducerContext* context,
PlaybackPriority priority)
{
const PlaybackStartResult start = pipeline_.StartSession(
PlaybackSource::kLocalPrompt, priority);
if (start.status != PlaybackStartStatus::kStarted) {
ESP_LOGW(kTag, "prompt producer rejected status=%s",
ToString(start.status));
DestroyProducerContext(context);
return start.status == PlaybackStartStatus::kAlreadyActive
? start.session_id
: 0;
}
context->session_id = start.session_id;
const size_t item_count = context->count;
const char* first_filename = context->blobs[0].filename;
if (!producer_running_.load(std::memory_order_acquire) ||
xQueueSend(producer_queue_, &context, 0) != pdTRUE) {
DestroyProducerContext(context);
pipeline_.Cancel(start.session_id);
ESP_LOGE(kTag, "prompt worker unavailable or queue full");
return 0;
}
ESP_LOGI(kTag,
"prompt producer started items=%u first=%s session=%lu",
static_cast<unsigned>(item_count),
first_filename,
static_cast<unsigned long>(start.session_id));
return start.session_id;
}
void LocalPromptPlayer::ProducerTaskEntry(void* raw_context)
{
static_cast<LocalPromptPlayer*>(raw_context)->RunProducer();
}
LocalPromptPlayer::ProducerContext*
LocalPromptPlayer::AllocateProducerContext()
{
// void* storage = heap_caps_calloc(
// 1,
// sizeof(ProducerContext),
// MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
// return storage == nullptr
// ? nullptr
// : new (storage) ProducerContext{};///改堆分配为队列
if (context_pool_ == nullptr || free_slots_ == nullptr) {
return nullptr;
}
uint8_t index = 0;
if (xQueueReceive(free_slots_, &index, 0) != pdTRUE) {
return nullptr;
}
if (index >= kProducerQueueDepth) {
return nullptr;
}
ProducerContext* context = &context_pool_[index];
new (context) ProducerContext{};
return context;
}
void LocalPromptPlayer::DestroyProducerContext(
ProducerContext* context)
{
// if (context == nullptr) {
// return;
// }
if (context == nullptr || context_pool_ == nullptr ||
free_slots_ == nullptr) {
return;
}
const uint8_t index = static_cast<uint8_t>(
context - context_pool_);
if (index >= kProducerQueueDepth) {
return;
}
context->~ProducerContext();
//heap_caps_free(context);
xQueueSend(free_slots_, &index, 0);
}
void LocalPromptPlayer::RunProducer()
{
while (producer_running_.load(std::memory_order_acquire)) {
ProducerContext* context = nullptr;
if (xQueueReceive(
producer_queue_,
&context,
pdMS_TO_TICKS(100)) != pdTRUE) {
continue;
}
if (!producer_running_.load(std::memory_order_acquire)) {
DestroyProducerContext(context);
break;
}
Produce(*context);
DestroyProducerContext(context);
}
xSemaphoreGive(producer_stopped_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void LocalPromptPlayer::Produce(ProducerContext& context)
{
for (size_t index = 0; index < context.count; ++index) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(context.session_id);
return;
}
if (!SubmitEmbedded(
context.blobs[index], context.session_id)) {
return;
}
if (context.activation_sequence &&
index + 1 < context.count) {
const uint16_t gap =
context.prompts[index] ==
LocalPrompt::kActivationDevice
? kActivationIntroGapMs
: kActivationDigitGapMs;
if (!SubmitSilence(context.session_id, gap)) {
return;
}
}
}
if (!pipeline_.EndInput(context.session_id)) {
ESP_LOGW(kTag,
"prompt producer ended after preemption session=%lu",
static_cast<unsigned long>(context.session_id));
}
}
bool LocalPromptPlayer::SubmitEmbedded(
const EmbeddedPromptBlob& blob,
PlaybackSessionId session_id)
{
PackedOpusReader reader(blob.data, blob.size);
if (!reader.valid()) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag, "invalid packed prompt asset=%s", blob.filename);
return false;
}
const uint8_t* frame = nullptr;
size_t frame_size = 0;
while (reader.Next(&frame, &frame_size)) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(session_id);
return false;
}
const uint64_t wait_started = NowMs();
while (!pipeline_.SubmitOpus(session_id, frame, frame_size)) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(session_id);
return false;
}
const PlaybackSessionSnapshot current = pipeline_.Snapshot();
if (!current.active || current.id != session_id) {
ESP_LOGI(kTag,
"prompt producer preempted asset=%s session=%lu",
blob.filename,
static_cast<unsigned long>(session_id));
return false;
}
if (NowMs() - wait_started >=
kQueueBackpressureTimeoutMs) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag,
"prompt queue stalled asset=%s session=%lu",
blob.filename,
static_cast<unsigned long>(session_id));
return false;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
}
if (!reader.complete()) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag, "truncated packed prompt asset=%s", blob.filename);
return false;
}
return true;
}
bool LocalPromptPlayer::SubmitSilence(
PlaybackSessionId session_id,
uint16_t duration_ms)
{
size_t samples_remaining =
static_cast<size_t>(PlaybackPipeline::kSampleRate) *
duration_ms / 1000;
while (samples_remaining > 0) {
if (!producer_running_.load(std::memory_order_acquire)) {
pipeline_.Cancel(session_id);
return false;
}
const size_t samples = std::min(
samples_remaining,
PlaybackPipeline::kSamplesPerFrame);
const uint64_t wait_started = NowMs();
while (!pipeline_.SubmitPcm(
session_id, kSilence.data(), samples)) {
const PlaybackSessionSnapshot current = pipeline_.Snapshot();
if (!current.active || current.id != session_id) {
return false;
}
if (NowMs() - wait_started >=
kQueueBackpressureTimeoutMs) {
pipeline_.Cancel(session_id);
ESP_LOGE(kTag,
"sequence silence queue stalled session=%lu",
static_cast<unsigned long>(session_id));
return false;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
samples_remaining -= samples;
}
return true;
}
PlaybackSessionId LocalPromptPlayer::PlayProceduralFallback(
LocalPrompt prompt,
PlaybackPriority priority)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!Initialize()) {
return 0;
}
const PlaybackStartResult start = pipeline_.StartSession(
PlaybackSource::kLocalPrompt, priority);
if (start.status != PlaybackStartStatus::kStarted) {
return start.status == PlaybackStartStatus::kAlreadyActive
? start.session_id
: 0;
}
float phase = 0.0f;
const auto submit_sequence =
[this, &start, &phase](const auto& sequence) {
for (const auto& tone : sequence) {
if (!SubmitTone(
start.session_id,
tone.frequency_hz,
tone.duration_ms,
tone.amplitude_percent,
&phase)) {
return false;
}
}
return true;
};
bool submitted = false;
switch (prompt) {
case LocalPrompt::kBoot:
submitted = submit_sequence(kBootFallback);
break;
case LocalPrompt::kProvisioning:
submitted = submit_sequence(kProvisioningFallback);
break;
case LocalPrompt::kShutdown:
submitted = submit_sequence(kShutdownFallback);
break;
default:
submitted = submit_sequence(kErrorFallback);
break;
}
if (!submitted || !pipeline_.EndInput(start.session_id)) {
pipeline_.Cancel(start.session_id);
return 0;
}
return start.session_id;
}
bool LocalPromptPlayer::SubmitTone(
PlaybackSessionId session_id,
uint16_t frequency_hz,
uint16_t duration_ms,
uint8_t amplitude_percent,
float* phase)
{
const size_t total_samples =
static_cast<size_t>(PlaybackPipeline::kSampleRate) *
duration_ms / 1000;
const float amplitude =
32767.0f * static_cast<float>(amplitude_percent) / 100.0f;
const size_t fade_samples =
PlaybackPipeline::kSampleRate / 100;
size_t generated = 0;
while (generated < total_samples) {
const size_t frame_samples = std::min(
PlaybackPipeline::kSamplesPerFrame,
total_samples - generated);
for (size_t index = 0; index < frame_samples; ++index) {
const size_t absolute = generated + index;
float envelope = 1.0f;
if (absolute < fade_samples) {
envelope = static_cast<float>(absolute) /
static_cast<float>(fade_samples);
} else if (total_samples - absolute < fade_samples) {
envelope = static_cast<float>(total_samples - absolute) /
static_cast<float>(fade_samples);
}
if (frequency_hz == 0) {
pcm_buffer_[index] = 0;
} else {
pcm_buffer_[index] = static_cast<int16_t>(
amplitude * envelope * std::sin(*phase));
*phase += 2.0f * kPi *
static_cast<float>(frequency_hz) /
static_cast<float>(
PlaybackPipeline::kSampleRate);
if (*phase >= 2.0f * kPi) {
*phase -= 2.0f * kPi;
}
}
}
if (!pipeline_.SubmitPcm(
session_id, pcm_buffer_, frame_samples)) {
return false;
}
generated += frame_samples;
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,83 @@
#pragma once
#include "audio/embedded_prompt_catalog.h"
#include "audio/playback_pipeline.h"
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <mutex>
namespace borla {
class LocalPromptPlayer final {
public:
explicit LocalPromptPlayer(PlaybackPipeline& pipeline);
~LocalPromptPlayer();
bool Initialize();
PlaybackSessionId Play(
LocalPrompt prompt,
PlaybackPriority priority,
int16_t selector = -1);
PlaybackSessionId PlaySequence(
const LocalPromptSequence& sequence,
PlaybackPriority priority);
private:
struct ProducerContext;
static constexpr size_t kProducerQueueDepth = 4;
static void ProducerTaskEntry(void* context);
// static ProducerContext* AllocateProducerContext();
// static void DestroyProducerContext(ProducerContext* context);
ProducerContext* AllocateProducerContext();
void DestroyProducerContext(ProducerContext* context);
void RunProducer();
void Produce(ProducerContext& context);
bool SubmitEmbedded(
const EmbeddedPromptBlob& blob,
PlaybackSessionId session_id);
bool SubmitSilence(
PlaybackSessionId session_id,
uint16_t duration_ms);
PlaybackSessionId StartProducer(
ProducerContext* context,
PlaybackPriority priority);
PlaybackSessionId PlayProceduralFallback(
LocalPrompt prompt,
PlaybackPriority priority);
bool SubmitTone(
PlaybackSessionId session_id,
uint16_t frequency_hz,
uint16_t duration_ms,
uint8_t amplitude_percent,
float* phase);
PlaybackPipeline& pipeline_;
std::mutex mutex_;
int16_t* pcm_buffer_ = nullptr;
std::array<
uint8_t,
kProducerQueueDepth * sizeof(ProducerContext*)>
producer_queue_bytes_{};
StaticQueue_t producer_queue_storage_{};
QueueHandle_t producer_queue_ = nullptr;
StaticSemaphore_t producer_stopped_storage_{};
SemaphoreHandle_t producer_stopped_ = nullptr;
std::atomic<bool> producer_running_{false};
/////
TaskHandle_t producer_task_ = nullptr;
ProducerContext* context_pool_ = nullptr;
std::array<uint8_t, kProducerQueueDepth> free_slots_bytes_{};
StaticQueue_t free_slots_storage_{};
QueueHandle_t free_slots_ = nullptr;
};
} // namespace borla

View File

@@ -0,0 +1,107 @@
#include "audio/opus_frame_decoder.h"
#include <esp_log.h>
#include <opus.h>
namespace borla {
namespace {
constexpr const char* kTag = "OpusFrameDecoder2";
} // namespace
OpusFrameDecoder::~OpusFrameDecoder()
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
opus_decoder_destroy(decoder_);
}
}
bool OpusFrameDecoder::Initialize(
uint32_t sample_rate,
uint8_t channels)
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
return true;
}
int error = OPUS_OK;
decoder_ = opus_decoder_create(
static_cast<opus_int32>(sample_rate), channels, &error);
if (decoder_ == nullptr || error != OPUS_OK) {
ESP_LOGE(kTag, "opus decoder creation failed: %s",
opus_strerror(error));
decoder_ = nullptr;
return false;
}
channels_ = channels;
ESP_LOGI(kTag, "decoder initialized rate=%lu channels=%u",
static_cast<unsigned long>(sample_rate),
static_cast<unsigned>(channels));
return true;
}
bool OpusFrameDecoder::Decode(
const uint8_t* encoded,
size_t encoded_size,
int16_t* pcm,
size_t pcm_capacity,
size_t* decoded_samples)
{
if (pcm == nullptr || decoded_samples == nullptr ||
pcm_capacity == 0 ||
(encoded_size > 0 && encoded == nullptr)) {
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ == nullptr) {
return false;
}
const size_t capacity_per_channel = pcm_capacity / channels_;
const int decoded = opus_decode(
decoder_,
encoded,
static_cast<opus_int32>(encoded_size),
pcm,
static_cast<int>(capacity_per_channel),
0);
if (decoded < 0) {
ESP_LOGE(kTag, "decode failed: %s", opus_strerror(decoded));
return false;
}
*decoded_samples =
static_cast<size_t>(decoded) * static_cast<size_t>(channels_);
// 2026-8-28 CKKJ temp debug: log first 10 frames peak + raw Opus info
static uint32_t s_decode_seq = 0;
if (s_decode_seq < 10) {
s_decode_seq++;
int32_t peak = 0;
for (size_t i = 0; i < *decoded_samples; ++i) {
int32_t a = pcm[i] < 0 ? -pcm[i] : pcm[i];
if (a > peak) peak = a;
}
const uint8_t toc = encoded_size > 0 ? encoded[0] : 0;
ESP_LOGI(kTag, "decode seq=%u enc_size=%u toc=0x%02x decoded=%u peak=%d",
static_cast<unsigned>(s_decode_seq),
static_cast<unsigned>(encoded_size),
static_cast<unsigned>(toc),
static_cast<unsigned>(*decoded_samples),
static_cast<int>(peak));
}//
return true;
}
void OpusFrameDecoder::Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
if (decoder_ != nullptr) {
opus_decoder_ctl(decoder_, OPUS_RESET_STATE);
}
}
} // namespace borla

View File

@@ -0,0 +1,31 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <mutex>
struct OpusDecoder;
namespace borla {
class OpusFrameDecoder final {
public:
OpusFrameDecoder() = default;
~OpusFrameDecoder();
bool Initialize(uint32_t sample_rate, uint8_t channels);
bool Decode(
const uint8_t* encoded,
size_t encoded_size,
int16_t* pcm,
size_t pcm_capacity,
size_t* decoded_samples);
void Reset();
private:
std::mutex mutex_;
OpusDecoder* decoder_ = nullptr;
uint8_t channels_ = 1;
};
} // namespace borla

View File

@@ -0,0 +1,105 @@
#include "audio/opus_frame_encoder.h"
#include <esp_log.h>
#include <opus.h>
namespace borla {
namespace {
constexpr const char* kTag = "OpusFrameEncoder2";
} // namespace
OpusFrameEncoder::~OpusFrameEncoder()
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
opus_encoder_destroy(encoder_);
}
}
bool OpusFrameEncoder::Initialize(
uint32_t sample_rate,
uint8_t channels,
uint32_t bitrate)
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
return true;
}
int error = OPUS_OK;
encoder_ = opus_encoder_create(
static_cast<opus_int32>(sample_rate),
channels,
OPUS_APPLICATION_VOIP,
&error);
if (encoder_ == nullptr || error != OPUS_OK) {
ESP_LOGE(kTag, "encoder creation failed: %s",
opus_strerror(error));
encoder_ = nullptr;
return false;
}
channels_ = channels;
// Complexity 3, matching the previous firmware ("ESP32 上用最低复杂度保证
// 实时性", audio_service.cc:14). At complexity 4 a 60 ms frame measured
// 33 ms to encode with the core to itself and 82 ms averaged when TTS
// playback shared core 1 — the task-watchdog backtraces all ended inside
// silk_encode_frame_FIX. The uplink feeds server-side ASR at 16 kHz mono;
// it does not need the marginal quality of the higher search depth.
if (opus_encoder_ctl(
encoder_,
OPUS_SET_BITRATE(static_cast<opus_int32>(bitrate))) != OPUS_OK ||
opus_encoder_ctl(encoder_, OPUS_SET_COMPLEXITY(3)) != OPUS_OK ||
opus_encoder_ctl(encoder_, OPUS_SET_VBR(1)) != OPUS_OK ||
opus_encoder_ctl(encoder_, OPUS_SET_DTX(0)) != OPUS_OK) {
ESP_LOGE(kTag, "encoder configuration failed");
opus_encoder_destroy(encoder_);
encoder_ = nullptr;
return false;
}
ESP_LOGI(kTag, "initialized rate=%lu channels=%u bitrate=%lu",
static_cast<unsigned long>(sample_rate),
static_cast<unsigned>(channels),
static_cast<unsigned long>(bitrate));
return true;
}
bool OpusFrameEncoder::Encode(
const int16_t* pcm,
size_t samples_per_channel,
uint8_t* encoded,
size_t capacity,
size_t* encoded_size)
{
if (pcm == nullptr || encoded == nullptr ||
encoded_size == nullptr || samples_per_channel == 0 ||
capacity == 0 || capacity > INT32_MAX) {
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ == nullptr) {
return false;
}
const int result = opus_encode(
encoder_,
pcm,
static_cast<int>(samples_per_channel),
encoded,
static_cast<opus_int32>(capacity));
if (result <= 0) {
ESP_LOGE(kTag, "encode failed: %s", opus_strerror(result));
return false;
}
*encoded_size = static_cast<size_t>(result);
return true;
}
void OpusFrameEncoder::Reset()
{
std::lock_guard<std::mutex> lock(mutex_);
if (encoder_ != nullptr) {
opus_encoder_ctl(encoder_, OPUS_RESET_STATE);
}
}
} // namespace borla

View File

@@ -0,0 +1,36 @@
#pragma once
#include "protocol/binary_audio_protocol.h"
#include <cstddef>
#include <cstdint>
#include <mutex>
struct OpusEncoder;
namespace borla {
class OpusFrameEncoder final {
public:
OpusFrameEncoder() = default;
~OpusFrameEncoder();
bool Initialize(
uint32_t sample_rate,
uint8_t channels,
uint32_t bitrate);
bool Encode(
const int16_t* pcm,
size_t samples_per_channel,
uint8_t* encoded,
size_t capacity,
size_t* encoded_size);
void Reset();
private:
std::mutex mutex_;
OpusEncoder* encoder_ = nullptr;
uint8_t channels_ = 1;
};
} // namespace borla

View File

@@ -0,0 +1,61 @@
#include "audio/packed_opus_reader.h"
namespace borla {
namespace {
uint16_t ReadLe16(const uint8_t* data)
{
return static_cast<uint16_t>(
static_cast<uint16_t>(data[0]) |
(static_cast<uint16_t>(data[1]) << 8));
}
} // namespace
PackedOpusReader::PackedOpusReader(
const uint8_t* data,
size_t size)
: data_(data),
size_(size)
{
if (data_ == nullptr || size_ < 2) {
return;
}
frame_count_ = ReadLe16(data_);
offset_ = 2;
valid_ = frame_count_ > 0;
}
bool PackedOpusReader::Next(
const uint8_t** frame,
size_t* frame_size)
{
if (!valid_ || frame == nullptr || frame_size == nullptr ||
frames_read_ >= frame_count_) {
return false;
}
if (offset_ + 2 > size_) {
valid_ = false;
return false;
}
const uint16_t size = ReadLe16(data_ + offset_);
offset_ += 2;
if (size == 0 || offset_ + size > size_) {
valid_ = false;
return false;
}
*frame = data_ + offset_;
*frame_size = size;
offset_ += size;
frames_read_++;
return true;
}
bool PackedOpusReader::complete() const
{
return valid_ && frames_read_ == frame_count_ && offset_ == size_;
}
} // namespace borla

View File

@@ -0,0 +1,27 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
class PackedOpusReader final {
public:
PackedOpusReader(const uint8_t* data, size_t size);
bool Next(const uint8_t** frame, size_t* frame_size);
bool valid() const { return valid_; }
bool complete() const;
uint16_t frame_count() const { return frame_count_; }
uint16_t frames_read() const { return frames_read_; }
private:
const uint8_t* data_ = nullptr;
size_t size_ = 0;
size_t offset_ = 0;
uint16_t frame_count_ = 0;
uint16_t frames_read_ = 0;
bool valid_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,45 @@
#include "audio/pcm_rate_converter.h"
#include <algorithm>
namespace borla {
constexpr int32_t kMicDigitalGain = 16;
//bool Pcm24kTo16kConverter::Convert(
bool Pcm48kTo16kConverter::Convert(
const int16_t* input,
size_t input_samples,
int16_t* output,
size_t output_capacity) const
{
if (input == nullptr || output == nullptr ||
input_samples != kInputSamples ||
output_capacity < kOutputSamples) {
return false;
}
// 24k -> 16k is a 3:2 ratio. Even outputs copy an input sample and odd
// outputs interpolate the two adjacent samples. The exact frame boundary
// is preserved, which is more important than a streaming fractional
// accumulator for the fixed 60 ms protocol.
for (size_t index = 0; index < kOutputSamples; ++index) {
const size_t base = (index * 3U) / 2U *2U;
int32_t value;
if ((index & 1U) == 0U) {
value = static_cast<int32_t>(input[base]);
} else {
value = (static_cast<int32_t>(input[base]) + static_cast<int32_t>(input[base + 2U])) / 2;
}
value *= kMicDigitalGain;
output[index] = static_cast<int16_t>(std::clamp<int32_t>(value, -32768, 32767));
// const size_t base = index * 3U;
// const int32_t mixed =
// static_cast<int32_t>(input[base]) +
// static_cast<int32_t>(input[base + 1]) +
// static_cast<int32_t>(input[base + 2]);
// output[index] = static_cast<int16_t>(
// std::clamp<int32_t>(mixed / 3, -32768, 32767));
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,25 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
// Stateless conversion for exact 60 ms frames. The hardware codec runs at
// 24 kHz so RX and TX can share one I2S clock; uplink is converted to the
// protocol's fixed 16 kHz rate before voice processing/Opus.
//class Pcm24kTo16kConverter final {
class Pcm48kTo16kConverter final {
public:
//static constexpr size_t kInputSamples = 1440;
static constexpr size_t kInputSamples = 2880;
static constexpr size_t kOutputSamples = 960;
bool Convert(
const int16_t* input,
size_t input_samples,
int16_t* output,
size_t output_capacity) const;
};
} // namespace borla

View File

@@ -0,0 +1,321 @@
#include "audio/playback_controller.h"
#include <algorithm>
#include <limits>
namespace borla {
namespace {
constexpr PlaybackSessionId kLocalSessionIdBase = 0x80000000U;
bool IsRemoteSource(PlaybackSource source)
{
return source == PlaybackSource::kRemoteTts ||
source == PlaybackSource::kRemoteMusic;
}
} // namespace
PlaybackStartResult PlaybackController::StartSession(
PlaybackSource source,
PlaybackPriority priority,
PlaybackSessionId requested_id,
uint64_t now_ms)
{
if (IsRemoteSource(source) &&
(requested_id == 0 || requested_id >= kLocalSessionIdBase)) {
return {
PlaybackStartStatus::kRejectedInvalidSessionId,
0,
0,
0,
};
}
if (session_.active && requested_id != 0 &&
requested_id == session_.id && source == session_.source) {
return {
PlaybackStartStatus::kAlreadyActive,
session_.id,
0,
session_.generation,
};
}
if (session_.active &&
static_cast<uint8_t>(priority) <
static_cast<uint8_t>(session_.priority)) {
metrics_.lower_priority_rejections++;
return {
PlaybackStartStatus::kRejectedLowerPriority,
0,
0,
0,
};
}
PlaybackSessionId preempted = 0;
if (session_.active) {
preempted = session_.id;
session_.state = PlaybackSessionState::kCancelled;
session_.active = false;
metrics_.sessions_cancelled++;
metrics_.sessions_preempted++;
}
session_ = {};
session_.id = AllocateSessionId(requested_id);
session_.generation = next_generation_++;
if (next_generation_ == 0) {
next_generation_ = 1;
}
session_.source = source;
session_.priority = priority;
session_.state = PlaybackSessionState::kPending;
session_.active = true;
started_at_ms_ = now_ms;
last_progress_ms_ = now_ms;
metrics_.sessions_started++;
return {
PlaybackStartStatus::kStarted,
session_.id,
preempted,
session_.generation,
};
}
bool PlaybackController::CanAcceptFrame(
PlaybackSessionId session_id) const
{
return session_.active && session_id != 0 &&
session_.id == session_id;
}
bool PlaybackController::QueueFrame(
PlaybackSessionId session_id,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id)) {
return false;
}
session_.producer_started = true;
session_.queued_frames++;
session_.state = session_.input_ended
? PlaybackSessionState::kDraining
: PlaybackSessionState::kStreaming;
metrics_.frames_queued++;
metrics_.queue_high_watermark =
std::max(metrics_.queue_high_watermark, session_.queued_frames);
Touch(now_ms);
return true;
}
bool PlaybackController::RollbackQueuedFrame(
PlaybackSessionId session_id)
{
if (!IsCurrent(session_id) || session_.queued_frames == 0) {
return false;
}
session_.queued_frames--;
metrics_.frames_dropped++;
return true;
}
bool PlaybackController::BeginFrame(
PlaybackSessionId session_id,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id) || session_.queued_frames == 0) {
return false;
}
session_.queued_frames--;
session_.in_flight_frames++;
Touch(now_ms);
return true;
}
bool PlaybackController::FinishFrame(
PlaybackSessionId session_id,
bool write_succeeded,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id) ||
session_.in_flight_frames == 0) {
return false;
}
session_.in_flight_frames--;
if (write_succeeded) {
session_.written_frames++;
metrics_.frames_written++;
} else {
metrics_.frames_dropped++;
}
Touch(now_ms);
return true;
}
bool PlaybackController::EndInput(
PlaybackSessionId session_id,
uint64_t now_ms)
{
if (!CanAcceptFrame(session_id)) {
return false;
}
session_.input_ended = true;
session_.state = PlaybackSessionState::kDraining;
Touch(now_ms);
return true;
}
PlaybackSessionId PlaybackController::TryComplete()
{
if (!session_.active || !session_.producer_started ||
!session_.input_ended || session_.queued_frames != 0 ||
session_.in_flight_frames != 0) {
return 0;
}
session_.state = PlaybackSessionState::kCompleted;
session_.active = false;
metrics_.sessions_completed++;
return session_.id;
}
PlaybackSessionId PlaybackController::Cancel(
PlaybackSessionId session_id)
{
if (!session_.active ||
(session_id != 0 && session_id != session_.id)) {
return 0;
}
session_.state = PlaybackSessionState::kCancelled;
session_.active = false;
session_.queued_frames = 0;
metrics_.sessions_cancelled++;
return session_.id;
}
PlaybackSessionId PlaybackController::Fail(
PlaybackSessionId session_id)
{
if (!session_.active || session_id != session_.id) {
return 0;
}
session_.state = PlaybackSessionState::kFailed;
session_.active = false;
session_.queued_frames = 0;
metrics_.sessions_failed++;
return session_.id;
}
PlaybackTimeoutResult PlaybackController::CheckTimeout(
uint64_t now_ms,
uint32_t producer_start_timeout_ms,
uint32_t stalled_timeout_ms)
{
if (!session_.active) {
return {};
}
if (!session_.producer_started &&
now_ms - started_at_ms_ >= producer_start_timeout_ms) {
const PlaybackSessionId failed = Fail(session_.id);
metrics_.producer_start_timeouts++;
return {PlaybackTimeoutReason::kProducerStart, failed};
}
if (session_.producer_started && stalled_timeout_ms > 0 &&
now_ms - last_progress_ms_ >= stalled_timeout_ms) {
const PlaybackSessionId failed = Fail(session_.id);
metrics_.stalled_timeouts++;
return {PlaybackTimeoutReason::kStalled, failed};
}
return {};
}
void PlaybackController::RecordStaleFrame()
{
metrics_.stale_frames_rejected++;
metrics_.frames_dropped++;
}
bool PlaybackController::IsCurrent(
PlaybackSessionId session_id) const
{
return session_.active && session_.id == session_id;
}
PlaybackSessionId PlaybackController::AllocateSessionId(
PlaybackSessionId requested_id)
{
if (requested_id != 0) {
return requested_id;
}
const PlaybackSessionId allocated = next_session_id_;
next_session_id_++;
if (next_session_id_ < kLocalSessionIdBase) {
next_session_id_ = kLocalSessionIdBase;
}
return allocated;
}
void PlaybackController::Touch(uint64_t now_ms)
{
last_progress_ms_ = now_ms;
}
const char* ToString(PlaybackSessionState state)
{
switch (state) {
case PlaybackSessionState::kPending:
return "pending";
case PlaybackSessionState::kStreaming:
return "streaming";
case PlaybackSessionState::kDraining:
return "draining";
case PlaybackSessionState::kCancelled:
return "cancelled";
case PlaybackSessionState::kCompleted:
return "completed";
case PlaybackSessionState::kFailed:
return "failed";
}
return "unknown";
}
const char* ToString(PlaybackStartStatus status)
{
switch (status) {
case PlaybackStartStatus::kStarted:
return "started";
case PlaybackStartStatus::kAlreadyActive:
return "already_active";
case PlaybackStartStatus::kRejectedLowerPriority:
return "rejected_lower_priority";
case PlaybackStartStatus::kRejectedInvalidSessionId:
return "rejected_invalid_session_id";
}
return "unknown";
}
const char* ToString(PlaybackTimeoutReason reason)
{
switch (reason) {
case PlaybackTimeoutReason::kNone:
return "none";
case PlaybackTimeoutReason::kProducerStart:
return "producer_start";
case PlaybackTimeoutReason::kStalled:
return "stalled";
}
return "unknown";
}
} // namespace borla

View File

@@ -0,0 +1,121 @@
#pragma once
#include "core/playback_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
enum class PlaybackSessionState : uint8_t {
kPending,
kStreaming,
kDraining,
kCancelled,
kCompleted,
kFailed,
};
enum class PlaybackStartStatus : uint8_t {
kStarted,
kAlreadyActive,
kRejectedLowerPriority,
kRejectedInvalidSessionId,
};
enum class PlaybackTimeoutReason : uint8_t {
kNone,
kProducerStart,
kStalled,
};
struct PlaybackSessionSnapshot {
PlaybackSessionId id = 0;
uint32_t generation = 0;
PlaybackSource source = PlaybackSource::kRemoteTts;
PlaybackPriority priority = PlaybackPriority::kConversation;
PlaybackSessionState state = PlaybackSessionState::kCompleted;
size_t queued_frames = 0;
size_t in_flight_frames = 0;
uint32_t written_frames = 0;
bool active = false;
bool producer_started = false;
bool input_ended = false;
};
struct PlaybackMetrics {
uint32_t sessions_started = 0;
uint32_t sessions_completed = 0;
uint32_t sessions_cancelled = 0;
uint32_t sessions_failed = 0;
uint32_t sessions_preempted = 0;
uint32_t lower_priority_rejections = 0;
uint32_t stale_frames_rejected = 0;
uint32_t frames_queued = 0;
uint32_t frames_written = 0;
uint32_t frames_dropped = 0;
uint32_t producer_start_timeouts = 0;
uint32_t stalled_timeouts = 0;
size_t queue_high_watermark = 0;
};
struct PlaybackStartResult {
PlaybackStartStatus status = PlaybackStartStatus::kRejectedLowerPriority;
PlaybackSessionId session_id = 0;
PlaybackSessionId preempted_session_id = 0;
uint32_t generation = 0;
};
struct PlaybackTimeoutResult {
PlaybackTimeoutReason reason = PlaybackTimeoutReason::kNone;
PlaybackSessionId session_id = 0;
};
class PlaybackController final {
public:
PlaybackStartResult StartSession(
PlaybackSource source,
PlaybackPriority priority,
PlaybackSessionId requested_id,
uint64_t now_ms);
bool CanAcceptFrame(PlaybackSessionId session_id) const;
bool QueueFrame(PlaybackSessionId session_id, uint64_t now_ms);
bool RollbackQueuedFrame(PlaybackSessionId session_id);
bool BeginFrame(PlaybackSessionId session_id, uint64_t now_ms);
bool FinishFrame(
PlaybackSessionId session_id,
bool write_succeeded,
uint64_t now_ms);
bool EndInput(PlaybackSessionId session_id, uint64_t now_ms);
PlaybackSessionId TryComplete();
PlaybackSessionId Cancel(PlaybackSessionId session_id);
PlaybackSessionId Fail(PlaybackSessionId session_id);
PlaybackTimeoutResult CheckTimeout(
uint64_t now_ms,
uint32_t producer_start_timeout_ms,
uint32_t stalled_timeout_ms);
void RecordStaleFrame();
bool IsCurrent(PlaybackSessionId session_id) const;
const PlaybackSessionSnapshot& snapshot() const { return session_; }
const PlaybackMetrics& metrics() const { return metrics_; }
private:
PlaybackSessionId AllocateSessionId(PlaybackSessionId requested_id);
void Touch(uint64_t now_ms);
PlaybackSessionSnapshot session_{};
PlaybackMetrics metrics_{};
PlaybackSessionId next_session_id_ = 0x80000000U;
uint32_t next_generation_ = 1;
uint64_t started_at_ms_ = 0;
uint64_t last_progress_ms_ = 0;
};
const char* ToString(PlaybackSessionState state);
const char* ToString(PlaybackStartStatus status);
const char* ToString(PlaybackTimeoutReason reason);
} // namespace borla

View File

@@ -0,0 +1,660 @@
#include "audio/playback_pipeline.h"
#include "core/task_stack_budget.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/idf_additions.h>
#include <algorithm>
#include <cstring>
#include <new>
namespace borla {
namespace {
constexpr const char* kTag = "PlaybackPipeline2";
constexpr uint32_t kProducerStartTimeoutMs = 2000;
constexpr uint32_t kStalledTimeoutMs = 10000;
// How long a late frame may be held waiting for a companion after the ready
// queue ran dry. Playout health showed why: the server re-anchors its rate
// control after a TTS generation stall and never refills the burst cushion,
// so a starved stretch played as a run of 60-80 ms micro-gaps (16 in one
// session). Holding once converts that into a single short pause followed by
// smooth playout. Draining sessions never hold — every frame is already
// queued once EndInput has been seen.
constexpr uint32_t kDryRebuildHoldMs = 150;
// Fixed hold before the FIRST write of a remote TTS session. The server runs
// 6 frames (360 ms) ahead and never refills after a generation stall (it
// re-anchors instead), so the cushion only ever shrinks over a reply.
// Delaying playout start grows the server's effective lead by exactly the
// hold: 360 + 180 = 540 ms of stall budget, which absorbs typical
// inter-sentence TTS generation gaps that were audible as mid-reply breaks.
// Local prompts are exempt — they are fully buffered and latency-sensitive.
constexpr uint32_t kStartupPrebufferMs = 180;
} // namespace
PlaybackPipeline::PlaybackPipeline(IAudioOutput& output)
: output_(output)
{
}
PlaybackPipeline::~PlaybackPipeline()
{
Stop();
if (frame_pool_ != nullptr) {
heap_caps_free(frame_pool_);
}
if (decode_buffer_ != nullptr) {
heap_caps_free(decode_buffer_);
}
if (reference_buffer_ != nullptr) {
heap_caps_free(reference_buffer_);
}
}
void PlaybackPipeline::SetEventPublisher(IEventPublisher* publisher)
{
publisher_.store(publisher, std::memory_order_release);
}
bool PlaybackPipeline::Initialize()
{
if (initialized_) {
return true;
}
if (output_.SampleRate() != kSampleRate) {
ESP_LOGE(kTag, "output rate=%lu does not match pipeline rate=%lu",
static_cast<unsigned long>(output_.SampleRate()),
static_cast<unsigned long>(kSampleRate));
return false;
}
if (!decoder_.Initialize(kSampleRate, 1)) {
return false;
}
if (stopped_signal_ == nullptr) {
stopped_signal_
= xSemaphoreCreateBinaryStatic(&stopped_signal_storage_);
if (stopped_signal_ == nullptr) {
ESP_LOGE(kTag, "task stop signal creation failed");
return false;
}
}
if (frame_pool_ == nullptr) {
frame_pool_ = static_cast<FrameSlot*>(heap_caps_calloc(kFramePoolSize,
sizeof(FrameSlot), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (decode_buffer_ == nullptr) {
decode_buffer_
= static_cast<int16_t*>(heap_caps_calloc(kSamplesPerFrame,
sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (reference_buffer_ == nullptr) {
reference_buffer_
= static_cast<int16_t*>(heap_caps_calloc(kSamplesPerFrame,
sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
}
if (frame_pool_ == nullptr || decode_buffer_ == nullptr ||
reference_buffer_ == nullptr) {
ESP_LOGE(kTag,
"PSRAM allocation failed pool=%p decode=%p reference=%p",
frame_pool_, decode_buffer_, reference_buffer_);
return false;
}
for (size_t index = 0; index < kFramePoolSize; ++index) {
new (&frame_pool_[index]) FrameSlot();
}
free_slots_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t),
free_slots_queue_bytes_, &free_slots_storage_);
ready_frames_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t),
ready_frames_queue_bytes_, &ready_frames_storage_);
if (free_slots_ == nullptr || ready_frames_ == nullptr) {
ESP_LOGE(kTag, "static queue creation failed");
return false;
}
for (uint16_t index = 0; index < kFramePoolSize; ++index) {
if (xQueueSend(free_slots_, &index, 0) != pdTRUE) {
ESP_LOGE(kTag, "failed to seed frame slot=%u", index);
return false;
}
}
initialized_ = true;
ESP_LOGI(kTag, "initialized frames=%u slot_bytes=%u PSRAM=%u bytes",
static_cast<unsigned>(kFramePoolSize),
static_cast<unsigned>(sizeof(FrameSlot)),
static_cast<unsigned>(kFramePoolSize * sizeof(FrameSlot)
+ 2 * kSamplesPerFrame * sizeof(int16_t)));
return true;
}
bool PlaybackPipeline::Start()
{
if (running_.load(std::memory_order_acquire)) {
return true;
}
if (!initialized_ && !Initialize()) {
return false;
}
xSemaphoreTake(stopped_signal_, 0);
running_.store(true, std::memory_order_release);
const BaseType_t result
= xTaskCreatePinnedToCoreWithCaps(&PlaybackPipeline::TaskEntry,
"playback", task_stack_budget::kPlaybackBytes, this,
task_priority::kPlaybackLoop, &task_, 1,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (result != pdPASS) {
running_.store(false, std::memory_order_release);
task_ = nullptr;
ESP_LOGE(kTag, "failed to create playback task");
return false;
}
ESP_LOGI(kTag, "task started stack_bytes=%u memory=PSRAM",
static_cast<unsigned>(task_stack_budget::kPlaybackBytes));
return true;
}
void PlaybackPipeline::Stop()
{
paused_.store(false, std::memory_order_release);
if (!running_.exchange(false, std::memory_order_acq_rel)) {
return;
}
if (task_ != nullptr) {
if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) {
ESP_LOGE(kTag, "speaker-owner task stop timed out");
}
vTaskDeleteWithCaps(task_);
task_ = nullptr;
}
std::lock_guard<std::mutex> lock(mutex_);
controller_.Cancel(0);
DrainReadyQueueLocked();
decoder_.Reset();
}
PlaybackStartResult PlaybackPipeline::StartSession(PlaybackSource source,
PlaybackPriority priority, PlaybackSessionId requested_id)
{
if (!running_.load(std::memory_order_acquire)) {
return {};
}
PlaybackStartResult result;
{
std::lock_guard<std::mutex> lock(mutex_);
result
= controller_.StartSession(source, priority, requested_id, NowMs());
if (result.status == PlaybackStartStatus::kStarted) {
paused_.store(false, std::memory_order_release);
backpressure_logged_session_.store(
0, std::memory_order_release);
DrainReadyQueueLocked();
// The decoder is reset by the playback task itself, right before
// the next Decode: this path runs on the application task while
// Run() may be inside Decode() — which happens OUTSIDE mutex_ —
// and libopus state is not reentrant. The flag is honoured before
// the new session's first frame, which is all the reset is for.
decoder_reset_pending_.store(
true, std::memory_order_release);
// Drop any reference frames stranded from the previous session so
// the AEC starts this one in phase with the speaker.
IPlaybackReferenceSink* reference_sink
= reference_sink_.load(std::memory_order_acquire);
if (reference_sink != nullptr) {
reference_sink->ResetPlaybackReference();
}
ESP_LOGI(kTag,
"session start id=%lu generation=%lu source=%s "
"priority=%s preempted=%lu",
static_cast<unsigned long>(result.session_id),
static_cast<unsigned long>(result.generation), ToString(source),
ToString(priority),
static_cast<unsigned long>(result.preempted_session_id));
} else {
ESP_LOGW(kTag,
"session request status=%s requested=%lu source=%s "
"priority=%s",
ToString(result.status),
static_cast<unsigned long>(requested_id), ToString(source),
ToString(priority));
}
}
if (result.preempted_session_id != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackPreempted,
result.preempted_session_id, result.session_id);
}
return result;
}
bool PlaybackPipeline::SubmitOpus(
PlaybackSessionId session_id, const uint8_t* data, size_t size)
{
if (data == nullptr || size == 0 || size > kMaxOpusBytes) {
ESP_LOGW(
kTag, "invalid Opus frame size=%u", static_cast<unsigned>(size));
return false;
}
return SubmitFrame(session_id, FrameFormat::kOpus, data, size, 0);
}
bool PlaybackPipeline::SubmitPcm(
PlaybackSessionId session_id, const int16_t* samples, size_t sample_count)
{
if (samples == nullptr || sample_count == 0
|| sample_count > kSamplesPerFrame) {
return false;
}
return SubmitFrame(session_id, FrameFormat::kPcm, samples,
sample_count * sizeof(int16_t), sample_count);
}
bool PlaybackPipeline::EndInput(PlaybackSessionId session_id)
{
PlaybackSessionId completed = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!controller_.EndInput(session_id, NowMs())) {
return false;
}
completed = controller_.TryComplete();
}
if (completed != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed);
}
return true;
}
bool PlaybackPipeline::Cancel(PlaybackSessionId session_id)
{
paused_.store(false, std::memory_order_release);
std::lock_guard<std::mutex> lock(mutex_);
const PlaybackSessionId cancelled = controller_.Cancel(session_id);
if (cancelled == 0) {
return false;
}
DrainReadyQueueLocked();
// Same reentrancy rule as StartSession: Decode() runs outside mutex_ on
// the playback task, so the reset must happen there, not here.
decoder_reset_pending_.store(true, std::memory_order_release);
ESP_LOGI(kTag, "session cancelled id=%lu",
static_cast<unsigned long>(cancelled));
return true;
}
void PlaybackPipeline::SetPaused(bool paused)
{
const bool previous = paused_.exchange(
paused, std::memory_order_acq_rel);
if (previous != paused) {
ESP_LOGI(kTag, "playback %s for barge-in candidate",
paused ? "paused" : "resumed");
}
}
PlaybackSessionSnapshot PlaybackPipeline::Snapshot() const
{
std::lock_guard<std::mutex> lock(mutex_);
return controller_.snapshot();
}
PlaybackMetrics PlaybackPipeline::Metrics() const
{
std::lock_guard<std::mutex> lock(mutex_);
return controller_.metrics();
}
void PlaybackPipeline::TaskEntry(void* context)
{
static_cast<PlaybackPipeline*>(context)->Run();
}
void PlaybackPipeline::Run()
{
ESP_LOGI(kTag, "speaker-owner task started");
while (running_.load(std::memory_order_acquire)) {
uint16_t slot_index = 0;
if (xQueueReceive(ready_frames_, &slot_index, pdMS_TO_TICKS(20))
!= pdTRUE) {
CheckTimeout();
continue;
}
if (slot_index >= kFramePoolSize) {
ESP_LOGE(kTag, "invalid frame slot=%u", slot_index);
continue;
}
const uint32_t ready_depth = static_cast<uint32_t>(
uxQueueMessagesWaiting(ready_frames_));
// Candidate barge-in is reversible. Keep the dequeued head frame and
// every queued frame intact until the server confirms or rejects the
// ASR result. A frame already inside synchronous I2S Write() may finish,
// so pause latency is bounded by one 60 ms frame.
if (paused_.load(std::memory_order_acquire)) {
// A deliberate hold is not starvation; skip the next gap sample.
health_skip_gap_ = true;
}
while (running_.load(std::memory_order_acquire) &&
paused_.load(std::memory_order_acquire)) {
vTaskDelay(pdMS_TO_TICKS(10));
}
if (!running_.load(std::memory_order_acquire)) {
ReleaseSlot(slot_index);
break;
}
FrameSlot& slot = frame_pool_[slot_index];
if (slot.session_id != health_session_) {
// First frame of a new session: see kStartupPrebufferMs.
bool prebuffer = false;
{
std::lock_guard<std::mutex> lock(mutex_);
prebuffer = controller_.IsCurrent(slot.session_id) &&
controller_.snapshot().source ==
PlaybackSource::kRemoteTts;
}
if (prebuffer) {
const uint64_t deadline_us =
static_cast<uint64_t>(esp_timer_get_time()) +
kStartupPrebufferMs * 1000ULL;
bool still_current = true;
while (still_current &&
running_.load(std::memory_order_acquire) &&
!paused_.load(std::memory_order_acquire) &&
static_cast<uint64_t>(esp_timer_get_time()) <
deadline_us) {
vTaskDelay(pdMS_TO_TICKS(10));
std::lock_guard<std::mutex> lock(mutex_);
still_current =
controller_.IsCurrent(slot.session_id);
}
}
} else if (last_write_end_us_ != 0 &&
static_cast<uint64_t>(esp_timer_get_time()) -
last_write_end_us_ >
kFrameDurationMs * 1000ULL) {
// De-jitter rebuild: reaching this frame more than one period
// after the previous write finished means the queue ran dry and
// the DMA is draining right now. Hold briefly for a companion
// frame so the dry spell plays as one pause instead of a
// micro-gap per frame. Also covers the post-candidate resume,
// which restarts with zero cushion.
bool input_ended = false;
{
std::lock_guard<std::mutex> lock(mutex_);
input_ended = !controller_.IsCurrent(slot.session_id) ||
controller_.snapshot().input_ended;
}
const uint64_t hold_deadline_us =
static_cast<uint64_t>(esp_timer_get_time()) +
kDryRebuildHoldMs * 1000ULL;
while (!input_ended &&
running_.load(std::memory_order_acquire) &&
!paused_.load(std::memory_order_acquire) &&
uxQueueMessagesWaiting(ready_frames_) == 0 &&
static_cast<uint64_t>(esp_timer_get_time()) <
hold_deadline_us) {
vTaskDelay(pdMS_TO_TICKS(10));
std::lock_guard<std::mutex> lock(mutex_);
input_ended = controller_.snapshot().input_ended;
}
}
bool process = false;
{
std::lock_guard<std::mutex> lock(mutex_);
process = controller_.BeginFrame(slot.session_id, NowMs());
if (!process) {
controller_.RecordStaleFrame();
}
}
if (!process) {
ReleaseSlot(slot_index);
continue;
}
size_t decoded_samples = 0;
bool decoded = false;
if (slot.format == FrameFormat::kOpus) {
if (decoder_reset_pending_.exchange(
false, std::memory_order_acq_rel)) {
decoder_.Reset();
}
decoded = decoder_.Decode(slot.payload, slot.payload_size,
decode_buffer_, kSamplesPerFrame, &decoded_samples);
} else {
decoded_samples = slot.sample_count;
std::memcpy(decode_buffer_, slot.payload,
decoded_samples * sizeof(int16_t));
decoded = true;
}
PlaybackSessionId completed = 0;
PlaybackSessionId failed = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
if (!controller_.IsCurrent(slot.session_id)) {
controller_.RecordStaleFrame();
} else if (!decoded) {
failed = controller_.Fail(slot.session_id);
DrainReadyQueueLocked();
} else {
// Hold the ownership lock across the synchronous I2S write.
// A preemption waits at most one 60 ms frame, and after it
// returns no frame from the old session can reach the PA.
IPlaybackReferenceSink* reference_sink
= reference_sink_.load(std::memory_order_acquire);
if (reference_sink != nullptr) {
// Mirror the software volume applied inside Write(). AEC
// must receive the PCM amplitude that reaches the DAC,
// not the unscaled decoder output.
const int32_t gain =
static_cast<int32_t>(output_.VolumePercent()) *
256 / 100;
for (size_t index = 0;
index < decoded_samples;
++index) {
const int32_t scaled =
(static_cast<int32_t>(decode_buffer_[index]) *
gain) >> 8;
reference_buffer_[index] =
static_cast<int16_t>(std::clamp<int32_t>(
scaled, -32768, 32767));
}
reference_sink->OnPlaybackReference(
reference_buffer_, decoded_samples);
}
if (slot.session_id != health_session_) {
FlushPlayoutHealth();
health_session_ = slot.session_id;
health_skip_gap_ = true;
health_depth_min_ = ready_depth;
health_depth_max_ = ready_depth;
}
const uint64_t write_start_us =
static_cast<uint64_t>(esp_timer_get_time());
if (!health_skip_gap_ && last_write_end_us_ != 0) {
const uint32_t gap_ms = static_cast<uint32_t>(
(write_start_us - last_write_end_us_) / 1000ULL);
health_max_gap_ms_ =
std::max(health_max_gap_ms_, gap_ms);
if (gap_ms > kFrameDurationMs) {
health_gap_over_frame_++;
}
if (gap_ms > 90) {
health_gap_over_dma_++;
}
}
health_skip_gap_ = false;
health_frames_++;
health_depth_min_ =
std::min(health_depth_min_, ready_depth);
health_depth_max_ =
std::max(health_depth_max_, ready_depth);
const bool written
= output_.Write(decode_buffer_, decoded_samples);
last_write_end_us_ =
static_cast<uint64_t>(esp_timer_get_time());
controller_.FinishFrame(slot.session_id, written, NowMs());
if (!written) {
failed = controller_.Fail(slot.session_id);
DrainReadyQueueLocked();
} else {
completed = controller_.TryComplete();
}
}
}
ReleaseSlot(slot_index);
if (failed != 0 || completed != 0) {
FlushPlayoutHealth();
}
if (failed != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackFailed, failed);
} else if (completed != 0) {
PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed);
}
}
FlushPlayoutHealth();
xSemaphoreGive(stopped_signal_);
for (;;) {
vTaskSuspend(nullptr);
}
}
void PlaybackPipeline::FlushPlayoutHealth()
{
if (health_frames_ > 1) {
// One line per session. gaps>frame means the queue ran dry longer
// than one frame period (cushion gone); gaps>dma means the 90 ms
// I2S buffer also drained and the break reached the speaker.
ESP_LOGI(kTag,
"playout health id=%lu frames=%lu max_gap=%lums "
"gaps>frame=%lu gaps>dma=%lu depth=%lu..%lu",
static_cast<unsigned long>(health_session_),
static_cast<unsigned long>(health_frames_),
static_cast<unsigned long>(health_max_gap_ms_),
static_cast<unsigned long>(health_gap_over_frame_),
static_cast<unsigned long>(health_gap_over_dma_),
static_cast<unsigned long>(health_depth_min_),
static_cast<unsigned long>(health_depth_max_));
}
health_session_ = 0;
health_frames_ = 0;
health_max_gap_ms_ = 0;
health_gap_over_frame_ = 0;
health_gap_over_dma_ = 0;
health_depth_min_ = 0;
health_depth_max_ = 0;
last_write_end_us_ = 0;
health_skip_gap_ = false;
}
bool PlaybackPipeline::SubmitFrame(PlaybackSessionId session_id,
FrameFormat format, const void* data, size_t byte_count,
size_t sample_count)
{
if (!running_.load(std::memory_order_acquire) || data == nullptr
|| byte_count > kMaxFrameBytes) {
return false;
}
uint16_t slot_index = 0;
if (xQueueReceive(free_slots_, &slot_index, 0) != pdTRUE) {
const PlaybackSessionId already_logged
= backpressure_logged_session_.exchange(
session_id, std::memory_order_acq_rel);
if (already_logged != session_id) {
ESP_LOGD(kTag,
"producer pacing session=%lu; frame pool temporarily full",
static_cast<unsigned long>(session_id));
}
return false;
}
FrameSlot& slot = frame_pool_[slot_index];
slot.session_id = session_id;
slot.format = format;
slot.payload_size = static_cast<uint16_t>(byte_count);
slot.sample_count = static_cast<uint16_t>(sample_count);
std::memcpy(slot.payload, data, byte_count);
{
std::lock_guard<std::mutex> lock(mutex_);
if (!controller_.QueueFrame(session_id, NowMs())) {
controller_.RecordStaleFrame();
ReleaseSlot(slot_index);
return false;
}
if (xQueueSend(ready_frames_, &slot_index, 0) != pdTRUE) {
controller_.RollbackQueuedFrame(session_id);
ReleaseSlot(slot_index);
ESP_LOGE(kTag, "ready queue unexpectedly full");
return false;
}
}
return true;
}
void PlaybackPipeline::DrainReadyQueueLocked()
{
uint16_t slot_index = 0;
while (xQueueReceive(ready_frames_, &slot_index, 0) == pdTRUE) {
ReleaseSlot(slot_index);
}
}
void PlaybackPipeline::ReleaseSlot(uint16_t slot_index)
{
if (xQueueSend(free_slots_, &slot_index, 0) != pdTRUE) {
ESP_LOGE(kTag, "failed to release frame slot=%u", slot_index);
}
}
void PlaybackPipeline::CheckTimeout()
{
PlaybackTimeoutResult timeout;
{
std::lock_guard<std::mutex> lock(mutex_);
timeout = controller_.CheckTimeout(
NowMs(), kProducerStartTimeoutMs, kStalledTimeoutMs);
if (timeout.session_id != 0) {
DrainReadyQueueLocked();
decoder_.Reset();
}
}
if (timeout.session_id != 0) {
ESP_LOGE(kTag, "session timeout id=%lu reason=%s",
static_cast<unsigned long>(timeout.session_id),
ToString(timeout.reason));
PublishPlaybackEvent(AppEventType::kPlaybackFailed, timeout.session_id);
}
}
void PlaybackPipeline::PublishPlaybackEvent(AppEventType type,
PlaybackSessionId session_id, PlaybackSessionId replacement_session_id)
{
IEventPublisher* publisher = publisher_.load(std::memory_order_acquire);
if (publisher == nullptr
|| !publisher->Publish(
AppEvent::Make(type, session_id, 0, replacement_session_id))) {
ESP_LOGE(kTag, "failed to publish playback event=%s session=%lu",
ToString(type), static_cast<unsigned long>(session_id));
}
}
uint64_t PlaybackPipeline::NowMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace borla

View File

@@ -0,0 +1,151 @@
#pragma once
#include "audio/audio_output.h"
#include "audio/opus_frame_decoder.h"
#include "audio/playback_controller.h"
#include "audio/voice_frame_processor.h"
#include "ports/event_publisher.h"
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <mutex>
namespace borla {
class PlaybackPipeline final {
public:
static constexpr uint32_t kSampleRate = 48000;//24000;
static constexpr uint32_t kFrameDurationMs = 60;
static constexpr size_t kSamplesPerFrame =
kSampleRate * kFrameDurationMs / 1000;
static constexpr size_t kMaxFrameBytes =
kSamplesPerFrame * sizeof(int16_t);
static constexpr size_t kMaxOpusBytes = 1536;
static constexpr size_t kFramePoolSize = 48;
explicit PlaybackPipeline(IAudioOutput& output);
~PlaybackPipeline();
void SetEventPublisher(IEventPublisher* publisher);
// True while a session still owns the speaker. Used to hold off a reboot
// until the prompt that explains the reboot has actually been heard.
bool Active() const
{
std::lock_guard<std::mutex> lock(mutex_);
return controller_.snapshot().active;
}
void SetReferenceSink(IPlaybackReferenceSink* sink)
{
reference_sink_.store(sink);
}
bool Initialize();
bool Start();
void Stop();
PlaybackStartResult StartSession(
PlaybackSource source,
PlaybackPriority priority,
PlaybackSessionId requested_id = 0);
bool SubmitOpus(
PlaybackSessionId session_id,
const uint8_t* data,
size_t size);
bool SubmitPcm(
PlaybackSessionId session_id,
const int16_t* samples,
size_t sample_count);
bool EndInput(PlaybackSessionId session_id);
void SetPaused(bool paused);
bool Cancel(PlaybackSessionId session_id = 0);
PlaybackSessionSnapshot Snapshot() const;
PlaybackMetrics Metrics() const;
private:
enum class FrameFormat : uint8_t {
kOpus,
kPcm,
};
struct FrameSlot {
PlaybackSessionId session_id = 0;
FrameFormat format = FrameFormat::kOpus;
uint16_t payload_size = 0;
uint16_t sample_count = 0;
alignas(int16_t) uint8_t payload[kMaxFrameBytes]{};
};
static void TaskEntry(void* context);
void Run();
void FlushPlayoutHealth();
bool SubmitFrame(
PlaybackSessionId session_id,
FrameFormat format,
const void* data,
size_t byte_count,
size_t sample_count);
void DrainReadyQueueLocked();
void ReleaseSlot(uint16_t slot_index);
void CheckTimeout();
void PublishPlaybackEvent(
AppEventType type,
PlaybackSessionId session_id,
PlaybackSessionId replacement_session_id = 0);
static uint64_t NowMs();
IAudioOutput& output_;
std::atomic<IEventPublisher*> publisher_{nullptr};
std::atomic<IPlaybackReferenceSink*> reference_sink_{nullptr};
OpusFrameDecoder decoder_;
mutable std::mutex mutex_;
PlaybackController controller_;
FrameSlot* frame_pool_ = nullptr;
int16_t* decode_buffer_ = nullptr;
int16_t* reference_buffer_ = nullptr;
QueueHandle_t free_slots_ = nullptr;
QueueHandle_t ready_frames_ = nullptr;
StaticQueue_t free_slots_storage_{};
StaticQueue_t ready_frames_storage_{};
uint8_t free_slots_queue_bytes_[kFramePoolSize * sizeof(uint16_t)]{};
uint8_t ready_frames_queue_bytes_[kFramePoolSize * sizeof(uint16_t)]{};
SemaphoreHandle_t stopped_signal_ = nullptr;
StaticSemaphore_t stopped_signal_storage_{};
TaskHandle_t task_ = nullptr;
bool initialized_ = false;
std::atomic<bool> running_{false};
std::atomic<bool> paused_{false};
// Playout health accounting, owned exclusively by the speaker task.
// The server paces frames in real time after a 6-frame (360 ms) burst,
// so the whole jitter cushion is that burst plus the 90 ms I2S DMA.
// These counters turn "偶发卡顿" into one measurable line per session:
// an inter-write gap > 60 ms means the cushion fully eroded, > 90 ms
// means the DMA drained and the break was audible.
PlaybackSessionId health_session_ = 0;
uint64_t last_write_end_us_ = 0;
bool health_skip_gap_ = false;
uint32_t health_frames_ = 0;
uint32_t health_gap_over_frame_ = 0;
uint32_t health_gap_over_dma_ = 0;
uint32_t health_max_gap_ms_ = 0;
uint32_t health_depth_min_ = 0;
uint32_t health_depth_max_ = 0;
// Set by StartSession/Cancel (application task); consumed by Run() right
// before Decode(), the only place allowed to touch decoder_ while the
// playback task lives. Decode() runs outside mutex_, so a direct Reset()
// from another task would race it.
std::atomic<bool> decoder_reset_pending_{false};
std::atomic<PlaybackSessionId> backpressure_logged_session_{0};
};
} // namespace borla

View File

@@ -0,0 +1,68 @@
#include "audio/voice_activity_detector.h"
#include <cmath>
namespace borla {
VoiceActivityDetector::VoiceActivityDetector(
VoiceActivityConfig config)
: config_(config)
{
if (config_.start_frames == 0) {
config_.start_frames = 1;
}
if (config_.stop_frames == 0) {
config_.stop_frames = 1;
}
}
VoiceActivityResult VoiceActivityDetector::Process(
const int16_t* samples,
size_t sample_count)
{
if (samples == nullptr || sample_count == 0) {
return VoiceActivityResult::kSilence;
}
uint64_t energy = 0;
for (size_t index = 0; index < sample_count; ++index) {
const int32_t sample = samples[index];
energy += static_cast<uint64_t>(sample * sample);
}
last_rms_ = static_cast<uint32_t>(
std::sqrt(
static_cast<double>(energy) /
static_cast<double>(sample_count)));
const bool loud = last_rms_ >= config_.rms_threshold;
if (!speech_active_) {
quiet_frames_ = 0;
loud_frames_ = loud ? static_cast<uint8_t>(loud_frames_ + 1) : 0;
if (loud_frames_ >= config_.start_frames) {
speech_active_ = true;
loud_frames_ = 0;
return VoiceActivityResult::kSpeechStarted;
}
return VoiceActivityResult::kSilence;
}
if (loud) {
quiet_frames_ = 0;
return VoiceActivityResult::kSpeech;
}
if (++quiet_frames_ >= config_.stop_frames) {
speech_active_ = false;
quiet_frames_ = 0;
return VoiceActivityResult::kSpeechEnded;
}
return VoiceActivityResult::kSpeech;
}
void VoiceActivityDetector::Reset()
{
loud_frames_ = 0;
quiet_frames_ = 0;
speech_active_ = false;
last_rms_ = 0;
}
} // namespace borla

View File

@@ -0,0 +1,41 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
enum class VoiceActivityResult : uint8_t {
kSilence,
kSpeechStarted,
kSpeech,
kSpeechEnded,
};
struct VoiceActivityConfig {
uint16_t rms_threshold = 650;
uint8_t start_frames = 2;
uint8_t stop_frames = 13;
};
class VoiceActivityDetector final {
public:
explicit VoiceActivityDetector(
VoiceActivityConfig config = {});
VoiceActivityResult Process(
const int16_t* samples,
size_t sample_count);
void Reset();
bool speech_active() const { return speech_active_; }
uint32_t LastRms() const { return last_rms_; }
private:
VoiceActivityConfig config_;
uint8_t loud_frames_ = 0;
uint8_t quiet_frames_ = 0;
bool speech_active_ = false;
uint32_t last_rms_ = 0;
};
} // namespace borla

403
main/audio/voice_dsp.cc Normal file
View File

@@ -0,0 +1,403 @@
#include "audio/voice_dsp.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace borla {
namespace {
constexpr const char* kTag = "VoiceDsp2";
constexpr float kTargetPeak = 0.42f;
constexpr float kMinimumGain = 0.8f;
constexpr float kMaximumGain = 4.0f;
constexpr float kBargeInMaximumGain = 1.8f;
constexpr float kNoiseGateAttenuation = 0.1f;
constexpr float kBargeInNoiseGateAttenuation = 0.05f;
// esp-sr allocates its AEC and NS state with plain malloc, and this build
// routes allocations larger than 16 KB to PSRAM. An earlier revision forced
// them into internal SRAM on the theory that the adaptive filter running over
// the PSRAM bus explained the AEC's per-frame cost. Field measurement killed
// that theory twice over: with the states internal the AEC still cost ~50 ms
// per 60 ms frame (placement was worth at most a few ms), and the ~50 KB of
// internal RAM they consumed starved lwIP (free=4415 min=531) until a TLS
// send failed mid-conversation and dropped the WebSocket. PSRAM placement is
// therefore the correct trade; the probes below keep reporting where the
// states actually land so the question stays answered.
} // namespace
VoiceDsp::~VoiceDsp()
{
DisableEchoCancellation();
if (ns_ != nullptr) {
ns_destroy(ns_);
}
}
bool VoiceDsp::InitializeNoiseSuppression()
{
if (ns_ != nullptr) {
return true;
}
const size_t internal_before =
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
ns_ = ns_pro_create(10, 2, 16000);
if (ns_ == nullptr) {
ESP_LOGE(kTag, "NS initialization failed");
return false;
}
ESP_LOGI(kTag, "NS state internal=%d bytes",
static_cast<int>(
internal_before -
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)));
return true;
}
bool VoiceDsp::EnableEchoCancellation(bool barge_in_profile)
{
if (aec_ != nullptr) {
// Both profiles use identical aec_create parameters — the flag only
// selects post-processing (NS off + conservative AGC for barge-in).
// Never tear the state down for a profile flip: aec_create grabs
// whatever internal RAM is free at that instant and keeps it for the
// rest of the session, so a mid-session re-create once confiscated
// the websocket's reconnect budget the moment it was released
// (internal free pinned at 75 bytes, every TLS attempt failing).
if (barge_in_profile_ != barge_in_profile) {
barge_in_profile_ = barge_in_profile;
Reset();
}
return true;
}
// FD_LOW_COST left speech-shaped TTS residue at RMS 4k-12k on this
// board. VOIP_HIGH_PERF/filter=4 is the field-proven ESP32-S3 setup for
// both barge-in and calls. The profile flag selects conservative
// post-processing for barge-in; it no longer selects a weaker AEC.
const aec_mode_t mode = AEC_MODE_VOIP_HIGH_PERF;
const int filter_length = 4;
// The deltas logged below say where the state actually landed — see the
// note above InitializeNoiseSuppression for why PSRAM is the intended
// answer.
const size_t internal_before =
heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
const size_t psram_before =
heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
aec_ = aec_create(16000, filter_length, 1, mode);
ESP_LOGI(kTag,
"AEC state allocated internal=%d psram=%d (bytes)",
static_cast<int>(
internal_before -
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
static_cast<int>(
psram_before -
heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
if (aec_ == nullptr) {
ESP_LOGE(kTag, "AEC initialization failed");
return false;
}
aec_chunk_samples_ = aec_get_chunksize(aec_);
if (aec_chunk_samples_ <= 0 ||
aec_chunk_samples_ >
static_cast<int>(kMaximumAecChunk)) {
ESP_LOGE(kTag, "unsupported AEC chunk=%d",
aec_chunk_samples_);
DisableEchoCancellation();
return false;
}
barge_in_profile_ = barge_in_profile;
Reset();
ESP_LOGI(kTag, "AEC enabled mode=%s chunk=%d filter=%d profile=%s",
aec_get_mode_string(mode),
aec_chunk_samples_,
filter_length,
barge_in_profile ? "barge_in" : "call");
return true;
}
bool VoiceDsp::PrewarmEchoCancellation()
{
if (aec_ != nullptr) {
return true;
}
// aec_create is opportunistic: it takes whatever internal RAM is free at
// that instant (observed 2.6-12.4 KB across boots) and the handle then
// lives for the whole session. Created lazily at the first TTS it once
// grabbed 12 KB exactly as the dropped websocket released its buffers —
// after that no TLS reconnect could ever allocate again. Placement is
// speed-neutral on this board (~50 ms/frame measured both ways), so the
// state belongs in PSRAM: create it ONCE at boot, before the WiFi driver
// exists, with guard blocks squatting on internal RAM so esp-sr's greedy
// pass lands in PSRAM, then release the guards.
// Guard blocks sized to the CURRENT largest free block, not a fixed
// size: the boot heap is a handful of region tails and DMA-pool chunks,
// and a fixed-8KB loop bailed on the first sub-8KB fragment while
// esp-sr's many small allocations then filled 24.9 KB of exactly those
// fragments — leaving the WiFi driver so dry that phy_track_pll_init's
// esp_timer_create aborted the boot.
constexpr uint32_t kGuardCaps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT;
constexpr size_t kInternalFloorBytes = 8 * 1024;
constexpr size_t kMinimumGuardBytes = 1024;
constexpr size_t kGuardHeadroomBytes = 256;
std::array<void*, 32> guards{};
size_t guard_count = 0;
size_t guarded_bytes = 0;
while (guard_count < guards.size() &&
heap_caps_get_free_size(kGuardCaps) > kInternalFloorBytes) {
const size_t largest =
heap_caps_get_largest_free_block(kGuardCaps);
if (largest < kMinimumGuardBytes) {
break;
}
const size_t take = largest - kGuardHeadroomBytes;
void* block = heap_caps_malloc(take, kGuardCaps);
if (block == nullptr) {
break;
}
guards[guard_count++] = block;
guarded_bytes += take;
}
ESP_LOGI(kTag,
"AEC prewarm guards=%u held=%u free=%u largest=%u",
static_cast<unsigned>(guard_count),
static_cast<unsigned>(guarded_bytes),
static_cast<unsigned>(heap_caps_get_free_size(kGuardCaps)),
static_cast<unsigned>(
heap_caps_get_largest_free_block(kGuardCaps)));
const bool enabled = EnableEchoCancellation(true);
for (size_t index = 0; index < guard_count; ++index) {
heap_caps_free(guards[index]);
}
if (!enabled) {
ESP_LOGE(kTag, "AEC prewarm failed");
return false;
}
Reset();
return true;
}
void VoiceDsp::SuspendEchoCancellation()
{
// Keep the adaptive filter warm across TTS turns. Reset() clears only
// frame accumulators and AGC state; the ESP AEC handle retains its learned
// acoustic path.
if (aec_ != nullptr) {
Reset();
}
}
void VoiceDsp::DisableEchoCancellation()
{
if (aec_ != nullptr) {
aec_destroy(aec_);
aec_ = nullptr;
}
aec_chunk_samples_ = 0;
barge_in_profile_ = false;
mic_count_ = 0;
ref_count_ = 0;
clean_count_ = 0;
}
void VoiceDsp::Reset()
{
mic_count_ = 0;
ref_count_ = 0;
clean_count_ = 0;
if (aec_chunk_samples_ > 0) {
clean_count_ = static_cast<size_t>(aec_chunk_samples_);
std::fill_n(clean_acc_.data(), clean_count_, 0);
}
envelope_ = 0.08f;
gain_ = 1.0f;
}
bool VoiceDsp::Process(
const int16_t* microphone,
const int16_t* reference,
bool echo_cancellation,
int16_t* output,
size_t sample_count,
int16_t* wake_tap)
{
if (microphone == nullptr || output == nullptr ||
sample_count != kFrameSamples) {
return false;
}
bool valid = true;
if (echo_cancellation) {
valid = reference != nullptr &&
ProcessAec(
microphone, reference, output, sample_count);
} else {
std::memcpy(
output,
microphone,
sample_count * sizeof(int16_t));
}
if (!valid) {
return false;
}
if (wake_tap != nullptr) {
std::memcpy(
wake_tap, output, sample_count * sizeof(int16_t));
}
ProcessNsAndAgc(
output,
sample_count,
echo_cancellation && barge_in_profile_);
return true;
}
bool VoiceDsp::ProcessAec(
const int16_t* microphone,
const int16_t* reference,
int16_t* output,
size_t sample_count)
{
if (aec_ == nullptr ||
mic_count_ + sample_count > mic_acc_.size() ||
ref_count_ + sample_count > ref_acc_.size()) {
return false;
}
std::memcpy(
mic_acc_.data() + mic_count_,
microphone,
sample_count * sizeof(int16_t));
std::memcpy(
ref_acc_.data() + ref_count_,
reference,
sample_count * sizeof(int16_t));
mic_count_ += sample_count;
ref_count_ += sample_count;
const size_t chunk =
static_cast<size_t>(aec_chunk_samples_);
while (mic_count_ >= chunk && ref_count_ >= chunk) {
if (clean_count_ + chunk > clean_acc_.size()) {
return false;
}
aec_process(
aec_,
mic_acc_.data(),
ref_acc_.data(),
aec_chunk_.data());
std::memmove(
mic_acc_.data(),
mic_acc_.data() + chunk,
(mic_count_ - chunk) * sizeof(int16_t));
std::memmove(
ref_acc_.data(),
ref_acc_.data() + chunk,
(ref_count_ - chunk) * sizeof(int16_t));
mic_count_ -= chunk;
ref_count_ -= chunk;
std::memcpy(
clean_acc_.data() + clean_count_,
aec_chunk_.data(),
chunk * sizeof(int16_t));
clean_count_ += chunk;
// Hand the core back between chunks. This loop runs 3-4 times per 60 ms
// frame on the capture task at priority 8, and aec_process() never
// blocks, so without this the idle task on this core gets no runtime for
// as long as duplex is active and the task watchdog fires. taskYIELD()
// would not help: the idle task sits at priority 0 and only a blocking
// delay lets it run. The previous firmware carried the same one-tick
// yield in the same position for the same reason. At 1000 Hz a tick is
// 1 ms, so the cost is ~4 ms per frame against a 60 ms budget.
vTaskDelay(1);
}
if (clean_count_ < sample_count) {
return false;
}
std::memcpy(
output,
clean_acc_.data(),
sample_count * sizeof(int16_t));
std::memmove(
clean_acc_.data(),
clean_acc_.data() + sample_count,
(clean_count_ - sample_count) * sizeof(int16_t));
clean_count_ -= sample_count;
return true;
}
void VoiceDsp::ProcessNsAndAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile)
{
// Full NS remains active for normal capture and calls. During TTS it can
// reshape residual echo and costs CPU, so barge-in uses high-performance
// AEC plus the conservative gate/AGC below.
if (ns_ != nullptr && !barge_in_profile) {
for (size_t offset = 0;
offset + kNsFrameSamples <= sample_count;
offset += kNsFrameSamples) {
ns_process(
ns_, samples + offset, ns_frame_.data());
std::memcpy(
samples + offset,
ns_frame_.data(),
kNsFrameSamples * sizeof(int16_t));
}
}
ApplyAgc(samples, sample_count, barge_in_profile);
}
void VoiceDsp::ApplyAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile)
{
int32_t peak = 0;
uint64_t energy = 0;
for (size_t index = 0; index < sample_count; ++index) {
const int32_t value = samples[index];
peak = std::max(peak, std::abs(value));
energy += static_cast<uint64_t>(value * value);
}
const float peak_normalized =
static_cast<float>(peak) / 32768.0f;
const float rms = std::sqrt(
static_cast<float>(energy) /
static_cast<float>(sample_count)) / 32768.0f;
if (rms < 0.004f && peak_normalized < 0.015f) {
const float attenuation = barge_in_profile
? kBargeInNoiseGateAttenuation
: kNoiseGateAttenuation;
for (size_t index = 0; index < sample_count; ++index) {
samples[index] =
static_cast<int16_t>(samples[index] * attenuation);
}
return;
}
const float alpha =
peak_normalized > envelope_ ? 0.45f : 0.12f;
envelope_ += alpha * (peak_normalized - envelope_);
envelope_ = std::max(envelope_, 0.01f);
const float target = std::clamp(
kTargetPeak / envelope_,
kMinimumGain,
barge_in_profile
? kBargeInMaximumGain
: kMaximumGain);
gain_ += 0.18f * (target - gain_);
for (size_t index = 0; index < sample_count; ++index) {
const float value = std::clamp(
static_cast<float>(samples[index]) * gain_,
-32768.0f,
32767.0f);
samples[index] = static_cast<int16_t>(value);
}
}
} // namespace borla

84
main/audio/voice_dsp.h Normal file
View File

@@ -0,0 +1,84 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <esp_aec.h>
#include <esp_ns.h>
namespace borla {
class VoiceDsp final {
public:
static constexpr size_t kFrameSamples = 960;
~VoiceDsp();
bool InitializeNoiseSuppression();
// Creates the AEC state once at boot (guarded so it lands in PSRAM) and
// leaves it suspended. See the implementation for why lazy creation was
// a session-killer.
bool PrewarmEchoCancellation();
bool EnableEchoCancellation(bool barge_in_profile);
void SuspendEchoCancellation();
void DisableEchoCancellation();
void Reset();
// wake_tap, when provided, receives the post-AEC pre-NS/AGC samples —
// the signal WakeNet should hear. The AGC pumps during double-talk and a
// gain-chopped phrase defeats the detector.
bool Process(
const int16_t* microphone,
const int16_t* reference,
bool echo_cancellation,
int16_t* output,
size_t sample_count,
int16_t* wake_tap = nullptr);
// Diagnostics. Cheap accessors so the frame statistics can report what the
// DSP is actually doing rather than what the policy asked for.
bool EchoCancellationActive() const { return aec_ != nullptr; }
bool NoiseSuppressionActive() const { return ns_ != nullptr; }
// NS is deliberately skipped in the barge-in profile; see ProcessNsAndAgc.
bool BargeInProfile() const { return barge_in_profile_; }
int AecChunkSamples() const { return aec_chunk_samples_; }
float AgcGain() const { return gain_; }
float AgcEnvelope() const { return envelope_; }
private:
static constexpr size_t kAccumulatorCapacity = 4096;
static constexpr size_t kMaximumAecChunk = 1024;
static constexpr size_t kNsFrameSamples = 160;
bool ProcessAec(
const int16_t* microphone,
const int16_t* reference,
int16_t* output,
size_t sample_count);
void ProcessNsAndAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile);
void ApplyAgc(
int16_t* samples,
size_t sample_count,
bool barge_in_profile);
aec_handle_t* aec_ = nullptr;
ns_handle_t ns_ = nullptr;
int aec_chunk_samples_ = 0;
bool barge_in_profile_ = false;
std::array<int16_t, kAccumulatorCapacity> mic_acc_{};
std::array<int16_t, kAccumulatorCapacity> ref_acc_{};
std::array<int16_t, kAccumulatorCapacity> clean_acc_{};
std::array<int16_t, kMaximumAecChunk> aec_chunk_{};
std::array<int16_t, kNsFrameSamples> ns_frame_{};
size_t mic_count_ = 0;
size_t ref_count_ = 0;
size_t clean_count_ = 0;
float envelope_ = 0.08f;
float gain_ = 1.0f;
};
} // namespace borla

View File

@@ -0,0 +1,36 @@
#pragma once
#include "core/runtime_state.h"
#include <cstddef>
#include <cstdint>
namespace borla {
class IVoiceFrameProcessor {
public:
virtual ~IVoiceFrameProcessor() = default;
virtual void ApplyPolicy(AudioPolicy policy) = 0;
virtual bool Process(
AudioPolicy policy,
const int16_t* input,
size_t sample_count,
int16_t* output,
size_t output_capacity) = 0;
};
class IPlaybackReferenceSink {
public:
virtual ~IPlaybackReferenceSink() = default;
virtual void OnPlaybackReference(
const int16_t* samples,
size_t sample_count) = 0;
// Called when a new playback session begins. Frames queued for the
// previous session are acoustically unrelated to what the microphone is
// about to hear, and leaving them in the ring offsets every reference by
// however many were stranded. Emptying it here phase-locks the reference
// stream to the session that is actually about to reach the speaker.
virtual void ResetPlaybackReference() = 0;
};
} // namespace borla

View File

@@ -0,0 +1,969 @@
#include "audio/voice_frontend.h"
#include "core/task_stack_budget.h"
#include <esp_log.h>
#include <esp_timer.h>
#include <freertos/idf_additions.h>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace borla {
namespace {
constexpr const char* kTag = "VoiceFrontend2";
} // namespace
bool VoiceFrontend::Initialize()
{
std::lock_guard<std::mutex> lock(processor_mutex_);
if (initialized_) {
return true;
}
buffers_ = MakePsramObject<ScratchBuffers>();
if (!buffers_) {
ESP_LOGE(kTag, "voice scratch buffer allocation failed");
return false;
}
if (!dsp_.InitializeNoiseSuppression()) {
buffers_.reset();
return false;
}
// Boot runs before the WiFi driver exists, so this is the one moment the
// internal heap is rich and unfragmented. Non-fatal: without the prewarm
// the first duplex turn creates the state mid-conversation and steals the
// websocket's reconnect budget.
dsp_.PrewarmEchoCancellation();
wake_queue_ = xQueueCreateWithCaps(
kWakeQueueFrames,
kFrameSamples * sizeof(int16_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (wake_queue_ == nullptr) {
ESP_LOGE(kTag, "wake queue allocation failed");
buffers_.reset();
return false;
}
const BaseType_t created = xTaskCreatePinnedToCoreWithCaps(
&VoiceFrontend::WakeScanTaskEntry,
"wake_scan2",
kWakeScanStackBytes,
this,
task_priority::kAudioCodec,
&wake_task_,
1,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (created != pdPASS) {
ESP_LOGE(kTag, "wake scan task creation failed");
vQueueDeleteWithCaps(wake_queue_);
wake_queue_ = nullptr;
buffers_.reset();
return false;
}
ESP_LOGI(kTag,
"wake scan task started core=1 stack_bytes=%u queue=%u",
static_cast<unsigned>(kWakeScanStackBytes),
static_cast<unsigned>(kWakeQueueFrames));
initialized_ = true;
return true;
}
void VoiceFrontend::WakeScanTaskEntry(void* context)
{
static_cast<VoiceFrontend*>(context)->RunWakeScan();
}
[[noreturn]] void VoiceFrontend::RunWakeScan()
{
// PSRAM stack is fine here: WakeNet's weights already live in PSRAM and
// the detect cost is dominated by the model math, not stack traffic.
std::array<int16_t, kFrameSamples> frame{};
while (true) {
if (wake_reset_pending_.exchange(
false, std::memory_order_acq_rel)) {
wake_accumulator_count_ = 0;
}
if (xQueueReceive(
wake_queue_, frame.data(), pdMS_TO_TICKS(100)) ==
pdTRUE) {
FeedWakeWord(frame.data(), frame.size());
}
}
}
void VoiceFrontend::QueueWakeAudio(const int16_t* samples)
{
if (wake_queue_ == nullptr) {
return;
}
// Zero timeout: the capture task must never block on the scanner. A full
// queue means the scanner is more than 360 ms behind — dropping is the
// only option that keeps the microphone stream (and AEC alignment) alive.
xQueueSend(wake_queue_, samples, 0);
}
void VoiceFrontend::SetEventPublisher(IEventPublisher* publisher)
{
publisher_.store(publisher);
}
bool VoiceFrontend::EnsureWakeWordLoaded()
{
if (wake_word_.initialized()) {
return true;
}
// esp_srmodel_init() + create() reads the model partition and takes ~110 ms
// on this board. It happens at most once per boot; the previous code ran it
// on every policy change that needed the wake word, i.e. twice per
// conversation turn, while holding processor_mutex_. That stalled the
// capture task for two whole 60 ms frames right as TTS playback started,
// which both blinded the wake word during the exact window a child would
// use it and scrambled the AEC mic/reference phase so the speaker echo
// reached the server uncancelled. The previous firmware kept the model
// resident for the whole uptime and only toggled a flag; so do we.
std::lock_guard<std::mutex> lock(wake_mutex_);
return wake_word_.Initialize();
}
void VoiceFrontend::ReleaseWakeWord()
{
std::lock_guard<std::mutex> lock(processor_mutex_);
std::lock_guard<std::mutex> wake_lock(wake_mutex_);
if (!wake_word_.initialized()) {
return;
}
wake_word_.Deinitialize();
wake_reset_pending_.store(true, std::memory_order_release);
ESP_LOGI(kTag, "WakeNet released");
}
void VoiceFrontend::SetWakeWordEnabled(bool enabled)
{
std::lock_guard<std::mutex> lock(processor_mutex_);
if (wake_word_enabled_ == enabled) {
return;
}
wake_word_enabled_ = enabled;
if (!enabled) {
// Keep the model loaded; only stop feeding it. Destroying it here is
// what made the reload expensive in the first place.
wake_reset_pending_.store(true, std::memory_order_release);
} else if (initialized_ && WakeRequired(policy_) &&
!EnsureWakeWordLoaded()) {
ESP_LOGE(kTag, "WakeNet unavailable after remote enable");
}
ESP_LOGI(kTag, "remote wake word=%d", enabled ? 1 : 0);
}
void VoiceFrontend::ApplyPolicy(AudioPolicy policy)
{
bool wake_ready = false;
bool aec_active = false;
bool duplex_window_closed = false;
// The mutex is scoped so the log lines below are written with it released.
// A ~150 character line takes on the order of 10 ms to drain at the console
// baud rate, and the capture task blocks on this same mutex once per 60 ms
// frame; holding it across the write is the same class of stall that the
// per-turn WakeNet reload used to cause.
{
std::lock_guard<std::mutex> lock(processor_mutex_);
if (!initialized_ || policy_ == policy) {
policy_ = policy;
return;
}
if (WakeRequired(policy) && !EnsureWakeWordLoaded()) {
ESP_LOGE(kTag, "WakeNet unavailable for policy=%s",
ToString(policy));
}
if (!WakeRequired(policy)) {
// The model stays resident; only the accumulator is dropped so the
// next duplex window does not start mid-phrase. The accumulator
// is owned by the wake-scan task, so hand it a reset flag rather
// than racing it.
wake_reset_pending_.store(true, std::memory_order_release);
}
const bool old_aec_required = AecRequired(policy_);
const bool new_aec_required = AecRequired(policy);
if (new_aec_required) {
const bool barge_in_profile =
policy != AudioPolicy::kCallDuplex;
if (!dsp_.EnableEchoCancellation(barge_in_profile)) {
ESP_LOGE(kTag, "AEC unavailable for policy=%s",
ToString(policy));
}
} else {
dsp_.SuspendEchoCancellation();
}
if (old_aec_required != new_aec_required) {
ClearReference();
}
if (policy == AudioPolicy::kConversationCapture ||
policy_ == AudioPolicy::kConversationCapture) {
vad_.Reset();
self_capture_hangover_ = 0;
}
if (policy != AudioPolicy::kBargeInDuplex) {
// The policy change means the control plane already decided the
// turn; a pending candidate must not publish a stale verdict on
// top. leak_ratio_ intentionally survives — the echo path barely
// moves between sessions, so the next duplex window starts with a
// trained gate instead of re-learning through a dirty one.
candidate_active_ = false;
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
uplink_pass_until_us_ = 0;
probe_silence_frames_ = 0;
candidate_deadline_us_ = 0;
candidate_rearm_until_us_ = 0;
candidate_needs_quiet_ = false;
window_ref_active_frames_ = 0;
previous_reference_rms_[0] = 0;
previous_reference_rms_[1] = 0;
}
policy_ = policy;
wake_ready = wake_word_.initialized();
aec_active = new_aec_required;
duplex_window_closed = old_aec_required && !new_aec_required;
}
// Debug: the engine's one-line summary (requested/effective/wake/barge)
// already covers every policy change at INFO.
ESP_LOGD(kTag, "policy=%s wake=%d aec=%d",
ToString(policy),
wake_ready ? 1 : 0,
aec_active ? 1 : 0);
if (duplex_window_closed) {
// One line per duplex window. aec_reference_misses is the number that
// matters: every miss is a 60 ms frame the AEC could not cancel, i.e.
// a frame of the device's own TTS that would have reached the server.
LogMetrics("duplex window closed");
}
}
void VoiceFrontend::LogMetrics(const char* reason) const
{
// Snapshot under the spinlock, format outside it.
const VoiceFrontendMetrics snapshot = Metrics();
ESP_LOGI(kTag,
"voice metrics (%s) frames=%lu ref_frames=%lu ref_drops=%lu "
"ref_trims=%lu "
"ref_misses=%lu uplink_suppressed=%lu self_capture=%lu "
"gated=%lu cand=%lu cand_local_rej=%lu cand_timeout=%lu "
"wake=%lu self_wake=%lu "
"vad_stops=%lu dsp_fail=%lu",
reason,
static_cast<unsigned long>(snapshot.processed_frames),
static_cast<unsigned long>(snapshot.reference_frames),
static_cast<unsigned long>(snapshot.reference_drops),
static_cast<unsigned long>(snapshot.reference_trims),
static_cast<unsigned long>(snapshot.aec_reference_misses),
static_cast<unsigned long>(snapshot.uplink_suppressions),
static_cast<unsigned long>(snapshot.self_capture_suppressions),
static_cast<unsigned long>(snapshot.residual_gated),
static_cast<unsigned long>(snapshot.barge_in_candidates),
static_cast<unsigned long>(snapshot.barge_in_local_rejects),
static_cast<unsigned long>(snapshot.barge_in_timeouts),
static_cast<unsigned long>(snapshot.wake_detections),
static_cast<unsigned long>(snapshot.self_wake_suppressions),
static_cast<unsigned long>(snapshot.vad_stops),
static_cast<unsigned long>(snapshot.dsp_failures));
}
bool VoiceFrontend::Process(
AudioPolicy policy,
const int16_t* input,
size_t sample_count,
int16_t* output,
size_t output_capacity)
{
if (input == nullptr || output == nullptr ||
sample_count != kFrameSamples ||
output_capacity < kFrameSamples) {
return false;
}
std::lock_guard<std::mutex> lock(processor_mutex_);
std::array<int16_t, kFrameSamples> reference{};
const bool has_reference = PopReference(reference.data());
const uint32_t microphone_rms = FrameRms(input, sample_count);
const uint32_t reference_rms =
has_reference ? FrameRms(reference.data(), reference.size()) : 0;
// Authoritative "is our own speaker running right now" test, shared by the
// VAD gate below and the wake-word self-trigger guard further down. Derived
// from the playback task's per-frame callback rather than from the energy of
// a popped reference frame, because the reference ring is empty whenever it
// has just been cleared or trimmed — and then the energy test silently
// reports "quiet" while the speaker is at full volume.
const uint64_t now_us =
static_cast<uint64_t>(esp_timer_get_time());
const uint64_t last_playback_us =
last_playback_frame_us_.load(std::memory_order_relaxed);
const bool speaker_active =
last_playback_us != 0 &&
now_us - last_playback_us < kSpeakerActiveWindowUs;
bool processed = true;
bool uplink_suppressed = false;
if (policy == AudioPolicy::kConversationCapture) {
processed = dsp_.Process(
input, nullptr, false, output, sample_count);
// Local prompts play while this policy is active — the wake
// acknowledgement "我在" is emitted immediately after the device enters
// listening — and this policy deliberately runs without AEC, so the
// microphone hears them at full level. Uploading that feeds the
// server's ASR the device's own voice, so the frames are dropped and
// the VAD is held in reset while the speaker runs. The server owns
// the authoritative auto-stop (listen mode="auto"), so a turn cannot
// hang here when the child stays quiet.
if (speaker_active) {
self_capture_hangover_ = kSelfCaptureHangoverFrames;
}
if (self_capture_hangover_ > 0) {
--self_capture_hangover_;
vad_.Reset();
uplink_suppressed = true;
portENTER_CRITICAL(&metrics_lock_);
metrics_.self_capture_suppressions++;
portEXIT_CRITICAL(&metrics_lock_);
} else if (processed) {
// Observability only. The turn end is owned by the server
// (listen mode="auto", protocols/websocket_protocol.md): its VAD
// pads and finalizes the ASR segment. Publishing a local stop
// here used to close the turn early — WakeNet fires mid-phrase,
// so the wake word's own tail (>=2 loud frames = 120 ms) read as
// "speech started" and 13 quiet frames later the device tore the
// listening window down before the child had said a word.
const VoiceActivityResult vad =
vad_.Process(output, sample_count);
// Two short lines per turn. Kept on this task on purpose: the
// instant a turn opens and closes is exactly what needs a
// timestamp, and aggregating it would lose that.
if (vad == VoiceActivityResult::kSpeechStarted) {
ESP_LOGI(kTag, "vad speech_started rms=%lu",
static_cast<unsigned long>(vad_.LastRms()));
} else if (vad == VoiceActivityResult::kSpeechEnded) {
ESP_LOGI(kTag, "vad speech_ended rms=%lu",
static_cast<unsigned long>(vad_.LastRms()));
portENTER_CRITICAL(&metrics_lock_);
metrics_.vad_stops++;
portEXIT_CRITICAL(&metrics_lock_);
}
}
} else if (AecRequired(policy)) {
processed = dsp_.Process(
input,
reference.data(),
true,
output,
sample_count,
buffers_->wake_tap.data());
if (processed &&
policy == AudioPolicy::kBargeInDuplex &&
UpdateBargeInGate(
FrameRms(output, sample_count),
reference_rms,
has_reference,
speaker_active,
now_us)) {
uplink_suppressed = true;
portENTER_CRITICAL(&metrics_lock_);
metrics_.residual_gated++;
portEXIT_CRITICAL(&metrics_lock_);
}
if (processed && !uplink_suppressed &&
!has_reference && speaker_active) {
// The speaker is running but the reference ring was empty for this
// frame, so the AEC subtracted nothing and the frame still carries
// the full echo. Uploading it makes the server's ASR transcribe the
// device's own TTS and raise a barge-in against itself. Drop it from
// the uplink but keep it for the local wake word below, which is
// exactly the path that has to survive so "你好波乐" can still
// interrupt playback.
//
// speaker_active is load-bearing. This used to suppress on "no
// reference" alone — but an empty reference ring is overwhelmingly
// the signature of "nothing is playing", not of a missed frame. In
// kCallDuplex the far end is silent for most of a call, so no
// playback frame ever arrives, the ring stays empty, and every
// single microphone frame was dropped: the uplink was mute for the
// whole call. kWakeWordDuplex and the tail of a kBargeInDuplex turn
// had the same hole. No playback means no echo, so those frames are
// safe to send and must be sent — that silence was the child's turn.
uplink_suppressed = true;
portENTER_CRITICAL(&metrics_lock_);
metrics_.aec_reference_misses++;
portEXIT_CRITICAL(&metrics_lock_);
}
// Both duplex flavors feed WakeNet the AEC-cleaned output: it is the
// only interrupt in kWakeWordDuplex (no uplink there), and the fast
// "你好播乐 cuts the reply" path in kBargeInDuplex — natural speech
// there still goes through server VAD/ASR arbitration. Fed from the
// pre-AGC tap, not `output`: the AGC swings 0.9-1.8 during
// music+speech double-talk and the gain steps chop the phrase.
// A missing playback reference must not create a blind WakeNet frame:
// with a zero reference the DSP output is still a usable microphone
// fallback, and dropping it could cut an arbitrary part of the wake
// phrase.
if (processed && WakeRequired(policy)) {
QueueWakeAudio(buffers_->wake_tap.data());
}
} else {
std::memcpy(
output, input, sample_count * sizeof(int16_t));
if (WakeRequired(policy)) {
// Same hazard as the VAD gate: idle-mode prompts (idle_check,
// alarms, the shutdown prompt) reach the microphone unattenuated
// because this path has no AEC, and WakeNet will happily trigger on
// the device's own voice. The previous firmware hit this in the
// field (2026-07-03: idle_check "你还在吗小朋友" self-triggering)
// and muted detection around the prompt for the same reason.
if (speaker_active || self_capture_hangover_ > 0) {
if (self_capture_hangover_ > 0) {
--self_capture_hangover_;
}
if (speaker_active) {
self_capture_hangover_ = kSelfCaptureHangoverFrames;
}
portENTER_CRITICAL(&metrics_lock_);
metrics_.self_wake_suppressions++;
portEXIT_CRITICAL(&metrics_lock_);
} else {
QueueWakeAudio(output);
}
}
}
AccumulateFrameStats(
policy,
microphone_rms,
FrameRms(output, sample_count),
reference_rms,
has_reference);
portENTER_CRITICAL(&metrics_lock_);
metrics_.processed_frames++;
if (!processed) {
metrics_.dsp_failures++;
}
if (uplink_suppressed) {
metrics_.uplink_suppressions++;
}
portEXIT_CRITICAL(&metrics_lock_);
// Returning false makes CapturePipeline skip the encode/uplink for this
// frame. The wake word has already consumed it above.
return processed && !uplink_suppressed;
}
void VoiceFrontend::OnPlaybackReference(
const int16_t* samples,
size_t sample_count)
{
// Stamp first: this call means a frame is on its way to the DAC, which is
// the fact the capture side needs. Whether it also lands in the reference
// ring is a separate question.
last_playback_frame_us_.store(
static_cast<uint64_t>(esp_timer_get_time()),
std::memory_order_relaxed);
std::array<int16_t, kFrameSamples> converted{};
if (!reference_converter_.Convert(
samples,
sample_count,
converted.data(),
converted.size())) {
return;
}
uint32_t discarded = 0;
{
std::lock_guard<std::mutex> lock(reference_mutex_);
if (!buffers_) {
return;
}
// Trim before pushing so occupancy after this call never exceeds
// kReferenceMaxLeadFrames. See the constant for why the old
// drop-one-when-full rule pinned the skew at its maximum instead of
// bounding it.
while (reference_count_ >= kReferenceMaxLeadFrames) {
reference_read_ =
(reference_read_ + 1) % kReferenceDepth;
reference_count_--;
discarded++;
}
buffers_->reference_ring[reference_write_] = converted;
reference_write_ =
(reference_write_ + 1) % kReferenceDepth;
reference_count_++;
}
if (discarded != 0) {
// The reference just jumped a frame relative to the echo still in
// flight; the AEC runs misaligned until it re-adapts and its residual
// bursts over the floor. Field run: 15 trims, ~17 false candidates,
// each pausing playback 0.4-1.5 s. Hold candidates while it settles.
alignment_settle_until_us_.store(
static_cast<uint64_t>(esp_timer_get_time()) + kAlignmentSettleUs,
std::memory_order_relaxed);
}
portENTER_CRITICAL(&metrics_lock_);
metrics_.reference_frames++;
if (discarded != 0) {
metrics_.reference_drops += discarded;
metrics_.reference_trims++;
}
portEXIT_CRITICAL(&metrics_lock_);
}
void VoiceFrontend::ResetPlaybackReference()
{
ClearReference();
}
VoiceFrontendMetrics VoiceFrontend::Metrics() const
{
portENTER_CRITICAL(&metrics_lock_);
const VoiceFrontendMetrics snapshot = metrics_;
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
bool VoiceFrontend::WakeRequired(AudioPolicy policy) const
{
// kBargeInDuplex feeds WakeNet too, so "你好播乐" interrupts a playing
// reply (product requirement). This was disabled while AEC+WakeNet
// measured 68 ms per 60 ms frame — but that number had Opus encode on the
// same task. With the encoder on core 1 and complexity 3 the duplex
// process step averages 10-15 ms (max ~37 ms); WakeNet's ~14 ms fits the
// budget. Watch period_avg in the frame stats: if it climbs past ~65 ms
// the fallback is a dedicated core-1 wake task (audit option R7).
// Self-trigger safety: the feed is post-AEC (echo at -10..-20 dB), and a
// rare false fire lands in the state machine as an ordinary barge-in.
//
// kWakeWordDuplex keeps it for the no-uplink prompt/alert windows where
// the wake word is the only interrupt.
return wake_word_enabled_ &&
(policy == AudioPolicy::kWakeWordOnly ||
policy == AudioPolicy::kWakeWordDuplex ||
policy == AudioPolicy::kBargeInDuplex);
}
bool VoiceFrontend::AecRequired(AudioPolicy policy) const
{
return policy == AudioPolicy::kWakeWordDuplex ||
policy == AudioPolicy::kBargeInDuplex ||
policy == AudioPolicy::kCallDuplex;
}
void VoiceFrontend::FeedWakeWord(
const int16_t* samples,
size_t sample_count)
{
// Wake-scan task only. The lock serializes Detect against the model
// being loaded (ApplyPolicy) or released (BLE provisioning).
std::lock_guard<std::mutex> lock(wake_mutex_);
if (!buffers_ || !wake_word_.initialized() ||
wake_word_.ChunkSamples() == 0) {
return;
}
auto& wake_accumulator = buffers_->wake_accumulator;
const uint64_t now_ms = static_cast<uint64_t>(
esp_timer_get_time() / 1000);
if (now_ms < wake_cooldown_until_ms_) {
return;
}
if (wake_accumulator_count_ + sample_count >
wake_accumulator.size()) {
wake_accumulator_count_ = 0;
}
std::memcpy(
wake_accumulator.data() + wake_accumulator_count_,
samples,
sample_count * sizeof(int16_t));
wake_accumulator_count_ += sample_count;
const size_t chunk = wake_word_.ChunkSamples();
while (wake_accumulator_count_ >= chunk) {
const bool detected = wake_word_.Detect(
wake_accumulator.data(), chunk);
std::memmove(
wake_accumulator.data(),
wake_accumulator.data() + chunk,
(wake_accumulator_count_ - chunk) * sizeof(int16_t));
wake_accumulator_count_ -= chunk;
if (detected) {
// ConversationCapture does not feed WakeNet. A frame counter used
// to freeze for the whole user question, then blind the first two
// seconds of the following TTS reply. Wall time keeps the intended
// duplicate-trigger protection without carrying that blind spot.
wake_cooldown_until_ms_ = now_ms + kWakeCooldownMs;
portENTER_CRITICAL(&metrics_lock_);
metrics_.wake_detections++;
portEXIT_CRITICAL(&metrics_lock_);
Publish(AppEvent::Make(
AppEventType::kWakeWordDetected));
wake_accumulator_count_ = 0;
break;
}
}
}
void VoiceFrontend::ResolveCandidateLocked(
AppEventType verdict,
const char* reason,
uint64_t now_us)
{
candidate_active_ = false;
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
probe_silence_frames_ = 0;
candidate_deadline_us_ = 0;
// No new candidate until the energy has both cooled off in time and
// dipped below the leak line at least once — see kCandidateRearmUs.
candidate_rearm_until_us_ = now_us + kCandidateRearmUs;
candidate_needs_quiet_ = true;
ESP_LOGI(kTag, "barge-in candidate %s", reason);
Publish(AppEvent::Make(verdict));
}
bool VoiceFrontend::UpdateBargeInGate(
uint32_t out_rms,
uint32_t reference_rms,
bool has_reference,
bool speaker_active,
uint64_t now_us)
{
if (candidate_active_) {
if (now_us >= candidate_deadline_us_) {
// Neither the server nor the probe decided. Resume playback; the
// reducer drops this if the server confirmed meanwhile.
portENTER_CRITICAL(&metrics_lock_);
metrics_.barge_in_timeouts++;
portEXIT_CRITICAL(&metrics_lock_);
// Sustained energy the server chose not to act on is most likely
// a raised noise floor; lift the line so it stops re-triggering.
leak_ratio_ = std::min(leak_ratio_ * 1.25F, kLeakMaximum);
ResolveCandidateLocked(
AppEventType::kBargeInRejected, "timed out, resuming",
now_us);
} else if (!speaker_active) {
// Playback paused, so the echo source is gone: whatever the
// microphone hears now is ground truth.
if (out_rms < kProbeSpeechFloorRms) {
if (++probe_silence_frames_ >= kProbeSilenceFrames) {
// The energy vanished with the speaker — it was residual.
// Raise the leak line so the same level does not trigger
// again, and resume.
leak_ratio_ = std::min(
leak_ratio_ * 1.5F, kLeakMaximum);
portENTER_CRITICAL(&metrics_lock_);
metrics_.barge_in_local_rejects++;
portEXIT_CRITICAL(&metrics_lock_);
ResolveCandidateLocked(
AppEventType::kBargeInRejected,
"probe heard silence, resuming",
now_us);
}
} else {
// A voice that survives the pause is a real voice; it is now
// uploading clean. Leave the verdict to the server's STT.
probe_silence_frames_ = 0;
}
}
}
if (!speaker_active) {
// Speaker quiet (idle gap or candidate pause): no echo to gate, every
// frame belongs to the room. Upload freely.
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
return false;
}
if (!has_reference) {
// Full echo with nothing to subtract; the caller's reference-miss rule
// suppresses it. It carries no gate information either way.
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
return false;
}
// Residual lags the reference by the TX DMA depth (~1.5 frames), so the
// echo in this frame is explained by the loudest of the LAST THREE
// reference frames, not by the instantaneous one. Judged against the
// instantaneous value the per-frame ratio swung between ~0.1 and ~1.0
// with alignment jitter (field: out=1437 against ref=1450 one moment,
// out=787 against ref=7325 the next) — no single line covers that spread
// without also swallowing speech.
const uint32_t reference_peak = std::max(
{reference_rms,
previous_reference_rms_[0],
previous_reference_rms_[1]});
previous_reference_rms_[1] = previous_reference_rms_[0];
previous_reference_rms_[0] = reference_rms;
// Leak information only exists while the reference actually carries
// energy. In an inter-sentence TTS gap the ratio degenerates — training
// on it would drag the line to a clamp and blind the gate for the next
// sentence. Gap frames are judged by the absolute floor alone.
const bool reference_active =
reference_peak >= kReferenceActiveRms;
if (reference_active &&
window_ref_active_frames_ < UINT16_MAX) {
window_ref_active_frames_++;
}
const float ratio =
static_cast<float>(out_rms) /
static_cast<float>(reference_peak != 0 ? reference_peak : 1);
if (!leak_seeded_ && reference_active) {
// Warm-up. The first reference frames PRECEDE their own echo (the
// reference is queued ~1.5 frames before the sound leaves the
// speaker), so seeding from the first frame reads out≈noise and pins
// the line at the floor — the field failure was candidates raised
// with leak=0.05 while ERL was 7 dB, each pausing playback for half a
// second. Instead: withhold the first kLeakWarmupFrames loud frames
// outright, remember the WORST ratio seen, and floor the seed. A high
// start self-corrects (the EMA below only trains on gated frames, so
// the line can walk down to truth but never up past speech); a low
// start is a trap.
leak_ratio_ = std::clamp(
std::max(leak_ratio_, ratio),
kLeakMinimum,
kLeakMaximum);
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
if (++leak_warmup_frames_ >= kLeakWarmupFrames) {
leak_ratio_ = std::max(leak_ratio_, kLeakSeedMinimum);
leak_seeded_ = true;
ESP_LOGI(kTag, "barge-in gate seeded leak=%.2f",
static_cast<double>(leak_ratio_));
}
return true;
}
float threshold = leak_seeded_
? leak_ratio_ * static_cast<float>(reference_peak) *
kLeakMargin
: 0.0F;
threshold = std::max(
threshold, static_cast<float>(kResidualFloorRms));
if (static_cast<float>(out_rms) <= threshold) {
// The dip below the line still re-arms the candidate gate either way.
candidate_needs_quiet_ = false;
consecutive_speech_frames_ = 0;
streak_peak_rms_ = 0;
if (now_us < uplink_pass_until_us_) {
// Inside an open voice segment this is an envelope dip, not
// residual: pass it so the server hears one contiguous
// utterance, and do NOT train the leak line on it — the frame
// may carry voice and training would drag the line upward.
return false;
}
// Explainable as residual: withhold it from the uplink, and train the
// leak line when the frame carries usable ratio information.
if (leak_seeded_ && reference_active) {
leak_ratio_ = std::clamp(
leak_ratio_ + kLeakAlpha * (ratio - leak_ratio_),
kLeakMinimum,
kLeakMaximum);
}
return true;
}
// Above the leak line: treat as the child speaking over the TTS. The frame
// flows to the server, and enough of them in a row raises the reversible
// pause. The leak estimate is deliberately not trained on these frames.
if (consecutive_speech_frames_ < 255) {
++consecutive_speech_frames_;
}
streak_peak_rms_ = std::max(streak_peak_rms_, out_rms);
if (consecutive_speech_frames_ >= kUplinkPassStreak) {
// Plausible voice: open (or extend) the segment window so the whole
// utterance reaches the server in one piece.
uplink_pass_until_us_ = now_us + kUplinkPassWindowUs;
}
// Candidates only where the pause-probe has value: gate seeded, the
// reference loud enough that echo could explain the energy, past the
// per-window AEC convergence holdoff, and not inside the re-adaptation
// window a reference trim opens. The trigger itself is shape-based:
// a sustained streak whose peak reached voice level — residual plateaus
// never peak, speech always does. Everything else still uploads and is
// the server's call.
if (!candidate_active_ &&
leak_seeded_ &&
reference_active &&
window_ref_active_frames_ >= kCandidateHoldoffFrames &&
now_us >= alignment_settle_until_us_.load(
std::memory_order_relaxed) &&
!candidate_needs_quiet_ &&
now_us >= candidate_rearm_until_us_ &&
consecutive_speech_frames_ >= kCandidateFrames &&
streak_peak_rms_ >= kCandidateStrongRms) {
candidate_active_ = true;
probe_silence_frames_ = 0;
candidate_deadline_us_ = now_us + kCandidateTimeoutUs;
portENTER_CRITICAL(&metrics_lock_);
metrics_.barge_in_candidates++;
portEXIT_CRITICAL(&metrics_lock_);
ESP_LOGI(kTag,
"barge-in candidate raised out_rms=%lu peak=%lu ref_rms=%lu "
"leak=%.2f",
static_cast<unsigned long>(out_rms),
static_cast<unsigned long>(streak_peak_rms_),
static_cast<unsigned long>(reference_rms),
static_cast<double>(leak_ratio_));
Publish(AppEvent::Make(AppEventType::kBargeInCandidate));
}
if (now_us < uplink_pass_until_us_) {
return false;
}
if (consecutive_speech_frames_ == 1 && !candidate_active_) {
// Single-frame excursions over the leak line are the signature of a
// syllable-onset residual spike (the adaptive filter under-cancels
// transients); real speech sustains. Withhold the first frame and
// pass from the second on — costs 60 ms of a genuine barge-in onset,
// which the server's ASR tolerates, and removes the last rhythmic
// residual ticks from the uplink.
return true;
}
return false;
}
bool VoiceFrontend::PopReference(int16_t* output)
{
std::lock_guard<std::mutex> lock(reference_mutex_);
if (!buffers_ || reference_count_ == 0) {
// Ring drained: the next burst must re-prime before serving, or the
// whole burst runs echo-misaligned (see reference_primed_).
reference_primed_ = false;
std::fill_n(output, kFrameSamples, 0);
return false;
}
if (!reference_primed_) {
if (reference_count_ < kReferencePrimeFrames) {
// The echo of these first frames is still inside the ~90 ms TX
// DMA and has not reached the microphone; serving them now would
// pair the AEC with a reference the echo lags by more than the
// 64 ms filter span. Field data: ref_depth >= ~2 tracked
// erl 16-20 dB, depth < 1 tracked erl <= 8 dB — every playback
// gap drained the ring and the following burst leaked rhythmic
// TTS residual into the uplink until depth recovered by luck.
std::fill_n(output, kFrameSamples, 0);
return false;
}
reference_primed_ = true;
}
std::memcpy(
output,
buffers_->reference_ring[reference_read_].data(),
kFrameSamples * sizeof(int16_t));
reference_read_ =
(reference_read_ + 1) % kReferenceDepth;
reference_count_--;
return true;
}
void VoiceFrontend::ClearReference()
{
std::lock_guard<std::mutex> lock(reference_mutex_);
reference_read_ = 0;
reference_write_ = 0;
reference_count_ = 0;
reference_primed_ = false;
}
uint32_t VoiceFrontend::FrameRms(
const int16_t* samples,
size_t sample_count)
{
if (samples == nullptr || sample_count == 0) {
return 0;
}
uint64_t energy = 0;
for (size_t index = 0; index < sample_count; ++index) {
const int32_t value = samples[index];
energy += static_cast<uint64_t>(value * value);
}
return static_cast<uint32_t>(
std::sqrt(
static_cast<double>(energy) /
static_cast<double>(sample_count)));
}
void VoiceFrontend::AccumulateFrameStats(
AudioPolicy policy,
uint32_t microphone_rms,
uint32_t processed_rms,
uint32_t reference_rms,
bool has_reference)
{
const uint64_t now_us =
static_cast<uint64_t>(esp_timer_get_time());
uint32_t depth = 0;
{
std::lock_guard<std::mutex> lock(reference_mutex_);
depth = static_cast<uint32_t>(reference_count_);
}
portENTER_CRITICAL(&metrics_lock_);
if (last_frame_us_ != 0 && now_us > last_frame_us_) {
const uint32_t period_us =
static_cast<uint32_t>(now_us - last_frame_us_);
frame_stats_.period_us_sum += period_us;
frame_stats_.period_us_max =
std::max(frame_stats_.period_us_max, period_us);
}
last_frame_us_ = now_us;
frame_stats_.frames++;
frame_stats_.policy = policy;
frame_stats_.microphone_rms_sum += microphone_rms;
frame_stats_.processed_rms_sum += processed_rms;
frame_stats_.reference_rms_sum += reference_rms;
frame_stats_.microphone_rms_peak =
std::max(frame_stats_.microphone_rms_peak, microphone_rms);
frame_stats_.processed_rms_peak =
std::max(frame_stats_.processed_rms_peak, processed_rms);
frame_stats_.reference_rms_peak =
std::max(frame_stats_.reference_rms_peak, reference_rms);
if (has_reference) {
frame_stats_.reference_present_frames++;
}
if (reference_rms >= kReferenceActiveRms) {
frame_stats_.reference_active_frames++;
}
frame_stats_.reference_depth_sum += depth;
frame_stats_.reference_depth_peak =
std::max(frame_stats_.reference_depth_peak, depth);
if (vad_.speech_active()) {
frame_stats_.vad_speech_frames++;
}
frame_stats_.agc_gain = dsp_.AgcGain();
frame_stats_.aec_active = dsp_.EchoCancellationActive();
frame_stats_.ns_active =
dsp_.NoiseSuppressionActive() && !dsp_.BargeInProfile();
frame_stats_.barge_in_profile = dsp_.BargeInProfile();
portEXIT_CRITICAL(&metrics_lock_);
}
VoiceFrameStats VoiceFrontend::ConsumeFrameStats()
{
portENTER_CRITICAL(&metrics_lock_);
const VoiceFrameStats snapshot = frame_stats_;
const AudioPolicy policy = frame_stats_.policy;
frame_stats_ = VoiceFrameStats{};
frame_stats_.policy = policy;
portEXIT_CRITICAL(&metrics_lock_);
return snapshot;
}
void VoiceFrontend::Publish(const AppEvent& event)
{
IEventPublisher* publisher = publisher_.load();
if (publisher == nullptr || !publisher->Publish(event)) {
ESP_LOGE(kTag, "event publish failed type=%s",
ToString(event.type));
}
}
} // namespace borla

392
main/audio/voice_frontend.h Normal file
View File

@@ -0,0 +1,392 @@
#pragma once
#include "audio/pcm_rate_converter.h"
#include "audio/voice_activity_detector.h"
#include "audio/voice_dsp.h"
#include "audio/voice_frame_processor.h"
#include "audio/wake_word_detector.h"
#include "core/psram_object.h"
#include "ports/event_publisher.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <mutex>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include <freertos/queue.h>
#include <freertos/task.h>
namespace borla {
struct VoiceFrontendMetrics {
uint32_t processed_frames = 0;
uint32_t reference_frames = 0;
uint32_t reference_drops = 0;
uint32_t reference_trims = 0;
uint32_t wake_detections = 0;
uint32_t aec_reference_misses = 0;
uint32_t uplink_suppressions = 0;
uint32_t self_capture_suppressions = 0;
uint32_t self_wake_suppressions = 0;
uint32_t vad_stops = 0;
uint32_t dsp_failures = 0;
// Barge-in gate: frames whose energy the leak line explained as residual
// echo and which were therefore withheld from the uplink.
uint32_t residual_gated = 0;
// Local barge-in candidates raised, and how they ended when the server
// did not decide them: probe heard silence after the pause (local reject)
// or nothing arrived at all (timeout).
uint32_t barge_in_candidates = 0;
uint32_t barge_in_local_rejects = 0;
uint32_t barge_in_timeouts = 0;
};
// Rolling per-frame measurements of the capture chain, accumulated by the
// capture task and drained by the diagnostics worker. The capture task only
// does arithmetic here: it must never write to the console, because a log line
// takes longer than the 60 ms frame budget it is already struggling to meet.
struct VoiceFrameStats {
uint32_t frames = 0;
uint32_t microphone_rms_sum = 0;
uint32_t processed_rms_sum = 0;
uint32_t reference_rms_sum = 0;
uint32_t microphone_rms_peak = 0;
uint32_t processed_rms_peak = 0;
uint32_t reference_rms_peak = 0;
uint32_t reference_present_frames = 0;
uint32_t reference_active_frames = 0;
uint32_t reference_depth_sum = 0;
uint32_t reference_depth_peak = 0;
uint32_t vad_speech_frames = 0;
uint32_t period_us_max = 0;
uint64_t period_us_sum = 0;
float agc_gain = 0.0F;
bool aec_active = false;
bool ns_active = false;
bool barge_in_profile = false;
AudioPolicy policy = AudioPolicy::kOff;
};
class VoiceFrontend final
: public IVoiceFrameProcessor,
public IPlaybackReferenceSink {
public:
bool Initialize();
void SetEventPublisher(IEventPublisher* publisher);
void SetWakeWordEnabled(bool enabled);
void ApplyPolicy(AudioPolicy policy) override;
bool Process(
AudioPolicy policy,
const int16_t* input,
size_t sample_count,
int16_t* output,
size_t output_capacity) override;
void OnPlaybackReference(
const int16_t* samples,
size_t sample_count) override;
void ResetPlaybackReference() override;
// Frees the WakeNet instance. Only for entering BLE provisioning, where the
// BT controller needs every spare byte and the wake word is unused. Normal
// policy changes must never call this: reloading the model takes ~110 ms
// under processor_mutex_, which stalls the capture task and breaks AEC
// mic/reference lockstep. See EnsureWakeWordLoaded().
void ReleaseWakeWord();
VoiceFrontendMetrics Metrics() const;
void LogMetrics(const char* reason) const;
// Returns the frames measured since the previous call and clears the
// accumulator. Called by the diagnostics worker, never by the capture task.
VoiceFrameStats ConsumeFrameStats();
private:
static constexpr size_t kFrameSamples = 960;
static constexpr size_t kReferenceDepth = 4;
// Occupancy the ring is trimmed back to on every push, NOT the array size.
//
// The echo of a reference frame reaches the microphone about 1.5 x 60 ms
// frames after it is queued (the I2S TX DMA holds 6 x 360 samples @ 24 kHz
// = 90 ms). So the frame the AEC needs was pushed 1-2 frames ago, i.e. the
// ring should sit at an occupancy of 2-3. It used to be 8 deep with a
// drop-the-oldest overflow rule, which is the worst possible combination:
// once the capture task falls behind, the ring pins itself at full and
// every reference handed to the AEC is ~7 frames (420 ms) older than the
// echo it is supposed to cancel. The adaptive filter spans roughly
// filter_length x chunk = 4 x 16 ms, so it simply stopped cancelling and
// the speaker leaked into the uplink — the device then answered its own
// TTS. Field metrics showed 25-30% of reference frames being dropped that
// way, i.e. a permanently full ring.
//
// Trimming to the newest frames costs AEC continuity when capture lags,
// but a correctly aligned reference with occasional gaps cancels; a
// chronically skewed one cancels nothing.
static constexpr size_t kReferenceMaxLeadFrames = 3;
// A freshly refilled ring must hold this many frames before serving the
// AEC: the echo of the first pushed frames is still inside the TX DMA and
// has not reached the microphone, so serving early pairs the filter with
// a reference the echo lags by more than its 64 ms span. Field data tied
// ref_depth >= ~2 to erl 16-20 dB and depth < 1 to <= 8 dB.
static constexpr size_t kReferencePrimeFrames = 2;
static constexpr size_t kWakeAccumulatorSamples = 4096;
static constexpr uint64_t kWakeCooldownMs = 2000;
static constexpr uint32_t kReferenceActiveRms = 300;
// Frames to keep ignoring the microphone after the playback reference goes
// quiet. The reference is queued before the I2S write, so it leads the
// sound leaving the speaker by the DMA depth (6 x 240 frames @ 24 kHz =
// 60 ms) plus PA and decay. Four 60 ms frames covers that tail without
// eating into the child's answer, which may start the instant the prompt
// stops. The previous firmware used a blunt 800 ms drain, but it only did
// so before a one-shot idle probe, never inside a listening turn.
static constexpr uint8_t kSelfCaptureHangoverFrames = 4;
// How stale the last playback frame may be before the speaker counts as
// quiet. OnPlaybackReference() fires once per decoded frame, so two frame
// periods bridges normal jitter without keeping the gate open into silence.
static constexpr uint64_t kSpeakerActiveWindowUs = 120ULL * 1000ULL;
// --- Barge-in residual gate + local candidate (kBargeInDuplex only) ---
//
// The AEC on this board converges to 17-20 dB ERL but starts every TTS
// session at 8-10 dB, and those first seconds of residual (out_rms up to
// several thousand) were being uploaded and transcribed by the server's
// ASR as user speech — the device then answered itself. Energy alone
// cannot separate residual from speech (they overlap in RMS), but residual
// is the only signal that scales with the playback reference. The gate
// therefore tracks leak = out_rms / ref_rms over frames it suppresses and
// withholds any frame whose energy the leak line explains; a frame that
// jumps clear of the line is treated as the child speaking, flows to the
// server, and after kCandidateFrames of it a local kBargeInCandidate
// reversibly pauses playback. The pause doubles as a probe: with the
// speaker silent the echo source is gone, so persistent energy means a
// real voice (now uploaded clean for the server to confirm) and instant
// silence means a false trigger, answered by a local kBargeInRejected.
// kBargeInRejected/kBargeInConfirmed guards in the reducer make a
// duplicate or late local verdict a no-op.
static constexpr float kLeakMargin = 1.5F;
static constexpr float kLeakAlpha = 0.0625F; // EMA 1/16
// EMA clamp floor ≈ the leak at 16 dB ERL — the best this AEC sustains
// in-session, so the line has no business going lower. The first cut used
// 0.05 and the gate seeded there (see the warm-up note in the .cc), which
// made every louder-than-floor residual frame read as speech: candidates
// fired with leak=0.05 while ERL was 7 dB and each one paused playback for
// ~half a second — heard in the field as stutter.
static constexpr float kLeakMinimum = 0.15F;
static constexpr float kLeakMaximum = 6.0F;
// Seed the line no lower than this once warm-up completes. Starting high
// is self-correcting (the EMA walks it down on gated frames); starting low
// is a trap (frames above the line never train it).
static constexpr float kLeakSeedMinimum = 0.5F;
// Loud-reference frames observed before the seed is trusted: long enough
// for the echo of the first frames to actually arrive at the microphone.
static constexpr uint8_t kLeakWarmupFrames = 8; // ~0.5 s
// Absolute floors sized against the barge-in profile's noise floor, which
// is NOT the quiet-capture one: NS is off in this profile and the AGC
// (gain up to 1.8) amplifies room noise to ~250-300 RMS. The first cut
// used 200/250 and inter-sentence TTS gaps — reference near zero, AGC-
// amplified noise just over the floor — fired candidates that paused
// playback for half a second: the field symptom was intermittent playback
// stutter. Child speech through this path measures ≥2000, so 500/400
// keeps an order-of-magnitude gap on both sides.
static constexpr uint32_t kResidualFloorRms = 500;
static constexpr uint32_t kProbeSpeechFloorRms = 400;
static constexpr uint8_t kCandidateFrames = 3; // 180 ms of speech
static constexpr uint8_t kProbeSilenceFrames = 5; // 300 ms of silence
// Nothing from the server and no probe verdict after this long: resume
// playback rather than leaving it paused forever. The reducer ignores the
// resulting kBargeInRejected if the server decided meanwhile.
static constexpr uint64_t kCandidateTimeoutUs = 1500ULL * 1000ULL;
// After a candidate is locally rejected or times out, no new candidate
// may be raised until this much time has passed AND at least one frame
// fell back below the leak line. Without it, the same sustained energy
// re-raised immediately: field log showed one TTS session paused four
// times for ~4.8 s total (three 1.5 s timeouts back to back) while the
// server kept streaming — the 48-slot queue overflowed and ~1.8 s of
// audio was dropped mid-sentence. During the hold the uplink still
// flows, so the server's own abort arbitration stays fully armed.
static constexpr uint64_t kCandidateRearmUs = 2000ULL * 1000ULL;
// No candidate may be raised during the first ~0.9 s of loud reference
// in each duplex window: the AEC re-converges at every session start
// (erl ~8-10 dB vs 17-25 dB converged) and its elevated residual crosses
// a leak line trained on the converged state. Field log: four candidate
// pauses in one run, ALL within 1 s of a session start, none
// mid-sentence. Real speech in that window still uploads and the server
// can abort; only the local reversible pause waits.
static constexpr uint16_t kCandidateHoldoffFrames = 15;
// A candidate additionally needs the over-line streak's PEAK to reach
// this level. Peak, not consecutive level: real speech is an envelope —
// syllable peaks with dips between them — and "N consecutive frames all
// loud" is unsatisfiable for it (field: with a consecutive-1100 rule the
// gate raised zero candidates for genuine interjections; duplex read as
// dead). Residual is the opposite shape, a plateau. The level is
// calibrated against double-talk reality: the AEC attenuates near-end
// speech while the far end plays (field tap: the child's voice sat
// entirely below the leak line during TTS), so voice peaks at the gate
// land near 900-1500, not the 2000-9000 seen without playback. False
// positives are held off by the trim-settle window + holdoff + rearm,
// not by this line alone.
static constexpr uint32_t kCandidateStrongRms = 900;
// A reference-ring trim jumps the reference timeline by a whole frame
// (60 ms > the 64 ms AEC filter span): the filter is misaligned until it
// re-adapts, and its residual reads as room energy. No candidate until
// the echo path has settled; uplink gating is untouched.
static constexpr uint64_t kAlignmentSettleUs = 2000ULL * 1000ULL;
// Segment-level uplink gating. Per-frame RMS censorship shreds speech:
// only the frames over the leak line survived, so the server's VAD/ASR
// received disconnected 60 ms shards and its whole two-phase arbitration
// starved (field tap: the child's voice was ENTIRELY absent from the
// uplink during TTS). Once a streak of kUplinkPassStreak over-line
// frames shows plausible voice, pass EVERYTHING for the next
// kUplinkPassWindowUs — envelope dips included — and keep extending
// while frames stay over the line. Suppression resumes when the window
// lapses, so the steady-state uplink stays as silent as before; the
// cost is a sub-second residual tail after a burst that opened a window.
static constexpr uint64_t kUplinkPassWindowUs = 800ULL * 1000ULL;
static constexpr uint8_t kUplinkPassStreak = 2;
// The wake accumulator (8 KB) and the AEC reference ring (15 KB) used to
// sit in the CompositionRoot's .bss, i.e. 23 KB of internal RAM held for
// the whole uptime. Internal RAM is the scarce pool on this board: the BT
// controller needs ~53 KB and the WiFi driver ~36 KB, and BLE provisioning
// has to hold both at once when it re-attaches WiFi to test credentials.
// Both buffers are only touched by the capture and playback tasks, whose
// stacks already live in PSRAM, so moving them there costs nothing that
// matters and buys back the headroom.
struct ScratchBuffers {
std::array<int16_t, kWakeAccumulatorSamples> wake_accumulator{};
std::array<
std::array<int16_t, kFrameSamples>,
kReferenceDepth>
reference_ring{};
// Post-AEC, pre-AGC copy of the frame for WakeNet. The AGC pumps
// hard during music+speech double-talk (gain swinging 0.9-1.8 inside
// one phrase) and a phrase chopped by gain steps is what WakeNet
// misses; idle detection feeds the raw microphone and never sees
// this, which is why it stays sensitive.
std::array<int16_t, kFrameSamples> wake_tap{};
};
bool WakeRequired(AudioPolicy policy) const;
bool AecRequired(AudioPolicy policy) const;
// Loads the WakeNet model at most once per boot. Deliberately lazy rather
// than eager: BLE provisioning runs with AudioPolicy::kOff from boot, so
// the model never loads there and the BT controller keeps the internal RAM
// that esp_wifi_deinit() freed for it.
bool EnsureWakeWordLoaded();
void FeedWakeWord(
const int16_t* samples,
size_t sample_count);
bool PopReference(int16_t* output);
void ClearReference();
// Runs the residual gate and the local candidate state machine for one
// kBargeInDuplex frame. Returns true when the frame must be withheld from
// the uplink. Called with processor_mutex_ held.
bool UpdateBargeInGate(
uint32_t out_rms,
uint32_t reference_rms,
bool has_reference,
bool speaker_active,
uint64_t now_us);
void ResolveCandidateLocked(
AppEventType verdict,
const char* reason,
uint64_t now_us);
static uint32_t FrameRms(
const int16_t* samples,
size_t sample_count);
void AccumulateFrameStats(
AudioPolicy policy,
uint32_t microphone_rms,
uint32_t processed_rms,
uint32_t reference_rms,
bool has_reference);
void Publish(const AppEvent& event);
static void WakeScanTaskEntry(void* context);
[[noreturn]] void RunWakeScan();
void QueueWakeAudio(const int16_t* samples);
std::atomic<IEventPublisher*> publisher_{nullptr};
mutable std::mutex processor_mutex_;
AudioPolicy policy_ = AudioPolicy::kOff;
WakeWordDetector wake_word_;
VoiceDsp dsp_;
VoiceActivityDetector vad_;
std::unique_ptr<ScratchBuffers, PsramObjectDeleter<ScratchBuffers>>
buffers_;
// --- Wake-word scan task (core 1) ---
// On paper AEC (10-15 ms avg) plus WakeNet (~14 ms) fitted the 60 ms
// capture budget; in the field the worst cases stacked to 59-84 ms of
// process time (period_avg 66-70 ms): the microphone backlogged, the
// reference ring pinned at its trim ceiling (ref_trims 4-9/window) and
// the echo alignment wobbled — audible as residual ticks in the uplink.
// Detection therefore runs on its own core-1 task fed through this
// queue; the capture task only copies one frame and moves on.
// wake_accumulator_/cooldown are owned by the scan task; wake_mutex_
// serializes Detect against model load/release.
static constexpr size_t kWakeQueueFrames = 6;
static constexpr uint32_t kWakeScanStackBytes = 12 * 1024;
QueueHandle_t wake_queue_ = nullptr;
TaskHandle_t wake_task_ = nullptr;
std::mutex wake_mutex_;
std::atomic<bool> wake_reset_pending_{false};
size_t wake_accumulator_count_ = 0;
uint64_t wake_cooldown_until_ms_ = 0;
uint8_t self_capture_hangover_ = 0;
// Barge-in gate state. All owned by the capture task under
// processor_mutex_. leak_ratio_ survives policy changes on purpose: the
// echo path barely moves between TTS sessions, so the next session starts
// with a trained gate instead of re-learning through a dirty window.
float leak_ratio_ = 0.0F;
bool leak_seeded_ = false;
uint8_t leak_warmup_frames_ = 0;
// The last two reference RMS values. Residual lags the reference by the
// TX DMA depth (~1.5 frames), so a frame's echo is explained by the
// loudest of the last three reference frames, never by the instantaneous
// one alone.
uint32_t previous_reference_rms_[2] = {0, 0};
bool candidate_active_ = false;
uint64_t candidate_rearm_until_us_ = 0;
bool candidate_needs_quiet_ = false;
uint16_t window_ref_active_frames_ = 0;
uint8_t consecutive_speech_frames_ = 0;
uint32_t streak_peak_rms_ = 0;
uint64_t uplink_pass_until_us_ = 0;
std::atomic<uint64_t> alignment_settle_until_us_{0};
uint8_t probe_silence_frames_ = 0;
uint64_t candidate_deadline_us_ = 0;
// Timestamp of the most recent frame handed to the speaker. Written by the
// playback task, read by the capture task.
//
// This replaced "is the popped reference frame loud?" as the self-playback
// test. That question is unanswerable when the reference ring is empty —
// and it routinely is, because the ring gets cleared on every policy change
// and playback session start, and trimmed on every push. Field log showed
// ref_present=0 for the whole wake-acknowledgement window, so the guard
// never armed and the VAD treated the device's own "我在" as the child
// answering: speech_started 348 ms into the prompt, speech_ended 568 ms
// after it stopped, turn closed 1.4 s after the wake word. The child had to
// speak instantly or say the wake word again.
std::atomic<uint64_t> last_playback_frame_us_{0};
// Each ring slot is a 1920-byte frame. Copying that under a spinlock kept
// interrupts disabled for tens of microseconds on every capture and
// playback frame; both callers are tasks, so a mutex is the right lock.
mutable std::mutex reference_mutex_;
size_t reference_read_ = 0;
size_t reference_write_ = 0;
size_t reference_count_ = 0;
bool reference_primed_ = false;
//Pcm24kTo16kConverter reference_converter_;
Pcm48kTo16kConverter reference_converter_;
mutable portMUX_TYPE metrics_lock_ =
portMUX_INITIALIZER_UNLOCKED;
VoiceFrontendMetrics metrics_{};
VoiceFrameStats frame_stats_{};
uint64_t last_frame_us_ = 0;
bool initialized_ = false;
bool wake_word_enabled_ = true;
};
} // namespace borla

View File

@@ -0,0 +1,103 @@
#include "audio/wake_word_detector.h"
#include <esp_log.h>
#include <esp_wn_iface.h>
#include <esp_wn_models.h>
#include <model_path.h>
#include <cstdio>
namespace borla {
namespace {
constexpr const char* kTag = "WakeWord2";
constexpr const char* kBorlaModelHint = "ni3hao3bo1le4";
} // namespace
WakeWordDetector::~WakeWordDetector()
{
Deinitialize();
}
bool WakeWordDetector::Initialize()
{
if (handle_ != nullptr) {
return true;
}
srmodel_list_t* models = esp_srmodel_init("model");
if (models == nullptr) {
ESP_LOGE(kTag, "model partition initialization failed");
return false;
}
char* selected = esp_srmodel_filter(
models, ESP_WN_PREFIX, kBorlaModelHint);
if (selected == nullptr) {
selected = esp_srmodel_filter(
models, ESP_WN_PREFIX, nullptr);
}
if (selected == nullptr) {
ESP_LOGE(kTag, "no WakeNet model in model partition");
esp_srmodel_deinit(models);
return false;
}
std::snprintf(
model_name_.data(), model_name_.size(), "%s", selected);
interface_ = esp_wn_handle_from_name(model_name_.data());
if (interface_ == nullptr) {
ESP_LOGE(kTag, "WakeNet interface lookup failed");
esp_srmodel_deinit(models);
return false;
}
handle_ = interface_->create(
model_name_.data(), DET_MODE_90);
esp_srmodel_deinit(models);
if (handle_ == nullptr) {
ESP_LOGE(kTag, "WakeNet instance creation failed");
interface_ = nullptr;
return false;
}
auto* model = static_cast<model_iface_data_t*>(handle_);
chunk_samples_ = static_cast<size_t>(
interface_->get_samp_chunksize(model));
const int sample_rate = interface_->get_samp_rate(model);
if (chunk_samples_ == 0 || sample_rate != 16000) {
ESP_LOGE(kTag, "invalid model format rate=%d chunk=%u",
sample_rate,
static_cast<unsigned>(chunk_samples_));
Deinitialize();
return false;
}
ESP_LOGI(kTag, "ready model=%s chunk=%u rate=%d",
model_name_.data(),
static_cast<unsigned>(chunk_samples_),
sample_rate);
return true;
}
void WakeWordDetector::Deinitialize()
{
if (interface_ != nullptr && handle_ != nullptr) {
interface_->destroy(
static_cast<model_iface_data_t*>(handle_));
}
interface_ = nullptr;
handle_ = nullptr;
chunk_samples_ = 0;
}
bool WakeWordDetector::Detect(
const int16_t* samples,
size_t sample_count)
{
if (interface_ == nullptr || handle_ == nullptr ||
samples == nullptr || sample_count != chunk_samples_) {
return false;
}
const int result = interface_->detect(
static_cast<model_iface_data_t*>(handle_),
const_cast<int16_t*>(samples));
return result > 0;
}
} // namespace borla

View File

@@ -0,0 +1,29 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <esp_wn_iface.h>
namespace borla {
class WakeWordDetector final {
public:
~WakeWordDetector();
bool Initialize();
void Deinitialize();
bool Detect(const int16_t* samples, size_t sample_count);
bool initialized() const { return handle_ != nullptr; }
size_t ChunkSamples() const { return chunk_samples_; }
const char* ModelName() const { return model_name_.data(); }
private:
const esp_wn_iface_t* interface_ = nullptr;
void* handle_ = nullptr;
size_t chunk_samples_ = 0;
std::array<char, 64> model_name_{};
};
} // namespace borla

View File

@@ -0,0 +1,212 @@
#include "configuration/remote_behavior_config.h"
#include <array>
#include <esp_err.h>
#include <esp_log.h>
#include <nvs.h>
namespace borla {
namespace {
constexpr const char* kTag = "RemoteBehavior2";
constexpr const char* kButtonNamespace = "btn_cfg";
constexpr const char* kTripleClickKey = "c3";
constexpr const char* kQuadrupleClickKey = "c4";
constexpr const char* kConnectionNamespace = "conn_err";
constexpr const char* kServerPromptKey = "srv";
constexpr const char* kNetworkPromptKey = "net";
template <typename Parser, typename Value>
bool ReadValue(
const char* name_space,
const char* key,
Parser parser,
Value* output)
{
nvs_handle_t handle = 0;
const esp_err_t open =
nvs_open(name_space, NVS_READONLY, &handle);
if (open == ESP_ERR_NVS_NOT_FOUND) {
return true;
}
if (open != ESP_OK) {
return false;
}
std::array<char, 32> value{};
size_t size = value.size();
const esp_err_t read =
nvs_get_str(handle, key, value.data(), &size);
nvs_close(handle);
if (read == ESP_ERR_NVS_NOT_FOUND) {
return true;
}
if (read != ESP_OK || !parser(value.data(), output)) {
// A stored value that is missing, oversized or unparsable only means
// this one behaviour keeps its default. Reporting failure here would
// escalate to kFatalError and leave the device stuck in kFaulted.
ESP_LOGW(kTag, "ignored invalid NVS value ns=%s key=%s error=%s",
name_space, key, esp_err_to_name(read));
return true;
}
return true;
}
bool WriteValues(
const char* name_space,
const char* first_key,
const char* first_value,
const char* second_key,
const char* second_value)
{
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(name_space, NVS_READWRITE, &handle);
if (result == ESP_OK && first_value != nullptr) {
result = nvs_set_str(handle, first_key, first_value);
}
if (result == ESP_OK && second_value != nullptr) {
result = nvs_set_str(handle, second_key, second_value);
}
if (result == ESP_OK) {
result = nvs_commit(handle);
}
if (handle != 0) {
nvs_close(handle);
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "NVS update failed ns=%s error=%s",
name_space, esp_err_to_name(result));
return false;
}
return true;
}
} // namespace
bool NvsRemoteBehaviorConfig::Load()
{
ButtonAction triple = ButtonAction::kFriendMode;
ButtonAction quadruple = ButtonAction::kNetworkSwitch;
LocalPrompt server = LocalPrompt::kServerError;
LocalPrompt network = LocalPrompt::kNoNetwork;
const bool valid =
ReadValue(
kButtonNamespace,
kTripleClickKey,
ParseButtonAction,
&triple) &&
ReadValue(
kButtonNamespace,
kQuadrupleClickKey,
ParseButtonAction,
&quadruple) &&
ReadValue(
kConnectionNamespace,
kServerPromptKey,
ParseConnectionPrompt,
&server) &&
ReadValue(
kConnectionNamespace,
kNetworkPromptKey,
ParseConnectionPrompt,
&network);
triple_click_.store(triple);
quadruple_click_.store(quadruple);
server_unreachable_.store(server);
no_network_.store(network);
return valid;
}
ButtonAction NvsRemoteBehaviorConfig::ResolveButtonAction(
uint8_t click_count) const
{
if (click_count == 3) {
return triple_click_.load();
}
if (click_count == 4) {
return quadruple_click_.load();
}
return ButtonAction::kUnspecified;
}
LocalPrompt NvsRemoteBehaviorConfig::ServerUnreachablePrompt() const
{
return server_unreachable_.load();
}
LocalPrompt NvsRemoteBehaviorConfig::NoNetworkPrompt() const
{
return no_network_.load();
}
bool NvsRemoteBehaviorConfig::UpdateButtonActions(
ButtonAction triple_click,
ButtonAction quadruple_click)
{
const char* triple = triple_click == ButtonAction::kUnspecified
? nullptr
: ToString(triple_click);
const char* quadruple =
quadruple_click == ButtonAction::kUnspecified
? nullptr
: ToString(quadruple_click);
if (triple == nullptr && quadruple == nullptr) {
return true;
}
if (!WriteValues(
kButtonNamespace,
kTripleClickKey,
triple,
kQuadrupleClickKey,
quadruple)) {
return false;
}
if (triple != nullptr) {
triple_click_.store(triple_click);
}
if (quadruple != nullptr) {
quadruple_click_.store(quadruple_click);
}
return true;
}
bool NvsRemoteBehaviorConfig::UpdateConnectionPrompts(
bool has_server_unreachable,
LocalPrompt server_unreachable,
bool has_no_network,
LocalPrompt no_network)
{
if ((has_server_unreachable &&
!IsAllowedConnectionPrompt(server_unreachable)) ||
(has_no_network &&
!IsAllowedConnectionPrompt(no_network))) {
return false;
}
const char* server = has_server_unreachable
? ToString(server_unreachable)
: nullptr;
const char* network = has_no_network
? ToString(no_network)
: nullptr;
if (server == nullptr && network == nullptr) {
return true;
}
if (!WriteValues(
kConnectionNamespace,
kServerPromptKey,
server,
kNetworkPromptKey,
network)) {
return false;
}
if (server != nullptr) {
server_unreachable_.store(server_unreachable);
}
if (network != nullptr) {
no_network_.store(no_network);
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,37 @@
#pragma once
#include "ports/remote_behavior_config.h"
#include <atomic>
namespace borla {
class NvsRemoteBehaviorConfig final : public IRemoteBehaviorConfig {
public:
bool Load();
ButtonAction ResolveButtonAction(
uint8_t click_count) const override;
LocalPrompt ServerUnreachablePrompt() const override;
LocalPrompt NoNetworkPrompt() const override;
bool UpdateButtonActions(
ButtonAction triple_click,
ButtonAction quadruple_click) override;
bool UpdateConnectionPrompts(
bool has_server_unreachable,
LocalPrompt server_unreachable,
bool has_no_network,
LocalPrompt no_network) override;
private:
std::atomic<ButtonAction> triple_click_{
ButtonAction::kFriendMode};
std::atomic<ButtonAction> quadruple_click_{
ButtonAction::kNetworkSwitch};
std::atomic<LocalPrompt> server_unreachable_{
LocalPrompt::kServerError};
std::atomic<LocalPrompt> no_network_{
LocalPrompt::kNoNetwork};
};
} // namespace borla

View File

@@ -0,0 +1,59 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
inline constexpr size_t kCellularIpv4Capacity = 16;
inline constexpr size_t kCellularImeiCapacity = 24;
inline constexpr size_t kCellularOperatorCapacity = 32;
enum class CellularTransportEventType : uint8_t {
kStarted,
kGotIp,
kDisconnected,
};
struct CellularTransportEvent {
CellularTransportEventType type = CellularTransportEventType::kStarted;
uint16_t reason = 0;
};
struct CellularLinkInfo {
bool modem_present = false;
bool registered = false;
bool online = false;
int8_t csq = -1;
uint8_t registration_status = 0;
std::array<char, kCellularIpv4Capacity> ipv4{};
std::array<char, kCellularImeiCapacity> imei{};
std::array<char, kCellularOperatorCapacity> operator_name{};
};
class ICellularTransportObserver {
public:
virtual ~ICellularTransportObserver() = default;
virtual void OnCellularTransportEvent(
const CellularTransportEvent& event) = 0;
};
//2026-9-9 ckkj add: 新增探测结果枚举,用于表示模块是否在位
enum class CellularProbeResult : uint8_t {
kPresent,
kAbsent,
// 探测本身没能执行(如内部 RAM 不足装不下探测 UART),不代表模块不在位。
kUnknown,
};
class ICellularTransport {
public:
virtual ~ICellularTransport() = default;
virtual bool Start(ICellularTransportObserver& observer) = 0;
virtual void Stop() = 0;
//virtual bool ProbePresent() = 0;
virtual CellularProbeResult ProbePresent() = 0;
virtual CellularLinkInfo GetLinkInfo() const = 0;
};
} // namespace borla

View File

@@ -0,0 +1,429 @@
#include "connectivity/connectivity_manager.h"
#include "core/playback_types.h"
#include <cstring>
#include <esp_err.h>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_random.h>
namespace borla {
namespace {
constexpr const char* kTag = "Connectivity2";
constexpr uint16_t kLocalConnectRequestFailure = 0xFFFE;
//2026-9-6 ckkj add: DualNetworkTransport 主动切网断开 WiFi 的标记 reason。
constexpr uint16_t kBearerswitchReason = 0xF101;
ConnectivityPhase ToPhase(ConnectivityPolicyState state)
{
switch (state) {
case ConnectivityPolicyState::kStopped:
return ConnectivityPhase::kStopped;
case ConnectivityPolicyState::kCredentialsMissing:
return ConnectivityPhase::kCredentialsMissing;
case ConnectivityPolicyState::kStartingTransport:
return ConnectivityPhase::kStartingTransport;
case ConnectivityPolicyState::kConnecting:
return ConnectivityPhase::kConnecting;
case ConnectivityPolicyState::kWaitingRetry:
return ConnectivityPhase::kWaitingRetry;
case ConnectivityPolicyState::kOnline:
return ConnectivityPhase::kOnline;
}
return ConnectivityPhase::kStopped;
}
} // namespace
ConnectivityManager::ConnectivityManager(IWifiTransport& transport,
IWifiCredentialStore& credentials, ReconnectBackoffConfig retry_config)
: transport_(transport)
, credential_store_(credentials)
, policy_(retry_config)
{
}
bool ConnectivityManager::Initialize()
{
if (initialized_) {
return true;
}
queue_ = xQueueCreateStatic(kQueueDepth, sizeof(ManagerEvent),
queue_storage_.data(), &queue_control_);
if (queue_ == nullptr) {
ESP_LOGE(kTag, "manager queue creation failed");
return false;
}
stop_completed_ = xSemaphoreCreateBinaryStatic(&stop_completed_control_);
if (stop_completed_ == nullptr) {
ESP_LOGE(kTag, "stop completion semaphore creation failed");
return false;
}
const esp_timer_create_args_t timer_args = {
.callback = &ConnectivityManager::RetryTimerCallback,
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "wifi_retry2",
.skip_unhandled_events = true,
};
const esp_err_t timer_result = esp_timer_create(&timer_args, &retry_timer_);
if (timer_result != ESP_OK) {
ESP_LOGE(kTag, "retry timer creation failed: %s",
esp_err_to_name(timer_result));
return false;
}
const BaseType_t task_result = xTaskCreate(&ConnectivityManager::TaskEntry,
"connectivity2", task_stack_budget::kConnectivityManagerBytes, this,
kTaskPriority, &task_);
if (task_result != pdPASS) {
task_ = nullptr;
ESP_LOGE(kTag, "manager task creation failed");
esp_timer_delete(retry_timer_);
retry_timer_ = nullptr;
return false;
}
initialized_ = true;
ESP_LOGI(kTag,
"manager initialized queue=%u stack_bytes=%u memory=internal",
static_cast<unsigned>(kQueueDepth),
static_cast<unsigned>(task_stack_budget::kConnectivityManagerBytes));
return true;
}
void ConnectivityManager::Start()
{
// 2026-9-7 ckkj add: BLE 好友模式挂起期间忽略启动请求,
// 否则重连效果会把 WiFi 驱动拉起来与 BT 控制器抢占内部 RAM。
if (ble_suspended_.load()) {
ESP_LOGW(kTag, "start ignored: suspended for BLE friend mode");
return;
}/////end
if (!Post({ ManagerEventType::kStart, 0 })) {
ESP_LOGE(kTag, "failed to enqueue start");
}
}
// 2026-9-7 ckkj add: BLE 好友模式启动前静默挂起网络。BT 控制器需要 ~65KB
// 内部 RAM,与已初始化的 WiFi 驱动无法共存:上次三击好友模式 BLE_INIT
// "Malloc failed" 后在 controller 内部 r_co_list_pop_front 直接 panic,
// 错误检查来不及执行,唯一可靠手段是启动前腾出内存。Stop() 是同步的且
// policy_.Stop() 会经 kStopTransport → DualNetworkTransport →
// wifi_.ReleaseDriver() 拆除驱动,且不发布断开事件(静默);随后再显式
// 兑底拆一次驱动(幂等),返回时 BLE 可用内存已就绪。
void ConnectivityManager::SuspendForBle()
{
bool expected = false;
if (!ble_suspended_.compare_exchange_strong(expected, true)) {
return;
}
Stop();
transport_.ReleaseDriver();
online_.store(false);
ESP_LOGI(kTag, "network suspended for BLE internal_free=%u largest=%u",
static_cast<unsigned>(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
static_cast<unsigned>(
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)));
}
// 好友模式结束(配对成功/失败/超时)后恢复正常重连。BleFriendExchange
// 在 nimble_port_deinit() 释放 BT 内存之后才回调,此处再拉起 WiFi 安全。
void ConnectivityManager::ResumeAfterBle()
{
bool expected = true;
if (!ble_suspended_.compare_exchange_strong(expected, false)) {
return;
}
ESP_LOGI(kTag, "network resume after BLE");
Start();
}/////add end
void ConnectivityManager::Stop()
{
if (!initialized_ || stop_completed_ == nullptr) {
return;
}
xSemaphoreTake(stop_completed_, 0);
if (!Post({ ManagerEventType::kStop, 0 })) {
ESP_LOGE(kTag, "failed to enqueue stop");
return;
}
// Handling kStop calls DualNetworkTransport::Stop(), which itself waits up
// to 5 s for its own worker. The outer wait must outlast that, otherwise a
// slow-but-successful stop always reports a bogus timeout here.
if (xSemaphoreTake(stop_completed_, pdMS_TO_TICKS(8000)) != pdTRUE) {
ESP_LOGE(kTag, "timed out waiting for WiFi transport stop");
}
}
void ConnectivityManager::SwitchNetwork()
{
if (!transport_.RequestNetworkSwitch()) {
ESP_LOGW(kTag, "active transport does not support network switch");
}
}
ConnectivityDiagnostics ConnectivityManager::GetDiagnostics() const
{
portENTER_CRITICAL(&diagnostics_lock_);
const ConnectivityDiagnostics snapshot = diagnostics_;
portEXIT_CRITICAL(&diagnostics_lock_);
return snapshot;
}
void ConnectivityManager::OnWifiTransportEvent(const WifiTransportEvent& event)
{
ManagerEvent manager_event;
switch (event.type) {
case WifiTransportEventType::kStarted:
manager_event.type = ManagerEventType::kTransportReady;
break;
case WifiTransportEventType::kGotIp:
manager_event.type = ManagerEventType::kGotIp;
break;
case WifiTransportEventType::kDisconnected:
manager_event.type = ManagerEventType::kDisconnected;
manager_event.disconnect_reason = event.disconnect_reason;
break;
case WifiTransportEventType::kReconnectRequested:
manager_event.type = ManagerEventType::kRetryNow;
break;
case WifiTransportEventType::kCellularOn:
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
static_cast<int32_t>(LocalPrompt::kNet4gOn),
static_cast<uint32_t>(PlaybackPriority::kSystem)));
return;
case WifiTransportEventType::kCellularOff:
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
static_cast<int32_t>(LocalPrompt::kNet4gOff),
static_cast<uint32_t>(PlaybackPriority::kSystem)));
return;
case WifiTransportEventType::kCellularUnavailable:
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
static_cast<int32_t>(LocalPrompt::kNet4gNoWifi),
static_cast<uint32_t>(PlaybackPriority::kSystem)));
return;
case WifiTransportEventType::kCellularBootOn:
PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
static_cast<int32_t>(LocalPrompt::kNet4gBootOn),
static_cast<uint32_t>(PlaybackPriority::kSystem)));
return;
}
if (!Post(manager_event)) {
ESP_LOGE(kTag, "transport event queue full type=%u",
static_cast<unsigned>(event.type));
}
}
void ConnectivityManager::TaskEntry(void* context)
{
static_cast<ConnectivityManager*>(context)->Run();
}
void ConnectivityManager::RetryTimerCallback(void* context)
{
auto* self = static_cast<ConnectivityManager*>(context);
if (!self->Post({ ManagerEventType::kRetryElapsed, 0 })) {
ESP_LOGE(kTag, "retry timer event queue full");
}
}
bool ConnectivityManager::Post(const ManagerEvent& event)
{
return initialized_ && queue_ != nullptr
&& xQueueSend(queue_, &event, 0) == pdTRUE;
}
[[noreturn]] void ConnectivityManager::Run()
{
ESP_LOGI(kTag, "manager task started");
while (true) {
ManagerEvent event;
if (xQueueReceive(queue_, &event, portMAX_DELAY) == pdTRUE) {
Handle(event);
}
}
}
void ConnectivityManager::Handle(const ManagerEvent& event)
{
ConnectivityPolicyResult result;
switch (event.type) {
case ManagerEventType::kStart:
if (policy_.state() == ConnectivityPolicyState::kStopped) {
credentials_.fill(WifiCredential {});
credential_count_ = credential_store_.Load(
credentials_.data(), credentials_.size());
}
result = policy_.Start(credential_count_);
break;
case ManagerEventType::kStop:
result = policy_.Stop();
break;
case ManagerEventType::kTransportReady:
result = policy_.OnTransportReady();
break;
case ManagerEventType::kTransportStartFailed:
result = policy_.OnTransportStartFailed(esp_random());
break;
case ManagerEventType::kGotIp:
result = policy_.OnGotIp();
break;
case ManagerEventType::kDisconnected:
//result = policy_.OnDisconnected(event.disconnect_reason, esp_random());
//2026-9-6 ckkj add: 0xF101 是切网动作主动断开 WiFi,非故障,
//不触发 WiFi 自动重试,避免与 4G 启动抢内部 RAM 导致 PPP UART 安装失败。
if (event.disconnect_reason != kBearerswitchReason) {
result = policy_.OnDisconnected(event.disconnect_reason, esp_random());
}
break;
case ManagerEventType::kRetryElapsed:
result = policy_.OnRetryElapsed();
break;
case ManagerEventType::kRetryNow:
if (retry_timer_ != nullptr) {
const esp_err_t stop_result = esp_timer_stop(retry_timer_);
if (stop_result != ESP_OK && stop_result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "immediate retry timer cancel failed: %s",
esp_err_to_name(stop_result));
}
}
result = policy_.OnRetryElapsed();
break;
}
Execute(result);
RefreshDiagnostics();
if (event.type == ManagerEventType::kStop && stop_completed_ != nullptr) {
xSemaphoreGive(stop_completed_);
}
}
void ConnectivityManager::Execute(const ConnectivityPolicyResult& result)
{
for (size_t index = 0; index < result.action_count; ++index) {
Execute(result.actions[index]);
}
}
void ConnectivityManager::Execute(const ConnectivityAction& action)
{
switch (action.type) {
case ConnectivityActionType::kStartTransport:
if (!transport_.Start(*this)) {
Post({ ManagerEventType::kTransportStartFailed, 0 });
}
return;
case ConnectivityActionType::kStopTransport:
transport_.Stop();
return;
case ConnectivityActionType::kConnectCredential:
if (action.credential_index >= credential_count_
|| !transport_.Connect(credentials_[action.credential_index])) {
Post({
ManagerEventType::kDisconnected,
kLocalConnectRequestFailure,
});
}
return;
case ConnectivityActionType::kScheduleRetry: {
if (retry_timer_ == nullptr) {
return;
}
const esp_err_t stop_result = esp_timer_stop(retry_timer_);
if (stop_result != ESP_OK && stop_result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "retry timer stop failed: %s",
esp_err_to_name(stop_result));
}
const esp_err_t start_result = esp_timer_start_once(
retry_timer_, static_cast<uint64_t>(action.delay_ms) * 1000ULL);
if (start_result != ESP_OK) {
ESP_LOGE(kTag, "retry timer start failed delay=%lu: %s",
static_cast<unsigned long>(action.delay_ms),
esp_err_to_name(start_result));
} else {
ESP_LOGI(kTag, "retry scheduled delay=%lu ms attempt=%lu",
static_cast<unsigned long>(action.delay_ms),
static_cast<unsigned long>(policy_.retry_attempt_count()));
}
return;
}
case ConnectivityActionType::kCancelRetry:
if (retry_timer_ != nullptr) {
const esp_err_t result = esp_timer_stop(retry_timer_);
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "retry timer cancel failed: %s",
esp_err_to_name(result));
}
}
return;
case ConnectivityActionType::kPublishConnected: {
const WifiLinkInfo link = transport_.GetLinkInfo();
ESP_LOGI(kTag, "online ssid=%s ip=%s rssi=%d channel=%u",
link.ssid.data(), link.ipv4.data(), static_cast<int>(link.rssi_dbm),
static_cast<unsigned>(link.channel));
PublishAppEvent(AppEvent::Make(
AppEventType::kNetworkConnected, 0, link.rssi_dbm, link.channel));
return;
}
case ConnectivityActionType::kPublishDisconnected:
ESP_LOGW(kTag, "offline reason=%u",
static_cast<unsigned>(action.disconnect_reason));
PublishAppEvent(AppEvent::Make(
AppEventType::kNetworkDisconnected, 0, action.disconnect_reason));
if (remote_behavior_config_ != nullptr) {
PublishAppEvent(
AppEvent::Make(AppEventType::kLocalPromptRequested, 0,
static_cast<int32_t>(
remote_behavior_config_->NoNetworkPrompt()),
static_cast<uint32_t>(PlaybackPriority::kSystem)));
}
return;
case ConnectivityActionType::kRequestProvisioning:
ESP_LOGW(kTag, "no saved WiFi credentials; provisioning requested");
PublishAppEvent(AppEvent::Make(AppEventType::kProvisioningRequested));
return;
}
}
void ConnectivityManager::RefreshDiagnostics()
{
const WifiLinkInfo link = transport_.GetLinkInfo();
ConnectivityDiagnostics next;
next.phase = ToPhase(policy_.state());
next.online = policy_.state() == ConnectivityPolicyState::kOnline;
next.rssi_dbm = link.rssi_dbm;
next.channel = link.channel;
next.last_disconnect_reason = policy_.last_disconnect_reason() != 0
? policy_.last_disconnect_reason()
: link.last_disconnect_reason;
next.retry_attempt_count = policy_.retry_attempt_count();
next.active_credential_index = policy_.credential_index();
next.credential_count = policy_.credential_count();
next.ssid = link.ssid;
next.ipv4 = link.ipv4;
portENTER_CRITICAL(&diagnostics_lock_);
diagnostics_ = next;
portEXIT_CRITICAL(&diagnostics_lock_);
online_.store(next.online);
}
void ConnectivityManager::PublishAppEvent(const AppEvent& event)
{
if (publisher_ == nullptr) {
ESP_LOGE(
kTag, "event publisher unavailable event=%s", ToString(event.type));
return;
}
if (!publisher_->Publish(event)) {
ESP_LOGE(
kTag, "application event rejected event=%s", ToString(event.type));
}
}
} // namespace borla

View File

@@ -0,0 +1,107 @@
#pragma once
#include "connectivity/connectivity_policy.h"
#include "connectivity/wifi_credential_store.h"
#include "connectivity/wifi_transport.h"
#include "core/task_stack_budget.h"
#include "ports/connectivity_manager.h"
#include "ports/event_publisher.h"
#include "ports/remote_behavior_config.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class ConnectivityManager final : public IConnectivityManager,
public IWifiTransportObserver {
public:
ConnectivityManager(IWifiTransport& transport,
IWifiCredentialStore& credentials, ReconnectBackoffConfig retry_config);
bool Initialize();
void SetEventPublisher(IEventPublisher* publisher)
{
publisher_ = publisher;
}
void SetRemoteBehaviorConfig(IRemoteBehaviorConfig* config)
{
remote_behavior_config_ = config;
}
void Start() override;
void Stop() override;
void SwitchNetwork() override;
// 2026-9-7 ckkj add: BLE 好友模式前后静默挂起/恢复网络,释放 WiFi 驱动内存。
void SuspendForBle() override;
void ResumeAfterBle() override;//////////
bool IsOnline() const override { return online_.load(); }
ConnectivityDiagnostics GetDiagnostics() const override;
void OnWifiTransportEvent(const WifiTransportEvent& event) override;
private:
enum class ManagerEventType : uint8_t {
kStart,
kStop,
kTransportReady,
kTransportStartFailed,
kGotIp,
kDisconnected,
kRetryElapsed,
kRetryNow,
};
struct ManagerEvent {
ManagerEventType type = ManagerEventType::kStart;
uint16_t disconnect_reason = 0;
};
static constexpr size_t kQueueDepth = 24;
static constexpr UBaseType_t kTaskPriority = 4;
static void TaskEntry(void* context);
static void RetryTimerCallback(void* context);
bool Post(const ManagerEvent& event);
[[noreturn]] void Run();
void Handle(const ManagerEvent& event);
void Execute(const ConnectivityPolicyResult& result);
void Execute(const ConnectivityAction& action);
void RefreshDiagnostics();
void PublishAppEvent(const AppEvent& event);
IWifiTransport& transport_;
IWifiCredentialStore& credential_store_;
ConnectivityPolicy policy_;
IEventPublisher* publisher_ = nullptr;
IRemoteBehaviorConfig* remote_behavior_config_ = nullptr;
std::array<WifiCredential, kMaxSavedWifiCredentials> credentials_ {};
size_t credential_count_ = 0;
QueueHandle_t queue_ = nullptr;
StaticQueue_t queue_control_ {};
alignas(ManagerEvent) std::array<uint8_t,
kQueueDepth * sizeof(ManagerEvent)> queue_storage_ {};
TaskHandle_t task_ = nullptr;
SemaphoreHandle_t stop_completed_ = nullptr;
StaticSemaphore_t stop_completed_control_ {};
esp_timer_handle_t retry_timer_ = nullptr;
bool initialized_ = false;
std::atomic<bool> online_ { false };
std::atomic<bool> ble_suspended_ { false };//2026-9-7 ckkj add
mutable portMUX_TYPE diagnostics_lock_ = portMUX_INITIALIZER_UNLOCKED;
ConnectivityDiagnostics diagnostics_ {};
};
} // namespace borla

View File

@@ -0,0 +1,164 @@
#include "connectivity/connectivity_policy.h"
namespace borla {
namespace {
ConnectivityAction Action(ConnectivityActionType type)
{
ConnectivityAction action;
action.type = type;
return action;
}
} // namespace
ConnectivityPolicy::ConnectivityPolicy(ReconnectBackoffConfig config)
: backoff_(config)
{
}
ConnectivityPolicyResult ConnectivityPolicy::Start(size_t credential_count)
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kStopped) {
return result;
}
credential_count_ = credential_count;
credential_index_ = 0;
last_disconnect_reason_ = 0;
transport_ready_ = false;
backoff_.Reset();
if (credential_count_ == 0) {
state_ = ConnectivityPolicyState::kCredentialsMissing;
result.Add(Action(ConnectivityActionType::kRequestProvisioning));
return result;
}
state_ = ConnectivityPolicyState::kStartingTransport;
result.Add(Action(ConnectivityActionType::kStartTransport));
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::Stop()
{
ConnectivityPolicyResult result;
if (state_ == ConnectivityPolicyState::kStopped) {
return result;
}
result.Add(Action(ConnectivityActionType::kCancelRetry));
result.Add(Action(ConnectivityActionType::kStopTransport));
state_ = ConnectivityPolicyState::kStopped;
credential_count_ = 0;
credential_index_ = 0;
last_disconnect_reason_ = 0;
transport_ready_ = false;
backoff_.Reset();
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::OnTransportReady()
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kStartingTransport ||
credential_count_ == 0) {
return result;
}
transport_ready_ = true;
state_ = ConnectivityPolicyState::kConnecting;
ConnectivityAction connect =
Action(ConnectivityActionType::kConnectCredential);
connect.credential_index = credential_index_;
result.Add(connect);
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::OnTransportStartFailed(
uint32_t entropy)
{
if (state_ != ConnectivityPolicyState::kStartingTransport) {
return {};
}
transport_ready_ = false;
return ScheduleRetry(false, 0, entropy);
}
ConnectivityPolicyResult ConnectivityPolicy::OnDisconnected(
uint16_t reason,
uint32_t entropy)
{
if (state_ == ConnectivityPolicyState::kStopped ||
state_ == ConnectivityPolicyState::kCredentialsMissing ||
state_ == ConnectivityPolicyState::kWaitingRetry) {
return {};
}
const bool was_online = state_ == ConnectivityPolicyState::kOnline;
if (credential_count_ > 0) {
credential_index_ = (credential_index_ + 1U) % credential_count_;
}
return ScheduleRetry(was_online, reason, entropy);
}
ConnectivityPolicyResult ConnectivityPolicy::OnRetryElapsed()
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kWaitingRetry) {
return result;
}
if (!transport_ready_) {
state_ = ConnectivityPolicyState::kStartingTransport;
result.Add(Action(ConnectivityActionType::kStartTransport));
return result;
}
state_ = ConnectivityPolicyState::kConnecting;
ConnectivityAction connect =
Action(ConnectivityActionType::kConnectCredential);
connect.credential_index = credential_index_;
result.Add(connect);
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::OnGotIp()
{
ConnectivityPolicyResult result;
if (state_ != ConnectivityPolicyState::kConnecting) {
return result;
}
state_ = ConnectivityPolicyState::kOnline;
backoff_.Reset();
result.Add(Action(ConnectivityActionType::kCancelRetry));
result.Add(Action(ConnectivityActionType::kPublishConnected));
return result;
}
ConnectivityPolicyResult ConnectivityPolicy::ScheduleRetry(
bool publish_disconnected,
uint16_t reason,
uint32_t entropy)
{
ConnectivityPolicyResult result;
state_ = ConnectivityPolicyState::kWaitingRetry;
last_disconnect_reason_ = reason;
if (publish_disconnected) {
ConnectivityAction disconnected =
Action(ConnectivityActionType::kPublishDisconnected);
disconnected.disconnect_reason = reason;
result.Add(disconnected);
}
ConnectivityAction schedule =
Action(ConnectivityActionType::kScheduleRetry);
schedule.delay_ms = backoff_.NextDelayMs(entropy);
result.Add(schedule);
return result;
}
} // namespace borla

View File

@@ -0,0 +1,94 @@
#pragma once
#include "connectivity/reconnect_backoff.h"
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
enum class ConnectivityPolicyState : uint8_t {
kStopped,
kCredentialsMissing,
kStartingTransport,
kConnecting,
kWaitingRetry,
kOnline,
};
enum class ConnectivityActionType : uint8_t {
kStartTransport,
kStopTransport,
kConnectCredential,
kScheduleRetry,
kCancelRetry,
kPublishConnected,
kPublishDisconnected,
kRequestProvisioning,
};
struct ConnectivityAction {
ConnectivityActionType type = ConnectivityActionType::kStartTransport;
size_t credential_index = 0;
uint32_t delay_ms = 0;
uint16_t disconnect_reason = 0;
};
struct ConnectivityPolicyResult {
std::array<ConnectivityAction, 4> actions{};
size_t action_count = 0;
bool Add(const ConnectivityAction& action)
{
if (action_count >= actions.size()) {
return false;
}
actions[action_count++] = action;
return true;
}
};
class ConnectivityPolicy final {
public:
explicit ConnectivityPolicy(
ReconnectBackoffConfig config = ReconnectBackoffConfig{});
ConnectivityPolicyResult Start(size_t credential_count);
ConnectivityPolicyResult Stop();
ConnectivityPolicyResult OnTransportReady();
ConnectivityPolicyResult OnTransportStartFailed(uint32_t entropy);
ConnectivityPolicyResult OnDisconnected(
uint16_t reason,
uint32_t entropy);
ConnectivityPolicyResult OnRetryElapsed();
ConnectivityPolicyResult OnGotIp();
ConnectivityPolicyState state() const { return state_; }
size_t credential_count() const { return credential_count_; }
size_t credential_index() const { return credential_index_; }
uint16_t last_disconnect_reason() const
{
return last_disconnect_reason_;
}
uint32_t retry_attempt_count() const
{
return backoff_.attempt_count();
}
bool transport_ready() const { return transport_ready_; }
private:
ConnectivityPolicyResult ScheduleRetry(
bool publish_disconnected,
uint16_t reason,
uint32_t entropy);
ReconnectBackoff backoff_;
ConnectivityPolicyState state_ = ConnectivityPolicyState::kStopped;
size_t credential_count_ = 0;
size_t credential_index_ = 0;
uint16_t last_disconnect_reason_ = 0;
bool transport_ready_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,292 @@
#include "connectivity/dual_network_policy.h"
namespace borla {
DualNetworkPolicy::DualNetworkPolicy(DualNetworkPolicyConfig config)
: config_(config)
{
if (config_.wifi_weak_sample_count == 0) {
config_.wifi_weak_sample_count = 1;
}
if (config_.modem_absent_sample_count == 0) {
config_.modem_absent_sample_count = 1;
}
}
DualNetworkPolicyResult DualNetworkPolicy::OnModemPresence(
ModemPresence observed,
uint64_t now_ms)
{
DualNetworkPolicyResult result;
if (!started_ || observed == ModemPresence::kUnknown) {
// An unusable probe (UART driver refused to install) must not be read
// as "the switch was turned off".
if (selected_bearer_ == NetworkBearer::kWifi &&
online_bearer_ != NetworkBearer::kWifi) {
result.Add(DualNetworkActionType::kStartWifi);
}//2026-9-8 ckkj add
return result;
}
if (stable_modem_presence_ == ModemPresence::kUnknown) {
stable_modem_presence_ = observed;
modem_absent_streak_ = 0;
if (observed == ModemPresence::kPresent) {
// Booted with the switch left on while running on WiFi: the modem
// is burning power for nothing, so say so once.
result.Add(DualNetworkActionType::kPromptCellularBootOn);
}
return result;
}
if (observed == ModemPresence::kPresent) {
modem_absent_streak_ = 0;
if (stable_modem_presence_ != ModemPresence::kPresent) {
stable_modem_presence_ = ModemPresence::kPresent;
modem_unavailable_announced_ = false;
result.Add(DualNetworkActionType::kPromptCellularOn);
}
return result;
}
if (stable_modem_presence_ != ModemPresence::kAbsent) {
if (modem_absent_streak_ < UINT8_MAX) {
++modem_absent_streak_;
}
if (modem_absent_streak_ >= config_.modem_absent_sample_count) {
stable_modem_presence_ = ModemPresence::kAbsent;
modem_absent_streak_ = 0;
result.Add(DualNetworkActionType::kPromptCellularOff);
}
}
(void)now_ms;
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::NotifyWifiLostWithoutModem(
uint64_t now_ms)
{
DualNetworkPolicyResult result;
if (!started_ ||
selected_bearer_ != NetworkBearer::kWifi ||
online_bearer_ == NetworkBearer::kWifi ||
stable_modem_presence_ != ModemPresence::kAbsent) {
return result;
}
// Same threshold the automatic failover uses. Announcing earlier would
// fire during a normal boot (WiFi not up yet) and on every brief blip;
// this only speaks once the device would otherwise have switched to 4G
// and found the modem unpowered.
if (wifi_disconnected_since_ms_ == 0 ||
now_ms < wifi_disconnected_since_ms_ ||
now_ms - wifi_disconnected_since_ms_ <
config_.wifi_disconnect_failover_ms) {
return result;
}
if (modem_unavailable_announced_ &&
now_ms >= modem_unavailable_announced_ms_ &&
now_ms - modem_unavailable_announced_ms_ <
config_.modem_unavailable_repeat_ms) {
return result;
}
modem_unavailable_announced_ = true;
modem_unavailable_announced_ms_ = now_ms;
result.Add(DualNetworkActionType::kPromptCellularUnavailable);
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::Start(
bool has_wifi_credentials,
uint64_t now_ms)
{
DualNetworkPolicyResult result;
if (started_) {
return result;
}
started_ = true;
selected_since_ms_ = now_ms;
if (!has_wifi_credentials) {
selected_bearer_ = NetworkBearer::kNone;
result.Add(DualNetworkActionType::kRequestProvisioning);
return result;
}
selected_bearer_ = NetworkBearer::kWifi;
result.Add(DualNetworkActionType::kStartWifi);
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::Stop()
{
DualNetworkPolicyResult result;
if (!started_) {
return result;
}
if (selected_bearer_ == NetworkBearer::kWifi) {
result.Add(DualNetworkActionType::kStopWifi);
} else if (selected_bearer_ == NetworkBearer::kCellular) {
result.Add(DualNetworkActionType::kStopCellular);
}
started_ = false;
selected_bearer_ = NetworkBearer::kNone;
online_bearer_ = NetworkBearer::kNone;
wifi_disconnected_since_ms_ = 0;
weak_sample_count_ = 0;
stable_modem_presence_ = ModemPresence::kUnknown;
modem_absent_streak_ = 0;
modem_unavailable_announced_ = false;
modem_unavailable_announced_ms_ = 0;
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::OnWifiOnline(uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kWifi) {
return {};
}
online_bearer_ = NetworkBearer::kWifi;
selected_since_ms_ = now_ms;
wifi_disconnected_since_ms_ = 0;
weak_sample_count_ = 0;
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::OnWifiDisconnected(
uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kWifi) {
return {};
}
online_bearer_ = NetworkBearer::kNone;
if (wifi_disconnected_since_ms_ == 0) {
wifi_disconnected_since_ms_ = now_ms == 0 ? 1 : now_ms;
}
weak_sample_count_ = 0;
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::OnCellularOnline(
uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kCellular) {
return {};
}
online_bearer_ = NetworkBearer::kCellular;
selected_since_ms_ = now_ms;
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::OnCellularDisconnected(
uint64_t now_ms)
{
if (!started_ || selected_bearer_ != NetworkBearer::kCellular) {
return {};
}
online_bearer_ = NetworkBearer::kNone;
return SwitchToWifi(now_ms, false);
}
DualNetworkPolicyResult DualNetworkPolicy::OnMonitor(
uint64_t now_ms,
int8_t wifi_rssi_dbm,
ModemPresence modem)
{
if (!started_ || selected_bearer_ != NetworkBearer::kWifi ||
modem == ModemPresence::kAbsent) {
return {};
}
if (online_bearer_ == NetworkBearer::kWifi) {
if (wifi_rssi_dbm != 0 &&
wifi_rssi_dbm != -127 &&
wifi_rssi_dbm < config_.wifi_weak_rssi_dbm) {
if (weak_sample_count_ < UINT8_MAX) {
++weak_sample_count_;
}
} else {
weak_sample_count_ = 0;
}
if (weak_sample_count_ >= config_.wifi_weak_sample_count) {
return SwitchToCellular(now_ms, false);
}
return {};
}
if (wifi_disconnected_since_ms_ != 0 &&
now_ms >= wifi_disconnected_since_ms_ &&
now_ms - wifi_disconnected_since_ms_ >=
config_.wifi_disconnect_failover_ms) {
return SwitchToCellular(now_ms, false);
}
return {};
}
DualNetworkPolicyResult DualNetworkPolicy::RequestManualSwitch(
uint64_t now_ms,
ModemPresence modem)
{
if (!started_) {
return {};
}
if (selected_bearer_ == NetworkBearer::kCellular) {
return SwitchToWifi(now_ms, true);
}
if (modem == ModemPresence::kAbsent) {
DualNetworkPolicyResult result;
result.Add(DualNetworkActionType::kPromptCellularUnavailable);
return result;
}
return SwitchToCellular(now_ms, true);
}
DualNetworkPolicyResult DualNetworkPolicy::SwitchToCellular(
uint64_t now_ms,
bool prompt)
{
DualNetworkPolicyResult result;
if (selected_bearer_ == NetworkBearer::kCellular) {
return result;
}
if (online_bearer_ != NetworkBearer::kNone) {
result.Add(DualNetworkActionType::kNotifyDisconnected);
}
result.Add(DualNetworkActionType::kStopWifi);
result.Add(DualNetworkActionType::kStartCellular);
result.Add(DualNetworkActionType::kRequestReconnect);
if (prompt) {
result.Add(DualNetworkActionType::kPromptCellularOn);
}
selected_bearer_ = NetworkBearer::kCellular;
online_bearer_ = NetworkBearer::kNone;
selected_since_ms_ = now_ms;
wifi_disconnected_since_ms_ = 0;
weak_sample_count_ = 0;
return result;
}
DualNetworkPolicyResult DualNetworkPolicy::SwitchToWifi(
uint64_t now_ms,
bool prompt)
{
DualNetworkPolicyResult result;
if (selected_bearer_ == NetworkBearer::kWifi) {
return result;
}
if (online_bearer_ != NetworkBearer::kNone) {
result.Add(DualNetworkActionType::kNotifyDisconnected);
}
result.Add(DualNetworkActionType::kStopCellular);
result.Add(DualNetworkActionType::kStartWifi);
result.Add(DualNetworkActionType::kRequestReconnect);
if (prompt) {
result.Add(DualNetworkActionType::kPromptCellularOff);
}
selected_bearer_ = NetworkBearer::kWifi;
online_bearer_ = NetworkBearer::kNone;
selected_since_ms_ = now_ms;
wifi_disconnected_since_ms_ = now_ms == 0 ? 1 : now_ms;
weak_sample_count_ = 0;
return result;
}
} // namespace borla

View File

@@ -0,0 +1,133 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
enum class NetworkBearer : uint8_t {
kNone,
kWifi,
kCellular,
};
enum class ModemPresence : uint8_t {
kUnknown,
kAbsent,
kPresent,
};
struct DualNetworkPolicyConfig {
uint32_t wifi_disconnect_failover_ms = 30000;
int8_t wifi_weak_rssi_dbm = -80;
uint8_t wifi_weak_sample_count = 6;
// The 4G switch cuts modem power directly, so the only way to sense it is
// whether the modem answers AT. An OFF reading needs two consecutive
// misses (UART jitter produces false absences); an ON reading is accepted
// immediately because an AT reply cannot be noise.
uint8_t modem_absent_sample_count = 2;
// Re-announce "no WiFi and 4G is off" at most this often. The WiFi monitor
// fires every few seconds while disconnected.
uint32_t modem_unavailable_repeat_ms = 120000;
};
enum class DualNetworkActionType : uint8_t {
kStartWifi,
kStopWifi,
kStartCellular,
kStopCellular,
kNotifyDisconnected,
kRequestReconnect,
kRequestProvisioning,
kPromptCellularOn,
kPromptCellularOff,
kPromptCellularUnavailable,
kPromptCellularBootOn,
};
struct DualNetworkAction {
DualNetworkActionType type = DualNetworkActionType::kStartWifi;
};
struct DualNetworkPolicyResult {
std::array<DualNetworkAction, 8> actions{};
size_t action_count = 0;
bool Add(DualNetworkActionType type)
{
if (action_count >= actions.size()) {
return false;
}
actions[action_count++].type = type;
return true;
}
};
class DualNetworkPolicy final {
public:
explicit DualNetworkPolicy(
DualNetworkPolicyConfig config = DualNetworkPolicyConfig{});
DualNetworkPolicyResult Start(
bool has_wifi_credentials,
uint64_t now_ms);
DualNetworkPolicyResult Stop();
DualNetworkPolicyResult OnWifiOnline(uint64_t now_ms);
DualNetworkPolicyResult OnWifiDisconnected(uint64_t now_ms);
DualNetworkPolicyResult OnCellularOnline(uint64_t now_ms);
DualNetworkPolicyResult OnCellularDisconnected(uint64_t now_ms);
DualNetworkPolicyResult OnMonitor(
uint64_t now_ms,
int8_t wifi_rssi_dbm,
ModemPresence modem);
DualNetworkPolicyResult RequestManualSwitch(
uint64_t now_ms,
ModemPresence modem);
// Physical 4G switch sensing, independent of bearer selection: flipping
// the switch only announces itself, it never moves the device between
// WiFi and cellular. Fed by every modem probe while WiFi is the bearer.
// first known reading, present -> kPromptCellularBootOn
// absent -> present -> kPromptCellularOn
// present -> absent (debounced) -> kPromptCellularOff
DualNetworkPolicyResult OnModemPresence(
ModemPresence observed,
uint64_t now_ms);
// WiFi is down and the modem is not powered: tell the parent to flip the
// switch. Rate-limited by modem_unavailable_repeat_ms.
DualNetworkPolicyResult NotifyWifiLostWithoutModem(uint64_t now_ms);
NetworkBearer selected_bearer() const { return selected_bearer_; }
ModemPresence stable_modem_presence() const
{
return stable_modem_presence_;
}
NetworkBearer online_bearer() const { return online_bearer_; }
bool started() const { return started_; }
uint8_t weak_sample_count() const { return weak_sample_count_; }
private:
DualNetworkPolicyResult SwitchToCellular(
uint64_t now_ms,
bool prompt);
DualNetworkPolicyResult SwitchToWifi(
uint64_t now_ms,
bool prompt);
DualNetworkPolicyConfig config_;
NetworkBearer selected_bearer_ = NetworkBearer::kNone;
NetworkBearer online_bearer_ = NetworkBearer::kNone;
uint64_t wifi_disconnected_since_ms_ = 0;
uint64_t selected_since_ms_ = 0;
uint8_t weak_sample_count_ = 0;
bool started_ = false;
ModemPresence stable_modem_presence_ = ModemPresence::kUnknown;
uint8_t modem_absent_streak_ = 0;
uint64_t modem_unavailable_announced_ms_ = 0;
bool modem_unavailable_announced_ = false;
};
} // namespace borla

View File

@@ -0,0 +1,437 @@
#include "connectivity/dual_network_transport.h"
#include <algorithm>
#include <cstring>
#include <esp_err.h>
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "DualNetwork2";
constexpr uint16_t kBearerSwitchReason = 0xF101;
} // namespace
DualNetworkTransport::DualNetworkTransport(IWifiTransport& wifi,
ICellularTransport& cellular, DualNetworkPolicyConfig config)
: wifi_(wifi)
, cellular_(cellular)
, config_(config)
, policy_(config)
{
}
bool DualNetworkTransport::Initialize()
{
if (initialized_) {
return true;
}
queue_ = xQueueCreateStatic(
kQueueDepth, sizeof(Event), queue_storage_.data(), &queue_control_);
stop_completed_ = xSemaphoreCreateBinaryStatic(&stop_completed_control_);
if (queue_ == nullptr || stop_completed_ == nullptr) {
ESP_LOGE(kTag, "failed to allocate static control objects");
return false;
}
const esp_timer_create_args_t timer_args = {
.callback = &DualNetworkTransport::MonitorTimerCallback,
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "dual_net_mon",
.skip_unhandled_events = true,
};
if (esp_timer_create(&timer_args, &monitor_timer_) != ESP_OK) {
ESP_LOGE(kTag, "monitor timer creation failed");
return false;
}
const BaseType_t task_result = xTaskCreate(&DualNetworkTransport::TaskEntry,
"dual_network2", task_stack_budget::kDualNetworkBytes, this, 4, &task_);
if (task_result != pdPASS) {
task_ = nullptr;
esp_timer_delete(monitor_timer_);
monitor_timer_ = nullptr;
return false;
}
initialized_ = true;
ESP_LOGI(kTag, "initialized queue=%u stack_bytes=%u memory=internal",
static_cast<unsigned>(kQueueDepth),
static_cast<unsigned>(task_stack_budget::kDualNetworkBytes));
return true;
}
bool DualNetworkTransport::Start(IWifiTransportObserver& observer)
{
if (!initialized_ && !Initialize()) {
return false;
}
portENTER_CRITICAL(&state_lock_);
upstream_ = &observer;
portEXIT_CRITICAL(&state_lock_);
return Post({ EventType::kStart, 0, {} });
}
void DualNetworkTransport::Stop()
{
if (!initialized_) {
return;
}
xSemaphoreTake(stop_completed_, 0);
if (!Post({ EventType::kStop, 0, {} })) {
return;
}
if (xSemaphoreTake(stop_completed_, pdMS_TO_TICKS(5000)) != pdTRUE) {
ESP_LOGE(kTag, "timed out stopping network transports");
}
}
// 2026-9-7 ckkj add: 转发拆除内部 WiFi 驱动释放内部 RAM。幂等(
// EspWifiTransport 内部有 driver_initialized_ 检查),供 BLE 好友模式
// 挂起时调用;仅在 Stop() 同步完成后调用,内部任务已空闲,无竞态。
void DualNetworkTransport::ReleaseDriver()
{
wifi_.ReleaseDriver();
wifi_ready_ = false;
}////
bool DualNetworkTransport::Connect(const WifiCredential& credential)
{
if (!credential.IsValid()) {
return false;
}
Event event;
event.type = EventType::kConnect;
event.credential = credential;
return Post(event);
}
bool DualNetworkTransport::Scan(
WifiNetwork* output, size_t capacity, size_t* count)
{
return wifi_.Scan(output, capacity, count);
}
WifiLinkInfo DualNetworkTransport::GetLinkInfo() const
{
if (selected_bearer_.load() != NetworkBearer::kCellular) {
return wifi_.GetLinkInfo();
}
const CellularLinkInfo cellular = cellular_.GetLinkInfo();
WifiLinkInfo link;
link.online = cellular.online;
link.rssi_dbm = cellular.csq >= 0 && cellular.csq <= 31
? static_cast<int8_t>(-113 + (2 * cellular.csq))
: -127;
// std::strncpy(link.ssid.data(), "cellular", link.ssid.size() - 1);
// std::strncpy(link.ipv4.data(), cellular.ipv4.data(), link.ipv4.size() - 1);
snprintf(link.ssid.data(), link.ssid.size(), "%s", "cellular");
snprintf(link.ipv4.data(),link.ipv4.size(),"%s",reinterpret_cast<const char*>(cellular.ipv4.data()));
return link;
}
bool DualNetworkTransport::RequestNetworkSwitch()
{
return Post({ EventType::kManualSwitch, 0, {} });
}
void DualNetworkTransport::OnWifiTransportEvent(const WifiTransportEvent& event)
{
Event converted;
switch (event.type) {
case WifiTransportEventType::kStarted:
converted.type = EventType::kWifiStarted;
break;
case WifiTransportEventType::kGotIp:
converted.type = EventType::kWifiGotIp;
break;
case WifiTransportEventType::kDisconnected:
converted.type = EventType::kWifiDisconnected;
converted.reason = event.disconnect_reason;
break;
case WifiTransportEventType::kReconnectRequested:
case WifiTransportEventType::kCellularOn:
case WifiTransportEventType::kCellularOff:
case WifiTransportEventType::kCellularUnavailable:
case WifiTransportEventType::kCellularBootOn:
return;
}
Post(converted);
}
void DualNetworkTransport::OnCellularTransportEvent(
const CellularTransportEvent& event)
{
Event converted;
switch (event.type) {
case CellularTransportEventType::kStarted:
converted.type = EventType::kCellularStarted;
break;
case CellularTransportEventType::kGotIp:
converted.type = EventType::kCellularGotIp;
break;
case CellularTransportEventType::kDisconnected:
converted.type = EventType::kCellularDisconnected;
converted.reason = event.reason;
break;
}
Post(converted);
}
void DualNetworkTransport::TaskEntry(void* context)
{
static_cast<DualNetworkTransport*>(context)->Run();
}
void DualNetworkTransport::MonitorTimerCallback(void* context)
{
static_cast<DualNetworkTransport*>(context)->Post(
{ EventType::kMonitor, 0, {} });
}
[[noreturn]] void DualNetworkTransport::Run()
{
while (true) {
Event event;
if (xQueueReceive(queue_, &event, portMAX_DELAY) == pdTRUE) {
Handle(event);
}
}
}
bool DualNetworkTransport::Post(const Event& event)
{
return initialized_ && queue_ != nullptr
&& xQueueSend(queue_, &event, 0) == pdTRUE;
}
void DualNetworkTransport::Handle(const Event& event)
{
const uint64_t now_ms = NowMs();
switch (event.type) {
case EventType::kStart:
initial_started_published_ = false;
Execute(policy_.Start(true, now_ms));
if (monitor_timer_ != nullptr) {
const esp_err_t result = esp_timer_start_periodic(monitor_timer_,
static_cast<uint64_t>(kMonitorIntervalMs) * 1000ULL);
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "monitor timer start failed: %s",
esp_err_to_name(result));
}
}
break;
case EventType::kStop:
if (monitor_timer_ != nullptr) {
const esp_err_t result = esp_timer_stop(monitor_timer_);
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) {
ESP_LOGW(kTag, "monitor timer stop failed: %s",
esp_err_to_name(result));
}
}
Execute(policy_.Stop());
pending_wifi_connect_ = false;
wifi_ready_ = false;
selected_bearer_.store(NetworkBearer::kNone);
portENTER_CRITICAL(&state_lock_);
upstream_ = nullptr;
portEXIT_CRITICAL(&state_lock_);
xSemaphoreGive(stop_completed_);
break;
case EventType::kConnect:
pending_credential_ = event.credential;
if (policy_.selected_bearer() == NetworkBearer::kWifi) {
if (wifi_ready_) {
if (!wifi_.Connect(pending_credential_)) {
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF102,
});
}
} else {
pending_wifi_connect_ = true;
}
}
break;
case EventType::kWifiStarted:
wifi_ready_ = true;
if (!initial_started_published_) {
initial_started_published_ = true;
PublishUpstream({ WifiTransportEventType::kStarted, 0 });
}
if (pending_wifi_connect_) {
pending_wifi_connect_ = false;
if (!wifi_.Connect(pending_credential_)) {
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF102,
});
}
}
break;
case EventType::kWifiGotIp:
policy_.OnWifiOnline(now_ms);
selected_bearer_.store(NetworkBearer::kWifi);
PublishUpstream({ WifiTransportEventType::kGotIp, 0 });
break;
case EventType::kWifiDisconnected:
policy_.OnWifiDisconnected(now_ms);
PublishUpstream({
WifiTransportEventType::kDisconnected,
event.reason,
});
break;
case EventType::kCellularStarted:
modem_presence_ = ModemPresence::kPresent;
break;
case EventType::kCellularGotIp:
policy_.OnCellularOnline(now_ms);
selected_bearer_.store(NetworkBearer::kCellular);
PublishUpstream({ WifiTransportEventType::kGotIp, 0 });
break;
case EventType::kCellularDisconnected:
PublishUpstream({
WifiTransportEventType::kDisconnected,
event.reason,
});
Execute(policy_.OnCellularDisconnected(now_ms));
break;
case EventType::kMonitor: {
const WifiLinkInfo link = wifi_.GetLinkInfo();
if (policy_.selected_bearer() == NetworkBearer::kWifi && !link.online
&& (last_modem_probe_ms_ == 0 || now_ms - last_modem_probe_ms_ >= kModemProbeIntervalMs))
{
// Probe unconditionally (not only when WiFi is degraded): the
// 4G switch is a physical control the user can flip at any time
// and the announcement is the only feedback they get. Cadence is
// kModemProbeIntervalMs because each probe drives the AT UART.
// modem_presence_ = cellular_.ProbePresent() ? ModemPresence::kPresent
// : ModemPresence::kAbsent;
const CellularProbeResult probe = cellular_.ProbePresent();
last_modem_probe_ms_ = now_ms;
//Execute(policy_.OnModemPresence(modem_presence_, now_ms));//2026-9-7 ckkj mod
if (probe != CellularProbeResult::kUnknown) {
modem_presence_ = probe == CellularProbeResult::kPresent
? ModemPresence::kPresent
: ModemPresence::kAbsent;
Execute(policy_.OnModemPresence(modem_presence_, now_ms));
}
}
// The policy owns the "long enough to matter" judgement; it uses the
// same disconnect deadline as the automatic failover.
Execute(policy_.NotifyWifiLostWithoutModem(now_ms));
Execute(policy_.OnMonitor(now_ms, link.rssi_dbm, modem_presence_));
break;
}
case EventType::kManualSwitch:
if (policy_.selected_bearer() == NetworkBearer::kWifi) {
// modem_presence_ = cellular_.ProbePresent() ? ModemPresence::kPresent
// : ModemPresence::kAbsent;
const CellularProbeResult probe = cellular_.ProbePresent();
last_modem_probe_ms_ = now_ms;
// kUnknown(内存不足探测没跑成)按在位处理:切换流程先释放 WiFi
// 驱动腾出内存,真实结果由 cellular_.Start() 给出;若模块确实
// 不在位,OnCellularDisconnected 会兜底回退 WiFi。
modem_presence_ = probe == CellularProbeResult::kAbsent
? ModemPresence::kAbsent
: ModemPresence::kPresent;//2026-9-9 ckkj mod
last_modem_probe_ms_ = now_ms;
}
Execute(policy_.RequestManualSwitch(now_ms, modem_presence_));
break;
}
selected_bearer_.store(policy_.selected_bearer());
}
void DualNetworkTransport::Execute(const DualNetworkPolicyResult& result)
{
for (size_t index = 0; index < result.action_count; ++index) {
Execute(result.actions[index].type);
}
}
void DualNetworkTransport::Execute(DualNetworkActionType action)
{
switch (action) {
case DualNetworkActionType::kStartWifi:
wifi_ready_ = false;
if (!wifi_.Start(*this)) {
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF103,
});
}
return;
case DualNetworkActionType::kStopWifi:
//wifi_.Stop();
// 2026-9-6 ckkj fix: 切 4G 时仅 Stop() 不释放 WiFi 驱动的几十 KB
// 内部 RAM,堆最大连续块被压到 ~3KB,PPP UART(4096B)永远安装失败
// (largest=3072)。ReleaseDriver() 彻底拆除驱动释放内存,
// 4G->WiFi 回切时 Start() 会自动重建驱动(BLE 配网已验证此流程)。
wifi_.ReleaseDriver();//// 释放 WiFi 驱动内存
wifi_ready_ = false;
return;
case DualNetworkActionType::kStartCellular:
if (!cellular_.Start(*this)) {
Post({ EventType::kCellularDisconnected, 0xF104, {} });
}
return;
case DualNetworkActionType::kStopCellular:
cellular_.Stop();
return;
case DualNetworkActionType::kNotifyDisconnected:
PublishUpstream({
WifiTransportEventType::kDisconnected,
kBearerSwitchReason,
});
return;
case DualNetworkActionType::kRequestReconnect:
PublishUpstream({
WifiTransportEventType::kReconnectRequested,
0,
});
return;
case DualNetworkActionType::kRequestProvisioning:
PublishUpstream({
WifiTransportEventType::kDisconnected,
0xF105,
});
return;
case DualNetworkActionType::kPromptCellularOn:
PublishUpstream({ WifiTransportEventType::kCellularOn, 0 });
return;
case DualNetworkActionType::kPromptCellularOff:
PublishUpstream({ WifiTransportEventType::kCellularOff, 0 });
return;
case DualNetworkActionType::kPromptCellularUnavailable:
PublishUpstream({
WifiTransportEventType::kCellularUnavailable,
0,
});
return;
case DualNetworkActionType::kPromptCellularBootOn:
PublishUpstream({
WifiTransportEventType::kCellularBootOn,
0,
});
return;
}
}
void DualNetworkTransport::PublishUpstream(const WifiTransportEvent& event)
{
portENTER_CRITICAL(&state_lock_);
IWifiTransportObserver* const observer = upstream_;
portEXIT_CRITICAL(&state_lock_);
if (observer != nullptr) {
observer->OnWifiTransportEvent(event);
}
}
uint64_t DualNetworkTransport::NowMs() const
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace borla

View File

@@ -0,0 +1,104 @@
#pragma once
#include "connectivity/cellular_transport.h"
#include "connectivity/dual_network_policy.h"
#include "connectivity/wifi_transport.h"
#include "core/task_stack_budget.h"
#include <array>
#include <atomic>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include <freertos/queue.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class DualNetworkTransport final : public IWifiTransport,
public IWifiTransportObserver,
public ICellularTransportObserver {
public:
DualNetworkTransport(IWifiTransport& wifi, ICellularTransport& cellular,
DualNetworkPolicyConfig config);
bool Initialize();
bool Start(IWifiTransportObserver& observer) override;
void Stop() override;
// 2026-9-7 ckkj add: 彻底拆除内部 WiFi 驱动释放内部 RAM(BLE 好友模式
// 挂起时由 ConnectivityManager 调用);不发布事件,下一步 Start() 重建驱动。
void ReleaseDriver() override;////
bool Connect(const WifiCredential& credential) override;
bool Scan(WifiNetwork* output, size_t capacity, size_t* count) override;
WifiLinkInfo GetLinkInfo() const override;
bool RequestNetworkSwitch() override;
void OnWifiTransportEvent(const WifiTransportEvent& event) override;
void OnCellularTransportEvent(const CellularTransportEvent& event) override;
NetworkBearer SelectedBearer() const { return selected_bearer_.load(); }
private:
enum class EventType : uint8_t {
kStart,
kStop,
kConnect,
kWifiStarted,
kWifiGotIp,
kWifiDisconnected,
kCellularStarted,
kCellularGotIp,
kCellularDisconnected,
kMonitor,
kManualSwitch,
};
struct Event {
EventType type = EventType::kStart;
uint16_t reason = 0;
WifiCredential credential {};
};
static constexpr size_t kQueueDepth = 20;
static constexpr uint32_t kMonitorIntervalMs = 5000;
static constexpr uint32_t kModemProbeIntervalMs = 30000;
static void TaskEntry(void* context);
static void MonitorTimerCallback(void* context);
[[noreturn]] void Run();
bool Post(const Event& event);
void Handle(const Event& event);
void Execute(const DualNetworkPolicyResult& result);
void Execute(DualNetworkActionType action);
void PublishUpstream(const WifiTransportEvent& event);
uint64_t NowMs() const;
IWifiTransport& wifi_;
ICellularTransport& cellular_;
DualNetworkPolicyConfig config_;
DualNetworkPolicy policy_;
mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED;
IWifiTransportObserver* upstream_ = nullptr;
WifiCredential pending_credential_ {};
bool pending_wifi_connect_ = false;
bool wifi_ready_ = false;
bool initial_started_published_ = false;
ModemPresence modem_presence_ = ModemPresence::kUnknown;
uint64_t last_modem_probe_ms_ = 0;
QueueHandle_t queue_ = nullptr;
StaticQueue_t queue_control_ {};
alignas(Event)
std::array<uint8_t, kQueueDepth * sizeof(Event)> queue_storage_ {};
TaskHandle_t task_ = nullptr;
SemaphoreHandle_t stop_completed_ = nullptr;
StaticSemaphore_t stop_completed_control_ {};
esp_timer_handle_t monitor_timer_ = nullptr;
bool initialized_ = false;
std::atomic<NetworkBearer> selected_bearer_ { NetworkBearer::kNone };
};
} // namespace borla

View File

@@ -0,0 +1,90 @@
#include "connectivity/ml307_at_parser.h"
#include <cstdio>
#include <cstring>
namespace borla {
bool ParseMl307Registration(
const char* response,
CellularRegistration* registration)
{
if (response == nullptr || registration == nullptr) {
return false;
}
const char* marker = std::strstr(response, "+CEREG:");
if (marker == nullptr) {
return false;
}
unsigned mode = 0;
unsigned status = 0;
const int fields =
std::sscanf(marker, "+CEREG: %u,%u", &mode, &status);
if (fields == 1) {
status = mode;
mode = 0;
} else if (fields != 2) {
return false;
}
if (mode > UINT8_MAX || status > UINT8_MAX) {
return false;
}
registration->mode = static_cast<uint8_t>(mode);
registration->status = static_cast<uint8_t>(status);
return true;
}
bool ParseMl307SignalQuality(const char* response, int8_t* csq)
{
if (response == nullptr || csq == nullptr) {
return false;
}
const char* marker = std::strstr(response, "+CSQ:");
if (marker == nullptr) {
return false;
}
int value = -1;
if (std::sscanf(marker, "+CSQ: %d", &value) != 1 ||
!((value >= 0 && value <= 31) || value == 99)) {
return false;
}
*csq = value == 99 ? -1 : static_cast<int8_t>(value);
return true;
}
bool CopyMl307ResponseLine(
const char* response,
const char* prefix,
char* output,
size_t output_capacity)
{
if (response == nullptr || prefix == nullptr || output == nullptr ||
output_capacity == 0) {
return false;
}
const char* begin =
prefix[0] == '\0' ? response : std::strstr(response, prefix);
if (begin == nullptr) {
return false;
}
begin += std::strlen(prefix);
while (*begin == ' ' || *begin == ':' || *begin == '"' ||
*begin == '\r' || *begin == '\n') {
++begin;
}
const char* end = begin;
while (*end != '\0' && *end != '\r' && *end != '\n' &&
*end != '"') {
++end;
}
const size_t size = static_cast<size_t>(end - begin);
if (size == 0 || size >= output_capacity) {
return false;
}
std::memset(output, 0, output_capacity);
std::memcpy(output, begin, size);
return true;
}
} // namespace borla

View File

@@ -0,0 +1,31 @@
#pragma once
#include <cstddef>
#include <cstdint>
namespace borla {
struct CellularRegistration {
uint8_t mode = 0;
uint8_t status = 0;
bool IsRegistered() const
{
return status == 1 || status == 5;
}
};
bool ParseMl307Registration(
const char* response,
CellularRegistration* registration);
bool ParseMl307SignalQuality(
const char* response,
int8_t* csq);
bool CopyMl307ResponseLine(
const char* response,
const char* prefix,
char* output,
size_t output_capacity);
} // namespace borla

View File

@@ -0,0 +1,62 @@
#include "connectivity/reconnect_backoff.h"
#include <algorithm>
#include <cstdint>
#include <limits>
namespace borla {
ReconnectBackoff::ReconnectBackoff(ReconnectBackoffConfig config)
: config_(Normalize(config))
{
}
uint32_t ReconnectBackoff::NextDelayMs(uint32_t entropy)
{
if (current_base_delay_ms_ == 0) {
current_base_delay_ms_ = config_.initial_delay_ms;
} else {
const uint64_t multiplied =
static_cast<uint64_t>(current_base_delay_ms_) *
config_.multiplier;
current_base_delay_ms_ = static_cast<uint32_t>(
std::min<uint64_t>(multiplied, config_.maximum_delay_ms));
}
++attempt_count_;
const uint32_t jitter_range = static_cast<uint32_t>(
(static_cast<uint64_t>(current_base_delay_ms_) *
config_.jitter_percent) /
100U);
if (jitter_range == 0) {
return current_base_delay_ms_;
}
const uint64_t bucket_count =
static_cast<uint64_t>(jitter_range) * 2U + 1U;
const int64_t offset =
static_cast<int64_t>(entropy % bucket_count) -
static_cast<int64_t>(jitter_range);
const int64_t jittered =
static_cast<int64_t>(current_base_delay_ms_) + offset;
return static_cast<uint32_t>(std::max<int64_t>(1, jittered));
}
void ReconnectBackoff::Reset()
{
current_base_delay_ms_ = 0;
attempt_count_ = 0;
}
ReconnectBackoffConfig ReconnectBackoff::Normalize(
ReconnectBackoffConfig config)
{
config.initial_delay_ms = std::max<uint32_t>(1, config.initial_delay_ms);
config.maximum_delay_ms =
std::max(config.initial_delay_ms, config.maximum_delay_ms);
config.multiplier = std::max<uint8_t>(1, config.multiplier);
config.jitter_percent = std::min<uint8_t>(50, config.jitter_percent);
return config;
}
} // namespace borla

View File

@@ -0,0 +1,35 @@
#pragma once
#include <cstdint>
namespace borla {
struct ReconnectBackoffConfig {
uint32_t initial_delay_ms = 1000;
uint32_t maximum_delay_ms = 60000;
uint8_t multiplier = 2;
uint8_t jitter_percent = 20;
};
class ReconnectBackoff final {
public:
explicit ReconnectBackoff(
ReconnectBackoffConfig config = ReconnectBackoffConfig{});
uint32_t NextDelayMs(uint32_t entropy);
void Reset();
uint32_t attempt_count() const { return attempt_count_; }
uint32_t current_base_delay_ms() const { return current_base_delay_ms_; }
const ReconnectBackoffConfig& config() const { return config_; }
private:
static ReconnectBackoffConfig Normalize(
ReconnectBackoffConfig config);
ReconnectBackoffConfig config_;
uint32_t current_base_delay_ms_ = 0;
uint32_t attempt_count_ = 0;
};
} // namespace borla

View File

@@ -0,0 +1,229 @@
#include "connectivity/wifi_credential_store.h"
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstring>
#include <esp_err.h>
#include <esp_log.h>
#include <nvs.h>
namespace borla {
namespace {
constexpr const char* kTag = "WifiCredentials2";
constexpr const char* kNvsNamespace = "wifi";
void MakeKey(const char* prefix, size_t index, char* output, size_t size)
{
if (index == 0) {
std::snprintf(output, size, "%s", prefix);
} else {
std::snprintf(output, size, "%s%u", prefix,
static_cast<unsigned>(index));
}
}
bool SameSsid(const WifiCredential& credential, const char* ssid)
{
return ssid != nullptr &&
std::strncmp(
credential.ssid.data(), ssid, credential.ssid.size()) == 0;
}
} // namespace
size_t NvsWifiCredentialStore::Load(
WifiCredential* output,
size_t capacity) const
{
if (output == nullptr || capacity == 0) {
return 0;
}
nvs_handle_t handle = 0;
const esp_err_t open_result =
nvs_open(kNvsNamespace, NVS_READONLY, &handle);
if (open_result == ESP_ERR_NVS_NOT_FOUND) {
return 0;
}
if (open_result != ESP_OK) {
ESP_LOGE(kTag, "open namespace failed: %s",
esp_err_to_name(open_result));
return 0;
}
size_t count = 0;
for (size_t index = 0;
index < kMaxSavedWifiCredentials && count < capacity;
++index) {
char ssid_key[16]{};
char password_key[16]{};
MakeKey("ssid", index, ssid_key, sizeof(ssid_key));
MakeKey("password", index, password_key, sizeof(password_key));
WifiCredential credential;
size_t ssid_size = credential.ssid.size();
size_t password_size = credential.password.size();
if (nvs_get_str(
handle, ssid_key, credential.ssid.data(), &ssid_size) !=
ESP_OK) {
continue;
}
if (nvs_get_str(
handle, password_key, credential.password.data(),
&password_size) != ESP_OK) {
continue;
}
if (!credential.IsValid()) {
ESP_LOGW(kTag, "ignored invalid credential slot=%u",
static_cast<unsigned>(index));
continue;
}
output[count++] = credential;
}
nvs_close(handle);
ESP_LOGI(kTag, "loaded %u saved WiFi credential(s)",
static_cast<unsigned>(count));
return count;
}
bool NvsWifiCredentialStore::SaveAndPromote(
const WifiCredential& credential)
{
if (!credential.IsValid()) {
ESP_LOGE(kTag, "refused invalid WiFi credential");
return false;
}
std::array<WifiCredential, kMaxSavedWifiCredentials> credentials{};
size_t count = Load(credentials.data(), credentials.size());
size_t existing = count;
for (size_t index = 0; index < count; ++index) {
if (SameSsid(credentials[index], credential.ssid.data())) {
existing = index;
break;
}
}
if (existing < count) {
for (size_t index = existing; index > 0; --index) {
credentials[index] = credentials[index - 1];
}
} else {
count = std::min(count + 1U, credentials.size());
for (size_t index = count - 1; index > 0; --index) {
credentials[index] = credentials[index - 1];
}
}
credentials[0] = credential;
if (!SaveAll(credentials.data(), count)) {
return false;
}
ESP_LOGI(kTag, "saved WiFi credential ssid=%s",
credential.ssid.data());
return true;
}
bool NvsWifiCredentialStore::Remove(const char* ssid)
{
if (ssid == nullptr || ssid[0] == '\0') {
return false;
}
std::array<WifiCredential, kMaxSavedWifiCredentials> credentials{};
size_t count = Load(credentials.data(), credentials.size());
size_t remove_index = count;
for (size_t index = 0; index < count; ++index) {
if (SameSsid(credentials[index], ssid)) {
remove_index = index;
break;
}
}
if (remove_index == count) {
return false;
}
for (size_t index = remove_index; index + 1 < count; ++index) {
credentials[index] = credentials[index + 1];
}
--count;
if (!SaveAll(credentials.data(), count)) {
return false;
}
ESP_LOGI(kTag, "removed WiFi credential ssid=%s", ssid);
return true;
}
bool NvsWifiCredentialStore::Clear()
{
return SaveAll(nullptr, 0);
}
bool NvsWifiCredentialStore::SaveAll(
const WifiCredential* credentials,
size_t count) const
{
if ((credentials == nullptr && count != 0) ||
count > kMaxSavedWifiCredentials) {
return false;
}
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNvsNamespace, NVS_READWRITE, &handle);
if (result != ESP_OK) {
ESP_LOGE(kTag, "open writable namespace failed: %s",
esp_err_to_name(result));
return false;
}
for (size_t index = 0; index < kMaxSavedWifiCredentials; ++index) {
char ssid_key[16]{};
char password_key[16]{};
MakeKey("ssid", index, ssid_key, sizeof(ssid_key));
MakeKey("password", index, password_key, sizeof(password_key));
if (index < count) {
result = nvs_set_str(
handle, ssid_key, credentials[index].ssid.data());
if (result == ESP_OK) {
result = nvs_set_str(
handle, password_key,
credentials[index].password.data());
}
} else {
const esp_err_t ssid_result = nvs_erase_key(handle, ssid_key);
const esp_err_t password_result =
nvs_erase_key(handle, password_key);
if (ssid_result != ESP_OK &&
ssid_result != ESP_ERR_NVS_NOT_FOUND) {
result = ssid_result;
}
if (password_result != ESP_OK &&
password_result != ESP_ERR_NVS_NOT_FOUND) {
result = password_result;
}
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "write credential slot=%u failed: %s",
static_cast<unsigned>(index),
esp_err_to_name(result));
nvs_close(handle);
return false;
}
}
result = nvs_commit(handle);
nvs_close(handle);
if (result != ESP_OK) {
ESP_LOGE(kTag, "commit credentials failed: %s",
esp_err_to_name(result));
return false;
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,32 @@
#pragma once
#include "connectivity/wifi_types.h"
#include <cstddef>
namespace borla {
class IWifiCredentialStore {
public:
virtual ~IWifiCredentialStore() = default;
virtual size_t Load(WifiCredential* output, size_t capacity) const = 0;
virtual bool SaveAndPromote(const WifiCredential& credential) = 0;
virtual bool Remove(const char* ssid) = 0;
virtual bool Clear() = 0;
};
class NvsWifiCredentialStore final : public IWifiCredentialStore {
public:
size_t Load(WifiCredential* output, size_t capacity) const override;
bool SaveAndPromote(const WifiCredential& credential) override;
bool Remove(const char* ssid) override;
bool Clear() override;
private:
bool SaveAll(
const WifiCredential* credentials,
size_t count) const;
};
} // namespace borla

View File

@@ -0,0 +1,69 @@
#pragma once
#include "connectivity/wifi_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
enum class WifiTransportEventType : uint8_t {
kStarted,
kGotIp,
kDisconnected,
kReconnectRequested,
kCellularOn,
kCellularOff,
kCellularUnavailable,
kCellularBootOn,
};
struct WifiTransportEvent {
WifiTransportEventType type = WifiTransportEventType::kStarted;
uint16_t disconnect_reason = 0;
};
class IWifiTransportObserver {
public:
virtual ~IWifiTransportObserver() = default;
virtual void OnWifiTransportEvent(
const WifiTransportEvent& event) = 0;
};
class IWifiTransport {
public:
virtual ~IWifiTransport() = default;
virtual bool Start(IWifiTransportObserver& observer) = 0;
virtual void Stop() = 0;
// Stop() only halts the driver; it keeps tens of KB of internal RAM in
// static/dynamic packet buffers. ReleaseDriver() tears the driver all the
// way down so that memory is available to something else — currently the
// BLE controller, which needs ~65 KB internal and cannot coexist with an
// idle-but-initialised WiFi driver on this board. The next Start() brings
// the driver back up. Default is a no-op for transports without one.
virtual void ReleaseDriver() {}
// Selects a trimmed buffer configuration for the next InitializeDriver().
//
// The default profile wants ~36 KB of internal RAM, most of it 10 static
// 1600-byte RX buffers. That is unaffordable in exactly one place: BLE
// provisioning, where the BT controller already holds ~53 KB and the
// driver has to come back up to test the credential the phone just sent.
// Field log: free=44287 at that moment, esp_wifi_init consumed 34 KB and
// then failed on the tenth RX buffer with ESP_ERR_NO_MEM, so the app
// reported "connection failed" on a perfectly good password.
//
// That link only has to associate and pull a DHCP lease before the driver
// is stopped again and the phone reboots the device, so throughput is
// irrelevant there. Everywhere else the default profile stays.
virtual void UseLowMemoryProfile(bool enabled) { (void)enabled; }
virtual bool Connect(const WifiCredential& credential) = 0;
virtual bool Scan(
WifiNetwork* output,
size_t capacity,
size_t* count) = 0;
virtual WifiLinkInfo GetLinkInfo() const = 0;
virtual bool RequestNetworkSwitch() { return false; }
};
} // namespace borla

View File

@@ -0,0 +1,78 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
namespace borla {
inline constexpr size_t kWifiSsidCapacity = 33;
inline constexpr size_t kWifiPasswordCapacity = 65;
inline constexpr size_t kWifiIpv4Capacity = 16;
inline constexpr size_t kMaxSavedWifiCredentials = 10;
inline constexpr size_t kMaxProvisioningScanResults = 20;
inline size_t BoundedStringLength(const char* value, size_t capacity)
{
if (value == nullptr) {
return capacity;
}
size_t length = 0;
while (length < capacity && value[length] != '\0') {
++length;
}
return length;
}
struct WifiCredential {
std::array<char, kWifiSsidCapacity> ssid{};
std::array<char, kWifiPasswordCapacity> password{};
bool Set(const char* new_ssid, const char* new_password)
{
if (new_ssid == nullptr || new_password == nullptr) {
return false;
}
const size_t ssid_length =
BoundedStringLength(new_ssid, kWifiSsidCapacity);
const size_t password_length =
BoundedStringLength(new_password, kWifiPasswordCapacity);
if (ssid_length == 0 || ssid_length >= kWifiSsidCapacity ||
password_length >= kWifiPasswordCapacity) {
return false;
}
ssid.fill('\0');
password.fill('\0');
std::memcpy(ssid.data(), new_ssid, ssid_length);
std::memcpy(password.data(), new_password, password_length);
return true;
}
bool IsValid() const
{
return ssid[0] != '\0' &&
BoundedStringLength(ssid.data(), ssid.size()) < ssid.size() &&
BoundedStringLength(password.data(), password.size()) <
password.size();
}
};
struct WifiLinkInfo {
bool online = false;
int8_t rssi_dbm = -127;
uint8_t channel = 0;
uint16_t last_disconnect_reason = 0;
std::array<char, kWifiSsidCapacity> ssid{};
std::array<char, kWifiIpv4Capacity> ipv4{};
};
struct WifiNetwork {
std::array<char, kWifiSsidCapacity> ssid{};
int8_t rssi_dbm = -127;
uint8_t auth_mode = 0;
};
} // namespace borla

90
main/core/app_effect.cc Normal file
View File

@@ -0,0 +1,90 @@
#include "core/app_effect.h"
namespace borla {
const char* ToString(AppEffectType type)
{
switch (type) {
case AppEffectType::kStartAudio:
return "start_audio";
case AppEffectType::kStopAudio:
return "stop_audio";
case AppEffectType::kStartConnectivity:
return "start_connectivity";
case AppEffectType::kStopConnectivity:
return "stop_connectivity";
case AppEffectType::kSwitchNetwork:
return "switch_network";
case AppEffectType::kOpenRealtime:
return "open_realtime";
case AppEffectType::kCloseRealtime:
return "close_realtime";
case AppEffectType::kSendStartListening:
return "send_start_listening";
case AppEffectType::kSendStopListening:
return "send_stop_listening";
case AppEffectType::kSendAbortSpeaking:
return "send_abort_speaking";
case AppEffectType::kSendGoodbye:
return "send_goodbye";
case AppEffectType::kSendAcceptCall:
return "send_accept_call";
case AppEffectType::kSendHangupCall:
return "send_hangup_call";
case AppEffectType::kSendButtonClick:
return "send_button_click";
case AppEffectType::kSendLocalPlaybackStarted:
return "send_local_playback_started";
case AppEffectType::kSendLocalPlaybackDone:
return "send_local_playback_done";
case AppEffectType::kBeginRemotePlayback:
return "begin_remote_playback";
case AppEffectType::kEndPlaybackInput:
return "end_playback_input";
case AppEffectType::kPlayLocalPrompt:
return "play_local_prompt";
case AppEffectType::kPlayDetachedPrompt:
return "play_detached_prompt";
case AppEffectType::kApplyAudioPolicy:
return "apply_audio_policy";
case AppEffectType::kSetAudioVolume:
return "set_audio_volume";
case AppEffectType::kSetWakeWordEnabled:
return "set_wake_word_enabled";
case AppEffectType::kSetBargeInEnabled:
return "set_barge_in_enabled";
case AppEffectType::kPausePlayback:
return "pause_playback";
case AppEffectType::kResumePlayback:
return "resume_playback";
case AppEffectType::kCancelPlayback:
return "cancel_playback";
case AppEffectType::kSetLed:
return "set_led";
case AppEffectType::kShowTemporaryLedAlert:
return "show_temporary_led_alert";
case AppEffectType::kStartFriendMode:
return "start_friend_mode";
case AppEffectType::kStopFriendMode:
return "stop_friend_mode";
case AppEffectType::kEnterProvisioning:
return "enter_provisioning";
case AppEffectType::kStartUpgrade:
return "start_upgrade";
case AppEffectType::kReboot:
return "reboot";
case AppEffectType::kEnterSoftOff:
return "enter_soft_off";
case AppEffectType::kStartAlert:
return "start_alert";
case AppEffectType::kStopAlert:
return "stop_alert";
case AppEffectType::kRequestConnectionErrorPrompt:
return "request_connection_error_prompt";
case AppEffectType::kReportError:
return "report_error";
}
return "unknown";
}
} // namespace borla

172
main/core/app_effect.h Normal file
View File

@@ -0,0 +1,172 @@
#pragma once
#include "core/playback_types.h"
#include "core/runtime_state.h"
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
enum class AppEffectType : uint8_t {
kStartAudio,
kStopAudio,
kStartConnectivity,
kStopConnectivity,
kSwitchNetwork,
kOpenRealtime,
kCloseRealtime,
kSendStartListening,
kSendStopListening,
kSendAbortSpeaking,
kSendGoodbye,
kSendAcceptCall,
kSendHangupCall,
kSendButtonClick,
kSendLocalPlaybackStarted,
kSendLocalPlaybackDone,
kBeginRemotePlayback,
kEndPlaybackInput,
kPlayLocalPrompt,
kPlayDetachedPrompt,
kApplyAudioPolicy,
kSetAudioVolume,
kSetWakeWordEnabled,
kSetBargeInEnabled,
kPausePlayback,
kResumePlayback,
kCancelPlayback,
kSetLed,
kShowTemporaryLedAlert,
kStartFriendMode,
kStopFriendMode,
kEnterProvisioning,
kStartUpgrade,
kReboot,
kEnterSoftOff,
kStartAlert,
kStopAlert,
kRequestConnectionErrorPrompt,
kReportError,
};
struct AppEffect {
AppEffectType type = AppEffectType::kReportError;
uint32_t correlation_id = 0;
AudioPolicy audio_policy = AudioPolicy::kOff;
LedPattern led_pattern = LedPattern::kOff;
PlaybackPriority playback_priority = PlaybackPriority::kConversation;
ConversationInterruptSource interrupt_source =
ConversationInterruptSource::kUserInitiated;
LocalPrompt local_prompt = LocalPrompt::kBoot;
int16_t prompt_selector = -1;
AlertKind alert_kind = AlertKind::kReminder;
static AppEffect Simple(AppEffectType type, uint32_t correlation_id = 0)
{
AppEffect effect;
effect.type = type;
effect.correlation_id = correlation_id;
return effect;
}
static AppEffect Audio(AudioPolicy policy)
{
AppEffect effect;
effect.type = AppEffectType::kApplyAudioPolicy;
effect.audio_policy = policy;
return effect;
}
static AppEffect Abort(ConversationInterruptSource source)
{
AppEffect effect;
effect.type = AppEffectType::kSendAbortSpeaking;
effect.interrupt_source = source;
return effect;
}
static AppEffect Led(LedPattern pattern)
{
AppEffect effect;
effect.type = AppEffectType::kSetLed;
effect.led_pattern = pattern;
return effect;
}
static AppEffect RemotePlayback(
AppEffectType type,
PlaybackSessionId session_id,
PlaybackPriority priority = PlaybackPriority::kConversation)
{
AppEffect effect;
effect.type = type;
effect.correlation_id = session_id;
effect.playback_priority = priority;
return effect;
}
static AppEffect Prompt(
LocalPrompt prompt,
PlaybackPriority priority = PlaybackPriority::kLocalPrompt,
int16_t selector = -1)
{
AppEffect effect;
effect.type = AppEffectType::kPlayLocalPrompt;
effect.local_prompt = prompt;
effect.playback_priority = priority;
effect.prompt_selector = selector;
return effect;
}
static AppEffect DetachedPrompt(
LocalPrompt prompt,
PlaybackPriority priority = PlaybackPriority::kLocalPrompt)
{
AppEffect effect;
effect.type = AppEffectType::kPlayDetachedPrompt;
effect.local_prompt = prompt;
effect.playback_priority = priority;
return effect;
}
static AppEffect LocalPlaybackState(
AppEffectType type,
LocalPrompt prompt)
{
AppEffect effect;
effect.type = type;
effect.local_prompt = prompt;
return effect;
}
static AppEffect Alert(AlertKind kind)
{
AppEffect effect;
effect.type = AppEffectType::kStartAlert;
effect.alert_kind = kind;
return effect;
}
};
constexpr size_t kMaxEffectsPerTransition = 10;
struct TransitionResult {
RuntimeState next;
std::array<AppEffect, kMaxEffectsPerTransition> effects{};
size_t effect_count = 0;
bool AddEffect(const AppEffect& effect)
{
if (effect_count >= effects.size()) {
return false;
}
effects[effect_count++] = effect;
return true;
}
};
const char* ToString(AppEffectType type);
} // namespace borla

116
main/core/app_event.cc Normal file
View File

@@ -0,0 +1,116 @@
#include "core/app_event.h"
namespace borla {
const char* ToString(AppEventType type)
{
switch (type) {
case AppEventType::kBootRequested:
return "boot_requested";
case AppEventType::kNetworkConnected:
return "network_connected";
case AppEventType::kNetworkDisconnected:
return "network_disconnected";
case AppEventType::kRealtimeConnected:
return "realtime_connected";
case AppEventType::kRealtimeDisconnected:
return "realtime_disconnected";
case AppEventType::kRealtimeProtocolError:
return "realtime_protocol_error";
case AppEventType::kButtonClicked:
return "button_clicked";
case AppEventType::kButtonLongPressed:
return "button_long_pressed";
case AppEventType::kAudioVolumeRequested:
return "audio_volume_requested";
case AppEventType::kWakeWordControlRequested:
return "wake_word_control_requested";
case AppEventType::kBargeInControlRequested:
return "barge_in_control_requested";
case AppEventType::kRemoteIdleSleepRequested:
return "remote_idle_sleep_requested";
case AppEventType::kLedAlertRequested:
return "led_alert_requested";
case AppEventType::kWakeWordDetected:
return "wake_word_detected";
case AppEventType::kBargeInCandidate:
return "barge_in_candidate";
case AppEventType::kBargeInRejected:
return "barge_in_rejected";
case AppEventType::kBargeInConfirmed:
return "barge_in_confirmed";
case AppEventType::kConversationStopRequested:
return "conversation_stop_requested";
case AppEventType::kTtsStarted:
return "tts_started";
case AppEventType::kTtsStreamEnded:
return "tts_stream_ended";
case AppEventType::kPlaybackPreempted:
return "playback_preempted";
case AppEventType::kPlaybackDrained:
return "playback_drained";
case AppEventType::kPlaybackFailed:
return "playback_failed";
case AppEventType::kLocalPromptRequested:
return "local_prompt_requested";
case AppEventType::kLocalPromptStarted:
return "local_prompt_started";
case AppEventType::kLocalSequenceRequested:
return "local_sequence_requested";
case AppEventType::kLocalSequenceStarted:
return "local_sequence_started";
case AppEventType::kActivationReplayDue:
return "activation_replay_due";
case AppEventType::kShutdownPromptRequested:
return "shutdown_prompt_requested";
case AppEventType::kUserActivityDetected:
return "user_activity_detected";
case AppEventType::kIdleCheckDue:
return "idle_check_due";
case AppEventType::kIdleResponseExpired:
return "idle_response_expired";
case AppEventType::kIdleGoodbyeDue:
return "idle_goodbye_due";
case AppEventType::kReminderDue:
return "reminder_due";
case AppEventType::kAlarmDue:
return "alarm_due";
case AppEventType::kFirstDayAlarmDue:
return "first_day_alarm_due";
case AppEventType::kAlertFinished:
return "alert_finished";
case AppEventType::kLowBatteryWarning:
return "low_battery_warning";
case AppEventType::kCriticalBattery:
return "critical_battery";
case AppEventType::kOutgoingCall:
return "outgoing_call";
case AppEventType::kIncomingCall:
return "incoming_call";
case AppEventType::kCallConnected:
return "call_connected";
case AppEventType::kCallEnded:
return "call_ended";
case AppEventType::kFriendModeEnded:
return "friend_mode_ended";
case AppEventType::kProvisioningRequested:
return "provisioning_requested";
case AppEventType::kProvisioningWifiSaved:
return "provisioning_wifi_saved";
case AppEventType::kProvisioningCompleted:
return "provisioning_completed";
case AppEventType::kUpgradeRequested:
return "upgrade_requested";
case AppEventType::kUpgradeCompleted:
return "upgrade_completed";
case AppEventType::kUpgradeFailed:
return "upgrade_failed";
case AppEventType::kSoftOffRequested:
return "soft_off_requested";
case AppEventType::kFatalError:
return "fatal_error";
}
return "unknown";
}
} // namespace borla

86
main/core/app_event.h Normal file
View File

@@ -0,0 +1,86 @@
#pragma once
#include <cstdint>
#include <type_traits>
namespace borla {
enum class AppEventType : uint8_t {
kBootRequested,
kNetworkConnected,
kNetworkDisconnected,
kRealtimeConnected,
kRealtimeDisconnected,
kRealtimeProtocolError,
kButtonClicked,
kButtonLongPressed,
kAudioVolumeRequested,
kWakeWordControlRequested,
kBargeInControlRequested,
kRemoteIdleSleepRequested,
kLedAlertRequested,
kWakeWordDetected,
kBargeInCandidate,
kBargeInRejected,
kBargeInConfirmed,
kConversationStopRequested,
kTtsStarted,
kTtsStreamEnded,
kPlaybackPreempted,
kPlaybackDrained,
kPlaybackFailed,
kLocalPromptRequested,
kLocalPromptStarted,
kLocalSequenceRequested,
kLocalSequenceStarted,
kActivationReplayDue,
kShutdownPromptRequested,
kUserActivityDetected,
kIdleCheckDue,
kIdleResponseExpired,
kIdleGoodbyeDue,
kReminderDue,
kAlarmDue,
kFirstDayAlarmDue,
kAlertFinished,
kLowBatteryWarning,
kCriticalBattery,
kOutgoingCall,
kIncomingCall,
kCallConnected,
kCallEnded,
kFriendModeEnded,
kProvisioningRequested,
// Credentials were accepted and written to NVS. Provisioning stays active
// afterwards: the miniprogram still owns the reboot that leaves this mode.
kProvisioningWifiSaved,
kProvisioningCompleted,
kUpgradeRequested,
kUpgradeCompleted,
kUpgradeFailed,
kSoftOffRequested,
kFatalError,
};
// Control-plane event only. Raw audio and JSON payloads must stay in their
// respective data planes. Keeping this type trivially copyable makes it safe
// for a statically allocated FreeRTOS queue.
struct AppEvent {
AppEventType type = AppEventType::kBootRequested;
uint32_t correlation_id = 0;
int32_t value = 0;
uint32_t flags = 0;
static AppEvent Make(AppEventType type, uint32_t correlation_id = 0,
int32_t value = 0, uint32_t flags = 0)
{
return AppEvent{type, correlation_id, value, flags};
}
};
static_assert(std::is_trivially_copyable<AppEvent>::value,
"AppEvent must remain safe for FreeRTOS queue copies");
const char* ToString(AppEventType type);
} // namespace borla

122
main/core/playback_types.cc Normal file
View File

@@ -0,0 +1,122 @@
#include "core/playback_types.h"
namespace borla {
const char* ToString(PlaybackSource source)
{
switch (source) {
case PlaybackSource::kRemoteTts:
return "remote_tts";
case PlaybackSource::kRemoteMusic:
return "remote_music";
case PlaybackSource::kLocalPrompt:
return "local_prompt";
case PlaybackSource::kAlarm:
return "alarm";
case PlaybackSource::kCall:
return "call";
}
return "unknown";
}
const char* ToString(PlaybackPriority priority)
{
switch (priority) {
case PlaybackPriority::kBackground:
return "background";
case PlaybackPriority::kConversation:
return "conversation";
case PlaybackPriority::kLocalPrompt:
return "local_prompt";
case PlaybackPriority::kSystem:
return "system";
case PlaybackPriority::kAlarm:
return "alarm";
case PlaybackPriority::kCall:
return "call";
}
return "unknown";
}
const char* ToString(LocalPrompt prompt)
{
switch (prompt) {
case LocalPrompt::kActivationDevice:
return "activation_device";
case LocalPrompt::kDeviceAlreadyBound:
return "device_already_bound";
case LocalPrompt::kServerError:
return "server_error";
case LocalPrompt::kAlarmWake:
return "alarm_wake";
case LocalPrompt::kAlarmSet:
return "alarm_set";
case LocalPrompt::kNoNetwork:
return "no_network";
case LocalPrompt::kProvisioning:
return "provisioning";
case LocalPrompt::kWakeResponse:
return "wake_response";
case LocalPrompt::kStoryExpired:
return "story_expired";
case LocalPrompt::kIdleCheck:
return "idle_check";
case LocalPrompt::kIdleGoodbye:
return "idle_goodbye";
case LocalPrompt::kSnoreLight:
return "snore_light";
case LocalPrompt::kWifiSuccess:
return "wifi_success";
case LocalPrompt::kWelcome:
return "welcome";
case LocalPrompt::kShutdown:
return "shutdown";
case LocalPrompt::kBoot:
return "boot";
case LocalPrompt::kError:
return "error";
case LocalPrompt::kLowBattery20:
return "low_battery_20";
case LocalPrompt::kLowBattery10:
return "low_battery_10";
case LocalPrompt::kNet4gBootOn:
return "net4g_boot_on";
case LocalPrompt::kNet4gOff:
return "net4g_off";
case LocalPrompt::kNet4gOn:
return "net4g_on";
case LocalPrompt::kNet4gNoWifi:
return "net4g_no_wifi";
case LocalPrompt::kCallWait:
return "call_wait";
case LocalPrompt::kCallRing:
return "call_ring";
case LocalPrompt::kCallConnected:
return "call_connected";
case LocalPrompt::kCallEnded:
return "call_ended";
case LocalPrompt::kDigit0:
return "digit_0";
case LocalPrompt::kDigit1:
return "digit_1";
case LocalPrompt::kDigit2:
return "digit_2";
case LocalPrompt::kDigit3:
return "digit_3";
case LocalPrompt::kDigit4:
return "digit_4";
case LocalPrompt::kDigit5:
return "digit_5";
case LocalPrompt::kDigit6:
return "digit_6";
case LocalPrompt::kDigit7:
return "digit_7";
case LocalPrompt::kDigit8:
return "digit_8";
case LocalPrompt::kDigit9:
return "digit_9";
}
return "unknown";
}
} // namespace borla

102
main/core/playback_types.h Normal file
View File

@@ -0,0 +1,102 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
using PlaybackSessionId = uint32_t;
enum class PlaybackSource : uint8_t {
kRemoteTts,
kRemoteMusic,
kLocalPrompt,
kAlarm,
kCall,
};
enum class PlaybackPriority : uint8_t {
kBackground = 20,
kConversation = 40,
kLocalPrompt = 60,
kSystem = 80,
kAlarm = 100,
kCall = 120,
};
enum class AlertKind : uint8_t {
kReminder,
kAlarm,
};
enum class LocalPrompt : uint8_t {
kActivationDevice,
kDeviceAlreadyBound,
kServerError,
kAlarmWake,
kAlarmSet,
kNoNetwork,
kProvisioning,
kWakeResponse,
kStoryExpired,
kIdleCheck,
kIdleGoodbye,
kSnoreLight,
kWifiSuccess,
kWelcome,
kShutdown,
kBoot,
kError,
kLowBattery20,
kLowBattery10,
kNet4gBootOn,
kNet4gOff,
kNet4gOn,
kNet4gNoWifi,
kCallWait,
kCallRing,
kCallConnected,
kCallEnded,
kDigit0,
kDigit1,
kDigit2,
kDigit3,
kDigit4,
kDigit5,
kDigit6,
kDigit7,
kDigit8,
kDigit9,
};
inline constexpr size_t kMaxLocalPromptSequenceItems = 16;
struct LocalPromptSequenceItem {
LocalPrompt prompt = LocalPrompt::kError;
int16_t selector = -1;
};
struct LocalPromptSequence {
std::array<
LocalPromptSequenceItem,
kMaxLocalPromptSequenceItems> items{};
size_t count = 0;
bool Empty() const { return count == 0; }
bool Contains(LocalPrompt prompt) const
{
for (size_t index = 0; index < count; ++index) {
if (items[index].prompt == prompt) {
return true;
}
}
return false;
}
};
const char* ToString(PlaybackSource source);
const char* ToString(PlaybackPriority priority);
const char* ToString(LocalPrompt prompt);
} // namespace borla

33
main/core/psram_object.h Normal file
View File

@@ -0,0 +1,33 @@
#pragma once
#include <memory>
#include <new>
#include <esp_heap_caps.h>
namespace borla {
template <typename T>
struct PsramObjectDeleter {
void operator()(T* object) const
{
if (object != nullptr) {
object->~T();
heap_caps_free(object);
}
}
};
template <typename T>
std::unique_ptr<T, PsramObjectDeleter<T>> MakePsramObject()
{
void* memory = heap_caps_malloc(
sizeof(T), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (memory == nullptr) {
return {};
}
return std::unique_ptr<T, PsramObjectDeleter<T>>(
new (memory) T());
}
} // namespace borla

View File

@@ -0,0 +1,69 @@
#include "core/remote_behavior.h"
#include <cstring>
namespace borla {
const char* ToString(ButtonAction action)
{
switch (action) {
case ButtonAction::kUnspecified:
return "";
case ButtonAction::kFriendMode:
return "friend_mode";
case ButtonAction::kNetworkSwitch:
return "network_switch";
case ButtonAction::kNothing:
return "nothing";
}
return "";
}
bool ParseButtonAction(const char* value, ButtonAction* action)
{
if (value == nullptr || action == nullptr) {
return false;
}
if (std::strcmp(value, "friend_mode") == 0) {
*action = ButtonAction::kFriendMode;
return true;
}
if (std::strcmp(value, "network_switch") == 0) {
*action = ButtonAction::kNetworkSwitch;
return true;
}
if (std::strcmp(value, "nothing") == 0) {
*action = ButtonAction::kNothing;
return true;
}
return false;
}
bool IsAllowedConnectionPrompt(LocalPrompt prompt)
{
return prompt == LocalPrompt::kServerError ||
prompt == LocalPrompt::kNoNetwork ||
prompt == LocalPrompt::kError;
}
bool ParseConnectionPrompt(const char* value, LocalPrompt* prompt)
{
if (value == nullptr || prompt == nullptr) {
return false;
}
if (std::strcmp(value, "server_error") == 0) {
*prompt = LocalPrompt::kServerError;
return true;
}
if (std::strcmp(value, "no_network") == 0) {
*prompt = LocalPrompt::kNoNetwork;
return true;
}
if (std::strcmp(value, "error") == 0) {
*prompt = LocalPrompt::kError;
return true;
}
return false;
}
} // namespace borla

View File

@@ -0,0 +1,22 @@
#pragma once
#include "core/playback_types.h"
#include <cstdint>
namespace borla {
enum class ButtonAction : uint8_t {
kUnspecified = 0,
kFriendMode,
kNetworkSwitch,
kNothing,
};
const char* ToString(ButtonAction action);
bool ParseButtonAction(const char* value, ButtonAction* action);
bool IsAllowedConnectionPrompt(LocalPrompt prompt);
bool ParseConnectionPrompt(const char* value, LocalPrompt* prompt);
} // namespace borla

216
main/core/runtime_state.cc Normal file
View File

@@ -0,0 +1,216 @@
#include "core/runtime_state.h"
namespace borla {
StateValidation ValidateRuntimeState(const RuntimeState& state)
{
if (state.realtime == RealtimeState::kOpen &&
state.connectivity != ConnectivityState::kOnline) {
return {false, "open realtime channel requires online connectivity"};
}
if (state.conversation != ConversationState::kIdle &&
state.lifecycle != LifecycleState::kRunning) {
return {false, "active conversation requires running lifecycle"};
}
if (state.conversation == ConversationState::kSpeaking &&
state.playback == PlaybackState::kIdle) {
return {false, "speaking requires an active playback session"};
}
if (state.playback != PlaybackState::kIdle &&
state.playback_session_id == 0 &&
!state.pending_soft_off_after_playback &&
!state.idle_check_prompt) {
return {false, "active playback requires a non-zero session id"};
}
if (state.local_prompt_active &&
state.playback == PlaybackState::kIdle) {
return {false, "active local prompt requires playback"};
}
if (state.idle_sleeping &&
(state.lifecycle != LifecycleState::kRunning ||
state.realtime != RealtimeState::kClosed ||
state.conversation != ConversationState::kIdle ||
state.call != CallState::kInactive ||
state.playback != PlaybackState::kIdle)) {
return {false, "idle sleep requires running offline media state"};
}
if (state.idle_check_prompt &&
(state.lifecycle != LifecycleState::kRunning ||
state.playback != PlaybackState::kDraining)) {
return {false, "idle check requires draining prompt playback"};
}
if (state.alert_ringing &&
state.lifecycle != LifecycleState::kRunning) {
return {false, "alert ringing requires running lifecycle"};
}
if (state.call != CallState::kInactive &&
state.lifecycle != LifecycleState::kRunning) {
return {false, "call requires running lifecycle"};
}
if (state.friend_mode &&
(state.lifecycle != LifecycleState::kRunning ||
state.realtime != RealtimeState::kClosed ||
state.conversation != ConversationState::kIdle ||
state.call != CallState::kInactive ||
state.playback != PlaybackState::kIdle ||
state.alert_ringing)) {
return {false, "friend mode requires exclusive idle media state"};
}
const bool exclusive_lifecycle =
state.lifecycle == LifecycleState::kProvisioning ||
state.lifecycle == LifecycleState::kUpgrading ||
state.lifecycle == LifecycleState::kShuttingDown ||
state.lifecycle == LifecycleState::kSoftOff ||
state.lifecycle == LifecycleState::kFaulted;
const bool shutdown_prompt_playing =
state.lifecycle == LifecycleState::kShuttingDown &&
state.pending_soft_off_after_playback &&
state.realtime == RealtimeState::kClosed &&
state.conversation == ConversationState::kIdle &&
state.call == CallState::kInactive &&
state.playback == PlaybackState::kDraining;
if (exclusive_lifecycle && !shutdown_prompt_playing &&
(state.realtime != RealtimeState::kClosed ||
state.conversation != ConversationState::kIdle ||
state.call != CallState::kInactive ||
state.playback != PlaybackState::kIdle)) {
return {false, "exclusive lifecycle requires inactive realtime and media state"};
}
if (state.pending_soft_off_after_playback &&
!shutdown_prompt_playing) {
return {false, "pending soft-off requires shutdown prompt playback"};
}
return {true, "ok"};
}
#define BORLA_ENUM_TO_STRING_CASE(value) \
case value: \
return #value
const char* ToString(LifecycleState state)
{
switch (state) {
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kCold);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kStarting);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kRunning);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kProvisioning);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kUpgrading);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kShuttingDown);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kSoftOff);
BORLA_ENUM_TO_STRING_CASE(LifecycleState::kFaulted);
}
return "LifecycleState::unknown";
}
const char* ToString(ConnectivityState state)
{
switch (state) {
BORLA_ENUM_TO_STRING_CASE(ConnectivityState::kOffline);
BORLA_ENUM_TO_STRING_CASE(ConnectivityState::kConnecting);
BORLA_ENUM_TO_STRING_CASE(ConnectivityState::kOnline);
}
return "ConnectivityState::unknown";
}
const char* ToString(RealtimeState state)
{
switch (state) {
BORLA_ENUM_TO_STRING_CASE(RealtimeState::kClosed);
BORLA_ENUM_TO_STRING_CASE(RealtimeState::kOpening);
BORLA_ENUM_TO_STRING_CASE(RealtimeState::kOpen);
}
return "RealtimeState::unknown";
}
const char* ToString(ConversationState state)
{
switch (state) {
BORLA_ENUM_TO_STRING_CASE(ConversationState::kIdle);
BORLA_ENUM_TO_STRING_CASE(ConversationState::kListening);
BORLA_ENUM_TO_STRING_CASE(ConversationState::kSpeaking);
}
return "ConversationState::unknown";
}
const char* ToString(CallState state)
{
switch (state) {
BORLA_ENUM_TO_STRING_CASE(CallState::kInactive);
BORLA_ENUM_TO_STRING_CASE(CallState::kRinging);
BORLA_ENUM_TO_STRING_CASE(CallState::kCalling);
BORLA_ENUM_TO_STRING_CASE(CallState::kActive);
}
return "CallState::unknown";
}
const char* ToString(PlaybackState state)
{
switch (state) {
BORLA_ENUM_TO_STRING_CASE(PlaybackState::kIdle);
BORLA_ENUM_TO_STRING_CASE(PlaybackState::kStreaming);
BORLA_ENUM_TO_STRING_CASE(PlaybackState::kDraining);
}
return "PlaybackState::unknown";
}
const char* ToString(AudioPolicy policy)
{
switch (policy) {
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kOff);
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kWakeWordOnly);
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kWakeWordDuplex);
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kConversationCapture);
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kBargeInDuplex);
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kCallDuplex);
BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kPlaybackOnly);
}
return "AudioPolicy::unknown";
}
const char* ToString(ConversationInterruptSource source)
{
switch (source) {
BORLA_ENUM_TO_STRING_CASE(
ConversationInterruptSource::kUserInitiated);
BORLA_ENUM_TO_STRING_CASE(
ConversationInterruptSource::kWakeWordDetected);
}
return "ConversationInterruptSource::unknown";
}
const char* ToString(LedPattern pattern)
{
switch (pattern) {
BORLA_ENUM_TO_STRING_CASE(LedPattern::kOff);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kStarting);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kConnecting);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kIdle);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kListening);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kSpeaking);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kRinging);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kCalling);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kFriendMode);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kProvisioning);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kUpgrading);
BORLA_ENUM_TO_STRING_CASE(LedPattern::kError);
}
return "LedPattern::unknown";
}
#undef BORLA_ENUM_TO_STRING_CASE
} // namespace borla

119
main/core/runtime_state.h Normal file
View File

@@ -0,0 +1,119 @@
#pragma once
#include "core/playback_types.h"
#include <cstdint>
namespace borla {
enum class LifecycleState : uint8_t {
kCold,
kStarting,
kRunning,
kProvisioning,
kUpgrading,
kShuttingDown,
kSoftOff,
kFaulted,
};
enum class ConnectivityState : uint8_t {
kOffline,
kConnecting,
kOnline,
};
enum class RealtimeState : uint8_t {
kClosed,
kOpening,
kOpen,
};
enum class ConversationState : uint8_t {
kIdle,
kListening,
kSpeaking,
};
enum class CallState : uint8_t {
kInactive,
kRinging,
kCalling,
kActive,
};
enum class PlaybackState : uint8_t {
kIdle,
kStreaming,
kDraining,
};
enum class AudioPolicy : uint8_t {
kOff,
kWakeWordOnly,
kWakeWordDuplex,
kConversationCapture,
kBargeInDuplex,
kCallDuplex,
kPlaybackOnly,
};
enum class ConversationInterruptSource : uint8_t {
kUserInitiated,
kWakeWordDetected,
};
enum class LedPattern : uint8_t {
kOff,
kStarting,
kConnecting,
kIdle,
kListening,
kSpeaking,
kRinging,
kCalling,
kFriendMode,
kProvisioning,
kUpgrading,
kError,
};
struct RuntimeState {
LifecycleState lifecycle = LifecycleState::kCold;
ConnectivityState connectivity = ConnectivityState::kOffline;
RealtimeState realtime = RealtimeState::kClosed;
ConversationState conversation = ConversationState::kIdle;
CallState call = CallState::kInactive;
PlaybackState playback = PlaybackState::kIdle;
uint32_t playback_session_id = 0;
bool pending_conversation_start = false;
bool pending_soft_off_after_playback = false;
bool idle_sleeping = false;
bool idle_check_prompt = false;
bool alert_ringing = false;
bool friend_mode = false;
bool pending_alert = false;
AlertKind pending_alert_kind = AlertKind::kReminder;
bool local_prompt_active = false;
LocalPrompt active_local_prompt = LocalPrompt::kError;
};
struct StateValidation {
bool valid;
const char* reason;
};
StateValidation ValidateRuntimeState(const RuntimeState& state);
const char* ToString(LifecycleState state);
const char* ToString(ConnectivityState state);
const char* ToString(RealtimeState state);
const char* ToString(ConversationState state);
const char* ToString(CallState state);
const char* ToString(PlaybackState state);
const char* ToString(AudioPolicy policy);
const char* ToString(ConversationInterruptSource source);
const char* ToString(LedPattern pattern);
} // namespace borla

1143
main/core/state_reducer.cc Normal file

File diff suppressed because it is too large Load Diff

13
main/core/state_reducer.h Normal file
View File

@@ -0,0 +1,13 @@
#pragma once
#include "core/app_effect.h"
#include "core/app_event.h"
#include "core/runtime_state.h"
namespace borla {
// Pure control-plane state transition function. It has no ESP-IDF dependency,
// performs no I/O and is therefore host-testable.
TransitionResult ReduceState(const RuntimeState& current, const AppEvent& event);
} // namespace borla

View File

@@ -0,0 +1,97 @@
#pragma once
#include <cstddef>
namespace borla::task_stack_budget {
// ESP-IDF's FreeRTOS task creation APIs on ESP32-S3 express stack depth in
// bytes. Keep the unit in each name so future changes do not accidentally
// treat these values as host FreeRTOS StackType_t words. The two large audio
// stacks are allocated from PSRAM; connectivity stacks stay in internal RAM.
inline constexpr size_t kPlaybackBytes = 36 * 1024;
// Internal RAM, and dynamically allocated so BLE provisioning gets it back
// when the audio engine is stopped. This is the one audio task with a hard
// deadline: it must finish read + AEC + wake word inside 60 ms or the I2S RX
// DMA overflows and the AEC loses microphone/reference alignment. Stack access
// is the most frequent memory operation in that code, and serving it from PSRAM
// — over a bus the encoder task is simultaneously hammering — was measured at
// 56-70 ms for the DSP stage alone.
//
// The previous firmware ran the identical work (VoiceProcessor + WakeNet) in
// 16 KB of internal RAM; 20 KB here leaves margin for the 1920-byte reference
// frame this implementation keeps on the stack. Watch capture2's
// stack_free_bytes in the diagnostics snapshot before trimming further.
// 16 KB matches the previous firmware's audio_in task for the same workload;
// the measured high-water mark here is ~6.3 KB (capture2 stack_free_bytes =
// 14172 of the earlier 20 KB, read while duplex AEC was active).
inline constexpr size_t kCaptureBytes = 10 * 1024;//16 * 1024;
// Opus encoding only; runs on the other core so it never competes with the
// capture loop's 60 ms frame budget.
//
// Sized from where the work came from, not from the task's idle footprint.
// libopus' SILK path (silk_encode_frame_FIX -> silk_find_pitch_lags_FIX ->
// silk_autocorr -> celt_pitch_xcorr) puts large arrays on the stack; the
// combined capture task that used to do this was measured at ~25 KB in use.
// A first attempt at 16 KB tripped the stack canary inside celt_pitch_xcorr_c
// on the very first encoded frame and put the device in a boot loop. A later
// trim to 24 KB tripped it again deeper in the same path (stack canary in
// silk_NSQ_del_dec_c at NSQ_del_dec.c:266, the call into
// silk_noise_shape_quantizer_del_dec, 2026-09-23): the panic backtrace spans
// 0x3c842cb0..0x3c848b60, i.e. the opus_encode() chain alone walked 24,240 of
// the 24,576 budgeted bytes before the next frame crossed the limit. This is
// PSRAM, so the headroom costs no internal RAM.
inline constexpr size_t kCaptureEncoderBytes = 32 * 1024;
// Sized from measured high-water marks after a full TLS + OTA + provisioning
// cycle, not guessed. Every byte here is .bss, i.e. it comes straight off the
// front of the main internal heap region — and that region is what BLE
// provisioning runs out of when it has to re-init the WiFi driver alongside the
// BT controller. Field numbers at the time of sizing (used / previous budget):
// connectivity2 2492 / 8192 dual_network2 3136 / 8192
// friend_service2 960 / 4096 alarm2 1172 / 4096
inline constexpr size_t kConnectivityManagerBytes = 5 * 1024;//6 * 1024;
inline constexpr size_t kDualNetworkBytes = 4 * 1024;//5 * 1024;
inline constexpr size_t kWebsocketTransportBytes = 10 * 1024;//12 * 1024;
inline constexpr size_t kFriendServiceBytes = 3 * 1024;
inline constexpr size_t kAlarmServiceBytes = 3 * 1024;
inline constexpr size_t kRuntimeDiagnosticsBytes = 8 * 1024;
inline constexpr size_t kLocalPromptProducerBytes = 6 * 1024;
// BLE provisioning worker: carries esp_wifi_scan_start, nimble_port_init and
// NVS credential writes on one stack, so it cannot live in PSRAM (NVS runs
// with the cache disabled) and needs real headroom.
inline constexpr size_t kBleProvisioningBytes = 8 * 1024;
} // namespace borla::task_stack_budget
namespace borla::task_priority {
// The audio path is a real-time system and its priorities are load-bearing,
// not incidental. Layout adopted from the previous firmware, which ran the
// same DSP on the same silicon without stuttering (audio_service.cc:56-58):
//
// audio_in prio 8 core 0 capture + AEC + wake word
// audio_out prio 4 core 1 I2S write
// opus_codec prio 2 core 1 encode + decode
//
// The rule is that the two tasks with a hard 60 ms deadline must preempt the
// CPU-heavy one, never the reverse. This firmware originally ran all three at
// priority 5; a single Opus encode costs ~50 ms of CPU, so at equal priority it
// simply took the speaker task's slot and playback stuttered audibly.
//
// The speaker task is 6 rather than the previous firmware's 4 because it is
// not the same task. The old audio_out was a pure I2S writer — per wake-up it
// memcpy'd already-decoded PCM into the DMA, work so small that time-slicing
// against the priority-4 service crowd could not hurt it, and behind it stood
// an 8-frame decoded-PCM queue (480 ms of runway) filled by the codec task.
// Here decode+write are fused into one task whose only runway is the I2S DMA
// itself, so a 10-15 ms Opus decode delayed by round-robin against the
// UNPINNED priority-4/5 tasks (websocket2 doing TLS at 4, imu_sensor2 doing
// I2C at 5, touch/battery/alarm/reminder at 4 — all free to land on core 1)
// occasionally missed the deadline: the field symptom was intermittent
// playback stutter. 6 puts the speaker above that crowd and below capture.
// Priority inheritance covers the shared mutexes (ESP-IDF std::mutex is a
// FreeRTOS PI mutex underneath).
inline constexpr unsigned kCaptureLoop = 8;
inline constexpr unsigned kPlaybackLoop = 6;
inline constexpr unsigned kAudioCodec = 2;
} // namespace borla::task_priority

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

View File

@@ -0,0 +1,266 @@
#include "friend/friend_service.h"
#include <cstring>
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "FriendService2";
constexpr uint32_t kFriendStartError = 12201;
constexpr uint32_t kFriendStoreError = 12202;
template <size_t Capacity>
bool CopyString(
const char* value,
std::array<char, Capacity>* output)
{
if (value == nullptr || output == nullptr) {
return false;
}
const size_t size = std::strlen(value);
if (size == 0 || size >= Capacity) {
return false;
}
output->fill('\0');
std::memcpy(output->data(), value, size);
return true;
}
} // namespace
FriendService::FriendService(
BleFriendExchange& exchange,
IFriendStore& store,
IRealtimeProtocol& realtime,IConnectivityManager& connectivity)
: exchange_(exchange),
store_(store),
realtime_(realtime),
connectivity_(connectivity)//2026-9-7 ckkj add
{
}
bool FriendService::Initialize(
const DeviceIdentity& identity,
IEventPublisher& publisher)
{
if (initialized_.load()) {
return true;
}
if (!CopyString(identity.mac, &local_mac_) ||
!BuildFriendAdvertisingName(
identity.mac,
fallback_name_.data(),
fallback_name_.size()) ||
!store_.Load(&snapshot_) ||
!exchange_.Initialize()) {
return false;
}
queue_ = xQueueCreateStatic(
kQueueDepth,
sizeof(Command),
queue_storage_.data(),
&queue_control_);
if (queue_ == nullptr) {
return false;
}
task_ = xTaskCreateStatic(
&FriendService::TaskEntry,
"friend_service2",
task_stack_.size(),
this,
kTaskPriority,
task_stack_.data(),
&task_control_);
if (task_ == nullptr) {
return false;
}
publisher_ = &publisher;
initialized_.store(true);
return true;
}
void FriendService::Start()
{
if (!Post({CommandType::kStart})) {
ESP_LOGE(kTag, "failed to enqueue friend start");
}
}
void FriendService::Stop()
{
Post({CommandType::kStop});
}
void FriendService::SetDeviceName(const char* device_name)
{
Command command;
command.type = CommandType::kSetDeviceName;
if (CopyString(device_name, &command.device_name)) {
Post(command);
}
}
void FriendService::OnBleFriendMatched(const FriendPeer& peer)
{
Command command;
command.type = CommandType::kMatched;
command.peer = peer;
Post(command);
}
void FriendService::OnBleFriendExchangeStopped(
bool paired,
uint32_t error_id)
{
Command command;
command.type = CommandType::kExchangeStopped;
command.paired = paired;
command.error_id = error_id;
Post(command);
}
void FriendService::OnApplicationEvent(
const AppEvent& event,
const RuntimeState&)
{
if (event.type == AppEventType::kRealtimeConnected) {
Post({CommandType::kUploadPending});
}
}
void FriendService::TaskEntry(void* context)
{
static_cast<FriendService*>(context)->Run();
}
[[noreturn]] void FriendService::Run()
{
while (true) {
Command command;
if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) {
Handle(command);
}
}
}
bool FriendService::Post(const Command& command)
{
return initialized_.load() && queue_ != nullptr &&
xQueueSend(queue_, &command, 0) == pdTRUE;
}
void FriendService::Handle(const Command& command)
{
switch (command.type) {
case CommandType::kStart:
HandleStart();
return;
case CommandType::kStop:
exchange_.Stop();
return;
case CommandType::kMatched:
HandleMatched(command.peer);
return;
case CommandType::kExchangeStopped:
// 2026-9-7 ckkj add: BLE 会话已结束(BleFriendExchange 在
// nimble_port_deinit 释放 BT 内存后才回调),立即恢复网络。
connectivity_.ResumeAfterBle();/////
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kFriendModeEnded,
command.error_id,
0,
command.paired ? 1U : 0U));
}
return;
case CommandType::kSetDeviceName:
HandleSetDeviceName(command.device_name.data());
return;
case CommandType::kUploadPending:
UploadPending();
return;
}
}
void FriendService::HandleStart()
{
if (exchange_.IsActive()) {
return;
}
// if (!exchange_.Start(local_mac_.data(), *this) &&
// publisher_ != nullptr) {
// publisher_->Publish(AppEvent::Make(
// AppEventType::kFriendModeEnded,
// kFriendStartError));
// 2026-9-7 ckkj add: BT 控制器需要 ~65KB 内部 RAM,与已初始化的 WiFi
// 驱动无法共存,必须在 nimble_port_init 之前拆除驱动,否则 BLE_INIT
// "Malloc failed" 后 controller 内部直接 panic。结束时在
// kExchangeStopped 恢复;启动请求本身失败也立即恢复,避免网络永久挂起。
connectivity_.SuspendForBle();
if (!exchange_.Start(local_mac_.data(), *this)) {
connectivity_.ResumeAfterBle();
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kFriendModeEnded,
kFriendStartError));
}
}
}
void FriendService::HandleMatched(const FriendPeer& peer)
{
if (!AddOrUpdateFriend(&snapshot_, peer)) {
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
kFriendStoreError));
}
return;
}
snapshot_.pending_upload = peer;
snapshot_.has_pending_upload = true;
if (!store_.Save(snapshot_) && publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
kFriendStoreError));
}
}
void FriendService::HandleSetDeviceName(const char* device_name)
{
if (CopyString(device_name, &snapshot_.device_name) &&
!store_.Save(snapshot_)) {
ESP_LOGE(kTag, "device name persistence failed");
}
}
void FriendService::UploadPending()
{
if (!snapshot_.has_pending_upload) {
return;
}
if (!realtime_.SendFriendAdd(
local_mac_.data(),
LocalName(),
snapshot_.pending_upload.mac.data(),
snapshot_.pending_upload.name.data())) {
ESP_LOGW(kTag, "friend_add deferred until next reconnect");
return;
}
snapshot_.has_pending_upload = false;
snapshot_.pending_upload = {};
if (!store_.Save(snapshot_)) {
ESP_LOGE(kTag, "pending friend clear persistence failed");
}
}
const char* FriendService::LocalName()
{
return snapshot_.device_name[0] != '\0'
? snapshot_.device_name.data()
: fallback_name_.data();
}
} // namespace borla

View File

@@ -0,0 +1,104 @@
#pragma once
#include "core/task_stack_budget.h"
#include "friend/friend_store.h"
#include "platform/borla_s3/ble_friend_exchange.h"
#include "ports/application_observer.h"
#include "ports/device_platform.h"
#include "ports/device_profile_sink.h"
#include "ports/event_publisher.h"
#include "ports/friend_service.h"
#include "ports/realtime_protocol.h"
#include "ports/connectivity_manager.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <freertos/task.h>
namespace borla {
class FriendService final
: public IFriendService,
public IBleFriendExchangeObserver,
public IDeviceProfileSink,
public IApplicationObserver {
public:
FriendService(
BleFriendExchange& exchange,
IFriendStore& store,
IRealtimeProtocol& realtime,
IConnectivityManager& connectivity);//2026-9-7 ckkj add
bool Initialize(
const DeviceIdentity& identity,
IEventPublisher& publisher);
void Start() override;
void Stop() override;
void SetDeviceName(const char* device_name) override;
void OnBleFriendMatched(const FriendPeer& peer) override;
void OnBleFriendExchangeStopped(
bool paired,
uint32_t error_id) override;
void OnApplicationEvent(
const AppEvent& event,
const RuntimeState& state) override;
private:
enum class CommandType : uint8_t {
kStart,
kStop,
kMatched,
kExchangeStopped,
kSetDeviceName,
kUploadPending,
};
struct Command {
CommandType type = CommandType::kStart;
FriendPeer peer{};
std::array<char, kFriendNameCapacity> device_name{};
uint32_t error_id = 0;
bool paired = false;
};
static constexpr size_t kQueueDepth = 10;
static constexpr UBaseType_t kTaskPriority = 5;
static void TaskEntry(void* context);
[[noreturn]] void Run();
bool Post(const Command& command);
void Handle(const Command& command);
void HandleStart();
void HandleMatched(const FriendPeer& peer);
void HandleSetDeviceName(const char* device_name);
void UploadPending();
const char* LocalName();
BleFriendExchange& exchange_;
IFriendStore& store_;
IRealtimeProtocol& realtime_;
IConnectivityManager& connectivity_;//2026-9-7 ckkj add
IEventPublisher* publisher_ = nullptr;
FriendStoreSnapshot snapshot_{};
std::array<char, kFriendMacCapacity> local_mac_{};
std::array<char, kFriendAdvertisingNameCapacity>
fallback_name_{};
QueueHandle_t queue_ = nullptr;
StaticQueue_t queue_control_{};
alignas(Command)
std::array<uint8_t, kQueueDepth * sizeof(Command)>
queue_storage_{};
TaskHandle_t task_ = nullptr;
StaticTask_t task_control_{};
std::array<
StackType_t,
task_stack_budget::kFriendServiceBytes> task_stack_{};
std::atomic<bool> initialized_{false};
};
} // namespace borla

313
main/friend/friend_store.cc Normal file
View File

@@ -0,0 +1,313 @@
#include "friend/friend_store.h"
#include "core/psram_object.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <cJSON.h>
#include <esp_err.h>
#include <esp_log.h>
#include <nvs.h>
namespace borla {
namespace {
constexpr const char* kTag = "FriendStore2";
constexpr const char* kNamespace = "friend_v2";
constexpr const char* kSnapshotKey = "snapshot";
constexpr uint32_t kMagic = 0x32444E46;
constexpr uint16_t kVersion = 1;
constexpr const char* kLegacyDeviceNamespace = "device";
constexpr const char* kLegacyDeviceNameKey = "name";
constexpr const char* kLegacyFriendsNamespace = "friends";
constexpr const char* kLegacyFriendCountKey = "count";
struct PersistedFriendSnapshot {
uint32_t magic = kMagic;
uint16_t version = kVersion;
uint16_t friend_count = 0;
uint8_t has_pending_upload = 0;
uint8_t reserved[3]{};
char device_name[kFriendNameCapacity]{};
FriendPeer friends[kMaximumFriendCount]{};
FriendPeer pending_upload{};
uint32_t checksum = 0;
};
uint32_t Checksum(const void* data, size_t size)
{
const auto* bytes = static_cast<const uint8_t*>(data);
uint32_t value = 2166136261U;
for (size_t index = 0; index < size; ++index) {
value ^= bytes[index];
value *= 16777619U;
}
return value;
}
bool PeerValid(const FriendPeer& peer)
{
return peer.mac[0] != '\0' &&
std::memchr(peer.mac.data(), '\0', peer.mac.size()) != nullptr &&
std::memchr(peer.name.data(), '\0', peer.name.size()) != nullptr;
}
template <size_t Capacity>
bool CopyString(
const char* value,
std::array<char, Capacity>* output)
{
if (value == nullptr || output == nullptr) {
return false;
}
const size_t length = std::strlen(value);
if (length == 0 || length >= Capacity) {
return false;
}
output->fill('\0');
std::memcpy(output->data(), value, length);
return true;
}
bool LoadLegacy(FriendStoreSnapshot* snapshot)
{
bool migrated = false;
nvs_handle_t device_handle = 0;
if (nvs_open(
kLegacyDeviceNamespace,
NVS_READONLY,
&device_handle) == ESP_OK) {
size_t size = snapshot->device_name.size();
if (nvs_get_str(
device_handle,
kLegacyDeviceNameKey,
snapshot->device_name.data(),
&size) == ESP_OK &&
snapshot->device_name[0] != '\0') {
migrated = true;
} else {
snapshot->device_name.fill('\0');
}
nvs_close(device_handle);
}
nvs_handle_t friends_handle = 0;
if (nvs_open(
kLegacyFriendsNamespace,
NVS_READONLY,
&friends_handle) != ESP_OK) {
return migrated;
}
int32_t count = 0;
if (nvs_get_i32(
friends_handle,
kLegacyFriendCountKey,
&count) != ESP_OK ||
count <= 0) {
nvs_close(friends_handle);
return migrated;
}
count = std::min<int32_t>(
count, static_cast<int32_t>(kMaximumFriendCount));
for (int32_t index = 0; index < count; ++index) {
char key[16]{};
std::snprintf(key, sizeof(key), "f_%u",
static_cast<unsigned>(index));
std::array<char, 256> json{};
size_t size = json.size();
if (nvs_get_str(
friends_handle,
key,
json.data(),
&size) != ESP_OK) {
continue;
}
cJSON* root = cJSON_Parse(json.data());
const cJSON* mac =
cJSON_GetObjectItemCaseSensitive(root, "mac");
const cJSON* name =
cJSON_GetObjectItemCaseSensitive(root, "name");
FriendPeer peer;
const bool valid =
cJSON_IsString(mac) &&
cJSON_IsString(name) &&
CopyString(mac->valuestring, &peer.mac) &&
CopyString(name->valuestring, &peer.name);
cJSON_Delete(root);
if (valid && AddOrUpdateFriend(snapshot, peer)) {
migrated = true;
}
}
nvs_close(friends_handle);
return migrated;
}
} // namespace
bool NvsFriendStore::Load(FriendStoreSnapshot* snapshot) const
{
if (snapshot == nullptr) {
return false;
}
auto legacy = MakePsramObject<FriendStoreSnapshot>();
auto stored = MakePsramObject<PersistedFriendSnapshot>();
if (!legacy || !stored) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
return false;
}
const bool has_legacy = LoadLegacy(legacy.get());
*snapshot = {};
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNamespace, NVS_READONLY, &handle);
if (result == ESP_ERR_NVS_NOT_FOUND) {
*snapshot = *legacy;
if (has_legacy) {
ESP_LOGI(kTag, "migrated legacy friends/device name");
Save(*snapshot);
}
return true;
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "open failed: %s", esp_err_to_name(result));
return false;
}
size_t size = sizeof(*stored);
result = nvs_get_blob(
handle, kSnapshotKey, stored.get(), &size);
nvs_close(handle);
if (result == ESP_ERR_NVS_NOT_FOUND) {
*snapshot = *legacy;
if (has_legacy) {
ESP_LOGI(kTag, "migrated legacy friends/device name");
Save(*snapshot);
}
return true;
}
const uint32_t expected = Checksum(
stored.get(), offsetof(PersistedFriendSnapshot, checksum));
if (result != ESP_OK || size != sizeof(*stored) ||
stored->magic != kMagic || stored->version != kVersion ||
stored->friend_count > kMaximumFriendCount ||
stored->checksum != expected ||
std::memchr(
stored->device_name,
'\0',
sizeof(stored->device_name)) == nullptr) {
ESP_LOGE(kTag, "invalid persisted friend snapshot");
return false;
}
snapshot->friend_count = stored->friend_count;
std::memcpy(
snapshot->device_name.data(),
stored->device_name,
snapshot->device_name.size());
for (size_t index = 0;
index < snapshot->friend_count;
++index) {
if (!PeerValid(stored->friends[index])) {
return false;
}
snapshot->friends[index] = stored->friends[index];
}
snapshot->has_pending_upload =
stored->has_pending_upload != 0;
if (snapshot->has_pending_upload) {
if (!PeerValid(stored->pending_upload)) {
return false;
}
snapshot->pending_upload = stored->pending_upload;
}
if (snapshot->device_name[0] == '\0' &&
legacy->device_name[0] != '\0') {
snapshot->device_name = legacy->device_name;
Save(*snapshot);
}
return true;
}
bool NvsFriendStore::Save(const FriendStoreSnapshot& snapshot) const
{
if (snapshot.friend_count > kMaximumFriendCount ||
std::memchr(
snapshot.device_name.data(),
'\0',
snapshot.device_name.size()) == nullptr ||
(snapshot.has_pending_upload &&
!PeerValid(snapshot.pending_upload))) {
return false;
}
auto stored = MakePsramObject<PersistedFriendSnapshot>();
if (!stored) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
return false;
}
stored->friend_count =
static_cast<uint16_t>(snapshot.friend_count);
stored->has_pending_upload =
snapshot.has_pending_upload ? 1 : 0;
std::memcpy(
stored->device_name,
snapshot.device_name.data(),
snapshot.device_name.size());
for (size_t index = 0;
index < snapshot.friend_count;
++index) {
if (!PeerValid(snapshot.friends[index])) {
return false;
}
stored->friends[index] = snapshot.friends[index];
}
stored->pending_upload = snapshot.pending_upload;
stored->checksum = Checksum(
stored.get(), offsetof(PersistedFriendSnapshot, checksum));
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNamespace, NVS_READWRITE, &handle);
if (result == ESP_OK) {
result = nvs_set_blob(
handle, kSnapshotKey, stored.get(), sizeof(*stored));
}
if (result == ESP_OK) {
result = nvs_commit(handle);
}
if (handle != 0) {
nvs_close(handle);
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "save failed: %s", esp_err_to_name(result));
return false;
}
return true;
}
bool AddOrUpdateFriend(
FriendStoreSnapshot* snapshot,
const FriendPeer& peer)
{
if (snapshot == nullptr || !PeerValid(peer)) {
return false;
}
for (size_t index = 0;
index < snapshot->friend_count;
++index) {
if (std::strcmp(
snapshot->friends[index].mac.data(),
peer.mac.data()) == 0) {
snapshot->friends[index] = peer;
return true;
}
}
if (snapshot->friend_count >= snapshot->friends.size()) {
return false;
}
snapshot->friends[snapshot->friend_count++] = peer;
return true;
}
} // namespace borla

View File

@@ -0,0 +1,35 @@
#pragma once
#include "friend/friend_types.h"
#include <array>
#include <cstddef>
namespace borla {
struct FriendStoreSnapshot {
std::array<char, kFriendNameCapacity> device_name{};
std::array<FriendPeer, kMaximumFriendCount> friends{};
size_t friend_count = 0;
FriendPeer pending_upload{};
bool has_pending_upload = false;
};
class IFriendStore {
public:
virtual ~IFriendStore() = default;
virtual bool Load(FriendStoreSnapshot* snapshot) const = 0;
virtual bool Save(const FriendStoreSnapshot& snapshot) const = 0;
};
class NvsFriendStore final : public IFriendStore {
public:
bool Load(FriendStoreSnapshot* snapshot) const override;
bool Save(const FriendStoreSnapshot& snapshot) const override;
};
bool AddOrUpdateFriend(
FriendStoreSnapshot* snapshot,
const FriendPeer& peer);
} // namespace borla

215
main/friend/friend_types.cc Normal file
View File

@@ -0,0 +1,215 @@
#include "friend/friend_types.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
namespace borla {
namespace {
constexpr const char* kFriendPrefix = "BorlaF-";
template <size_t Capacity>
bool CopyString(const char* value, std::array<char, Capacity>* output)
{
if (value == nullptr || output == nullptr) {
return false;
}
const size_t size = std::strlen(value);
if (size == 0 || size >= Capacity) {
return false;
}
output->fill('\0');
std::memcpy(output->data(), value, size);
return true;
}
bool IsFriendName(const char* name)
{
return name != nullptr &&
std::strncmp(name, kFriendPrefix, std::strlen(kFriendPrefix)) == 0;
}
} // namespace
bool FriendCandidateSelector::Observe(
const char* ble_mac,
const char* advertising_name,
int8_t rssi_dbm,
uint64_t now_ms)
{
if (!IsFriendName(advertising_name) ||
ble_mac == nullptr || now_ms == 0) {
return false;
}
FriendCandidate* slot = nullptr;
FriendCandidate* oldest = nullptr;
for (FriendCandidate& candidate : candidates_) {
if (candidate.occupied &&
std::strcmp(candidate.peer.mac.data(), ble_mac) == 0) {
slot = &candidate;
break;
}
if (!candidate.occupied && slot == nullptr) {
slot = &candidate;
}
if (candidate.occupied &&
(oldest == nullptr ||
candidate.last_seen_ms < oldest->last_seen_ms)) {
oldest = &candidate;
}
}
if (slot == nullptr) {
slot = oldest;
}
if (slot == nullptr) {
return false;
}
if (!slot->occupied ||
std::strcmp(slot->peer.mac.data(), ble_mac) != 0) {
*slot = {};
if (!CopyString(ble_mac, &slot->peer.mac) ||
!CopyString(advertising_name, &slot->peer.name)) {
*slot = {};
return false;
}
slot->best_rssi_dbm = rssi_dbm;
slot->occupied = true;
} else {
CopyString(advertising_name, &slot->peer.name);
slot->best_rssi_dbm =
std::max(slot->best_rssi_dbm, rssi_dbm);
}
if (slot->seen_count != UINT8_MAX) {
slot->seen_count++;
}
slot->last_seen_ms = now_ms;
return true;
}
bool FriendCandidateSelector::Select(
uint64_t now_ms,
FriendPeer* peer)
{
if (peer == nullptr) {
return false;
}
FriendCandidate* best = nullptr;
for (FriendCandidate& candidate : candidates_) {
if (!candidate.occupied) {
continue;
}
if (now_ms < candidate.last_seen_ms ||
now_ms - candidate.last_seen_ms > kStaleAfterMs) {
candidate = {};
continue;
}
const bool eligible =
candidate.best_rssi_dbm >= kStrongRssiDbm ||
(candidate.best_rssi_dbm >= kWeakRssiDbm &&
candidate.seen_count >= kWeakMinimumSeen);
if (eligible &&
(best == nullptr ||
candidate.best_rssi_dbm > best->best_rssi_dbm)) {
best = &candidate;
}
}
if (best == nullptr) {
return false;
}
*peer = best->peer;
return NormalizeBleMacToBaseMac(
best->peer.mac.data(),
peer->mac.data(),
peer->mac.size());
}
void FriendCandidateSelector::Reset()
{
candidates_.fill(FriendCandidate{});
}
bool NormalizeBleMacToBaseMac(
const char* ble_mac,
char* base_mac,
size_t capacity)
{
if (ble_mac == nullptr || base_mac == nullptr ||
capacity < kFriendMacCapacity) {
return false;
}
unsigned values[6]{};
char trailing = '\0';
if (std::sscanf(
ble_mac,
"%2x:%2x:%2x:%2x:%2x:%2x%c",
&values[0],
&values[1],
&values[2],
&values[3],
&values[4],
&values[5],
&trailing) != 6) {
return false;
}
uint64_t value = 0;
for (unsigned octet : values) {
if (octet > 0xFFU) {
return false;
}
value = (value << 8U) | octet;
}
if (value < 2) {
return false;
}
value -= 2;
// Lower case, non-negotiable. The normalized base MAC is the peer
// device's device_id, sent verbatim in friend_add, and the server matches
// device ids case-sensitively — the same contract that made the uppercase
// MAC in borla_s3_platform.cc loop the activation prompt forever. The
// previous firmware's BleMacToBaseMac emitted lower case here too.
const int written = std::snprintf(
base_mac,
capacity,
"%02x:%02x:%02x:%02x:%02x:%02x",
static_cast<unsigned>((value >> 40U) & 0xFFU),
static_cast<unsigned>((value >> 32U) & 0xFFU),
static_cast<unsigned>((value >> 24U) & 0xFFU),
static_cast<unsigned>((value >> 16U) & 0xFFU),
static_cast<unsigned>((value >> 8U) & 0xFFU),
static_cast<unsigned>(value & 0xFFU));
return written == 17;
}
bool BuildFriendAdvertisingName(
const char* base_mac,
char* output,
size_t capacity)
{
if (base_mac == nullptr || output == nullptr ||
capacity < 12) {
return false;
}
char compact[13]{};
size_t count = 0;
for (size_t index = 0;
base_mac[index] != '\0' && count < 12;
++index) {
if (base_mac[index] != ':') {
compact[count++] = base_mac[index];
}
}
if (count != 12) {
return false;
}
const int written = std::snprintf(
output,
capacity,
"BorlaF-%.4s",
compact + 8);
return written == 11;
}
} // namespace borla

View File

@@ -0,0 +1,56 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
inline constexpr size_t kFriendMacCapacity = 18;
inline constexpr size_t kFriendNameCapacity = 64;
inline constexpr size_t kFriendAdvertisingNameCapacity = 32;
inline constexpr size_t kMaximumFriendCount = 20;
inline constexpr size_t kMaximumFriendCandidates = 8;
struct FriendPeer {
std::array<char, kFriendMacCapacity> mac{};
std::array<char, kFriendNameCapacity> name{};
};
struct FriendCandidate {
FriendPeer peer{};
int8_t best_rssi_dbm = -127;
uint8_t seen_count = 0;
uint64_t last_seen_ms = 0;
bool occupied = false;
};
class FriendCandidateSelector final {
public:
static constexpr int8_t kStrongRssiDbm = -60;
static constexpr int8_t kWeakRssiDbm = -85;
static constexpr uint8_t kWeakMinimumSeen = 2;
static constexpr uint64_t kStaleAfterMs = 6000;
bool Observe(
const char* ble_mac,
const char* advertising_name,
int8_t rssi_dbm,
uint64_t now_ms);
bool Select(uint64_t now_ms, FriendPeer* peer);
void Reset();
private:
std::array<FriendCandidate, kMaximumFriendCandidates> candidates_{};
};
bool NormalizeBleMacToBaseMac(
const char* ble_mac,
char* base_mac,
size_t capacity);
bool BuildFriendAdvertisingName(
const char* base_mac,
char* output,
size_t capacity);
} // namespace borla

8
main/idf_component.yml Normal file
View File

@@ -0,0 +1,8 @@
dependencies:
idf: ">=5.3,<6.0"
78/esp-opus: "==1.0.5"
espressif/button: "==4.1.3"
espressif/esp_codec_dev: "==1.4.0"
espressif/esp-dsp: "==1.8.0"
espressif/esp-sr: "==2.5.0"
espressif/led_strip: "==3.0.3"

41
main/main.cc Normal file
View File

@@ -0,0 +1,41 @@
#include "app/composition_root.h"
#include "diagnostics/device_log_formatter.h"
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <cJSON.h>
namespace {
constexpr const char* kTag = "BorlaFirmware2";
void* PsramCjsonMalloc(size_t size)
{
return heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
}
void PsramCjsonFree(void* pointer)
{
heap_caps_free(pointer);
}
} // namespace
extern "C" void app_main()
{
cJSON_Hooks cjson_hooks = {
PsramCjsonMalloc,
PsramCjsonFree,
};
cJSON_InitHooks(&cjson_hooks);///修复:全局 cJSON 钩子指向 PSRAM,防止WiFi mem fail
const bool log_identity_ready = borla::DeviceLogFormatter::Initialize();
ESP_LOGI(kTag, "starting firmware2 control and playback foundation");
if (!log_identity_ready) {
ESP_LOGW(kTag, "device MAC unavailable for log prefix");
}
static borla::CompositionRoot root;
if (!root.Initialize()) {
ESP_LOGE(kTag, "initialization incomplete; entering fault-capable loop");
}
root.Run();
}

228
main/memory/memory_cache.cc Normal file
View File

@@ -0,0 +1,228 @@
#include "memory/memory_cache.h"
#include "core/psram_object.h"
#include <algorithm>
#include <cstring>
#include <cJSON.h>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_partition.h>
#include <nvs.h>
namespace borla {
namespace {
constexpr const char* kTag = "MemoryCache2";
constexpr const char* kNamespace = "memory2";
constexpr const char* kSnapshotKey = "snapshot";
constexpr const char* kLegacyPartitionLabel = "claude_mem";
constexpr uint32_t kRecordMagic = 0x324D454DU; // "MEM2"
constexpr uint16_t kRecordVersion = 1;
constexpr uint32_t kLegacyMagic = 0x424F524CU; // "BORL"
constexpr size_t kMaximumLegacyJsonBytes = 64 * 1024;
struct StoredMemoryRecord {
uint32_t magic = kRecordMagic;
uint16_t version = kRecordVersion;
uint16_t reserved = 0;
MemorySnapshot snapshot{};
uint32_t checksum = 0;
};
template <size_t Capacity>
void CopyLegacyTruncated(
const char* value,
std::array<char, Capacity>* output)
{
output->fill('\0');
if (value == nullptr) {
return;
}
size_t length = std::min(
std::strlen(value), Capacity - 1);
while (length > 0 &&
(static_cast<uint8_t>(value[length]) & 0xC0U) == 0x80U) {
--length;
}
std::memcpy(output->data(), value, length);
}
} // namespace
bool NvsMemoryCache::Load()
{
std::lock_guard<std::mutex> lock(mutex_);
snapshot_ = {};
if (LoadNvsLocked()) {
return true;
}
if (!LoadLegacyPartitionLocked()) {
ESP_LOGI(kTag, "no valid memory snapshot");
return true;
}
if (!SaveLocked(snapshot_)) {
ESP_LOGW(kTag, "legacy snapshot loaded but NVS migration failed");
}
return true;
}
void NvsMemoryCache::CopySnapshot(MemorySnapshot* output) const
{
if (output == nullptr) {
return;
}
std::lock_guard<std::mutex> lock(mutex_);
*output = snapshot_;
}
bool NvsMemoryCache::Update(const MemorySnapshot& snapshot)
{
if (!IsValidMemorySnapshot(snapshot)) {
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
if (!SaveLocked(snapshot)) {
return false;
}
snapshot_ = snapshot;
ESP_LOGD(kTag,
"snapshot saved child_bytes=%u brain_bytes=%u interactions=%ld",
static_cast<unsigned>(
std::strlen(snapshot_.child_name.data())),
static_cast<unsigned>(
std::strlen(snapshot_.brain_text.data())),
static_cast<long>(snapshot_.interaction_count));
return true;
}
bool NvsMemoryCache::LoadNvsLocked()
{
nvs_handle_t handle = 0;
if (nvs_open(kNamespace, NVS_READONLY, &handle) != ESP_OK) {
return false;
}
auto record = MakePsramObject<StoredMemoryRecord>();
if (!record) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
nvs_close(handle);
return false;
}
size_t size = sizeof(*record);
const esp_err_t result =
nvs_get_blob(handle, kSnapshotKey, record.get(), &size);
nvs_close(handle);
if (result != ESP_OK || size != sizeof(*record) ||
record->magic != kRecordMagic ||
record->version != kRecordVersion ||
!IsValidMemorySnapshot(record->snapshot) ||
record->checksum !=
MemorySnapshotChecksum(record->snapshot)) {
return false;
}
snapshot_ = record->snapshot;
ESP_LOGI(kTag, "loaded memory snapshot from NVS");
return true;
}
bool NvsMemoryCache::LoadLegacyPartitionLocked()
{
const esp_partition_t* partition = esp_partition_find_first(
ESP_PARTITION_TYPE_DATA,
ESP_PARTITION_SUBTYPE_DATA_SPIFFS,
kLegacyPartitionLabel);
if (partition == nullptr) {
return false;
}
uint32_t header[2]{};
if (esp_partition_read(
partition, 0, header, sizeof(header)) != ESP_OK ||
header[0] != kLegacyMagic || header[1] == 0 ||
header[1] > kMaximumLegacyJsonBytes ||
sizeof(header) + header[1] > partition->size) {
return false;
}
auto* json = static_cast<char*>(heap_caps_calloc(
header[1] + 1,
sizeof(char),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
if (json == nullptr) {
return false;
}
const esp_err_t read_result = esp_partition_read(
partition, sizeof(header), json, header[1]);
cJSON* root = read_result == ESP_OK
? cJSON_ParseWithLength(json, header[1])
: nullptr;
heap_caps_free(json);
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
return false;
}
auto migrated = MakePsramObject<MemorySnapshot>();
if (!migrated) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
cJSON_Delete(root);
return false;
}
const cJSON* brain =
cJSON_GetObjectItemCaseSensitive(root, "brain");
const cJSON* name =
cJSON_GetObjectItemCaseSensitive(root, "name");
const cJSON* count =
cJSON_GetObjectItemCaseSensitive(root, "count");
if (cJSON_IsString(brain)) {
CopyLegacyTruncated(
brain->valuestring, &migrated->brain_text);
}
if (cJSON_IsString(name)) {
CopyLegacyTruncated(
name->valuestring, &migrated->child_name);
}
if (cJSON_IsNumber(count) && count->valuedouble >= 0 &&
count->valuedouble <= INT32_MAX) {
migrated->interaction_count = count->valueint;
}
cJSON_Delete(root);
if (!IsValidMemorySnapshot(*migrated) ||
!migrated->HasData()) {
return false;
}
snapshot_ = *migrated;
ESP_LOGI(kTag, "migrated legacy claude_mem snapshot");
return true;
}
bool NvsMemoryCache::SaveLocked(const MemorySnapshot& snapshot)
{
auto record = MakePsramObject<StoredMemoryRecord>();
if (!record) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
return false;
}
record->snapshot = snapshot;
record->checksum = MemorySnapshotChecksum(record->snapshot);
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNamespace, NVS_READWRITE, &handle);
if (result == ESP_OK) {
result = nvs_set_blob(
handle, kSnapshotKey, record.get(), sizeof(*record));
}
if (result == ESP_OK) {
result = nvs_commit(handle);
}
if (handle != 0) {
nvs_close(handle);
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "NVS save failed: %s",
esp_err_to_name(result));
return false;
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,24 @@
#pragma once
#include "ports/memory_cache.h"
#include <mutex>
namespace borla {
class NvsMemoryCache final : public IMemoryCache {
public:
bool Load() override;
void CopySnapshot(MemorySnapshot* output) const override;
bool Update(const MemorySnapshot& snapshot) override;
private:
bool LoadNvsLocked();
bool LoadLegacyPartitionLocked();
bool SaveLocked(const MemorySnapshot& snapshot);
mutable std::mutex mutex_;
MemorySnapshot snapshot_{};
};
} // namespace borla

View File

@@ -0,0 +1,56 @@
#include "memory/memory_types.h"
#include <cstring>
namespace borla {
namespace {
constexpr uint32_t kFnvOffset = 2166136261U;
constexpr uint32_t kFnvPrime = 16777619U;
void HashBytes(
uint32_t* hash,
const void* data,
size_t size)
{
const auto* bytes = static_cast<const uint8_t*>(data);
for (size_t index = 0; index < size; ++index) {
*hash ^= bytes[index];
*hash *= kFnvPrime;
}
}
template <size_t Capacity>
bool IsTerminated(const std::array<char, Capacity>& value)
{
return std::memchr(value.data(), '\0', value.size()) != nullptr;
}
} // namespace
bool IsValidMemorySnapshot(const MemorySnapshot& snapshot)
{
return IsTerminated(snapshot.child_name) &&
IsTerminated(snapshot.brain_text) &&
snapshot.interaction_count >= 0;
}
uint32_t MemorySnapshotChecksum(const MemorySnapshot& snapshot)
{
uint32_t hash = kFnvOffset;
HashBytes(
&hash,
snapshot.child_name.data(),
snapshot.child_name.size());
HashBytes(
&hash,
snapshot.brain_text.data(),
snapshot.brain_text.size());
HashBytes(
&hash,
&snapshot.interaction_count,
sizeof(snapshot.interaction_count));
return hash;
}
} // namespace borla

View File

@@ -0,0 +1,26 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
inline constexpr size_t kMemoryChildNameCapacity = 64;
inline constexpr size_t kMemoryBrainTextCapacity = 2048;
struct MemorySnapshot {
std::array<char, kMemoryChildNameCapacity> child_name{};
std::array<char, kMemoryBrainTextCapacity> brain_text{};
int32_t interaction_count = 0;
bool HasData() const
{
return child_name[0] != '\0' || brain_text[0] != '\0';
}
};
bool IsValidMemorySnapshot(const MemorySnapshot& snapshot);
uint32_t MemorySnapshotChecksum(const MemorySnapshot& snapshot);
} // namespace borla

135
main/ota/ota_endpoint.cc Normal file
View File

@@ -0,0 +1,135 @@
#include "ota/ota_endpoint.h"
#include <cstring>
namespace borla {
namespace {
constexpr const char kWildcardHost[] = "0.0.0.0";
constexpr size_t kWildcardHostLength = sizeof(kWildcardHost) - 1;
bool Contains(const char* haystack, const char* needle)
{
return haystack != nullptr && needle != nullptr &&
std::strstr(haystack, needle) != nullptr;
}
// Extract the host portion of "<scheme>://<host>[:port][/path]".
// Returns 0 when the URL has no scheme separator or an empty host.
size_t HostSpan(const char* url, const char** host_begin)
{
if (url == nullptr || host_begin == nullptr) {
return 0;
}
const char* separator = std::strstr(url, "://");
if (separator == nullptr) {
return 0;
}
const char* begin = separator + 3;
const char* cursor = begin;
while (*cursor != '\0' && *cursor != ':' && *cursor != '/') {
cursor++;
}
*host_begin = begin;
return static_cast<size_t>(cursor - begin);
}
} // namespace
bool IsRolloverEndpoint(const char* url)
{
if (url == nullptr || url[0] == '\0') {
return false;
}
if (Contains(url, ".lkall.com") &&
(Contains(url, "-dev.") || Contains(url, "-moe.") ||
Contains(url, "borlaws.lkall.com") ||
Contains(url, "borla-ota.lkall.com"))) {
return true;
}
return Contains(url, "192.168.1.121") ||
Contains(url, "117.50.44.247");
}
bool SubstituteWildcardHost(
const char* url,
const char* ota_url,
char* output,
size_t capacity)
{
if (url == nullptr || output == nullptr || capacity == 0) {
return false;
}
const char* wildcard = std::strstr(url, kWildcardHost);
if (wildcard == nullptr) {
return false;
}
const char* ota_host = nullptr;
const size_t ota_host_size = HostSpan(ota_url, &ota_host);
if (ota_host_size == 0 ||
(ota_host_size == kWildcardHostLength &&
std::strncmp(ota_host, kWildcardHost, kWildcardHostLength) == 0)) {
return false;
}
const size_t prefix_size = static_cast<size_t>(wildcard - url);
const char* suffix = wildcard + kWildcardHostLength;
const size_t suffix_size = std::strlen(suffix);
const size_t total = prefix_size + ota_host_size + suffix_size;
if (total >= capacity) {
return false;
}
std::memcpy(output, url, prefix_size);
std::memcpy(output + prefix_size, ota_host, ota_host_size);
std::memcpy(
output + prefix_size + ota_host_size, suffix, suffix_size);
output[total] = '\0';
return true;
}
bool ResolveRealtimeUrl(
const char* url,
const char* ota_url,
const char* default_url,
char* output,
size_t capacity)
{
if (output == nullptr || capacity == 0) {
return false;
}
const char* candidate = url;
if (candidate == nullptr || candidate[0] == '\0') {
candidate = nullptr;
}
if (candidate != nullptr) {
if (SubstituteWildcardHost(
candidate, ota_url, output, capacity)) {
// A substituted URL is by construction the reachable OTA host, so
// it is never treated as a rollover default.
return true;
}
if (std::strstr(candidate, kWildcardHost) != nullptr) {
// Wildcard host that could not be resolved is unusable.
candidate = nullptr;
}
}
if (candidate != nullptr && IsRolloverEndpoint(candidate)) {
candidate = nullptr;
}
if (candidate == nullptr) {
candidate = default_url;
}
if (candidate == nullptr || candidate[0] == '\0') {
return false;
}
const size_t size = std::strlen(candidate);
if (size >= capacity) {
return false;
}
std::memcpy(output, candidate, size + 1);
return true;
}
} // namespace borla

50
main/ota/ota_endpoint.h Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#include "protocol/websocket_transport.h"
#include <array>
#include <cstddef>
namespace borla {
// Endpoint block carried by the OTA check response. The OTA service is the
// only channel that can repoint a fielded device at a different realtime
// server, so the URL/token pair travels with the firmware manifest rather than
// with the realtime protocol itself.
struct OtaEndpointConfig {
std::array<char, kWebsocketUrlCapacity> url{};
std::array<char, kWebsocketTokenCapacity> token{};
bool has_url = false;
bool has_token = false;
bool HasAny() const { return has_url || has_token; }
};
// True for endpoints that ship as build/staging defaults. A saved value that
// matches one of these is treated as "not deliberately provisioned" and is
// replaced by the current default, so a device that once talked to a retired
// staging host recovers on its own instead of retrying it forever.
bool IsRolloverEndpoint(const char* url);
// Some deployments answer with a wildcard bind address in the websocket block.
// Substitute the host the OTA request itself was answered by, which is the
// only host the device is known to be able to reach.
// Returns false when `url` has no 0.0.0.0 host, when `ota_url` has no usable
// host, or when the result would not fit; `output` is only written on true.
bool SubstituteWildcardHost(
const char* url,
const char* ota_url,
char* output,
size_t capacity);
// Full resolution used by OtaService: applies SubstituteWildcardHost, then
// falls back to `default_url` when the result is a rollover endpoint.
// Returns false when nothing usable could be produced.
bool ResolveRealtimeUrl(
const char* url,
const char* ota_url,
const char* default_url,
char* output,
size_t capacity);
} // namespace borla

View File

@@ -0,0 +1,232 @@
#include "ota/ota_response_parser.h"
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstring>
#include <cJSON.h>
namespace borla {
namespace {
const char* StringField(const cJSON* root, const char* name)
{
const cJSON* value =
cJSON_GetObjectItemCaseSensitive(root, name);
return cJSON_IsString(value) ? value->valuestring : nullptr;
}
bool CopyBounded(const char* source, char* output, size_t capacity)
{
if (source == nullptr || output == nullptr || capacity == 0) {
return false;
}
const size_t size = std::strlen(source);
if (size == 0 || size >= capacity) {
return false;
}
std::memcpy(output, source, size);
output[size] = '\0';
return true;
}
bool IsSafeUrl(const char* url, bool allow_insecure_http)
{
return url != nullptr &&
(std::strncmp(url, "https://", 8) == 0 ||
(allow_insecure_http &&
std::strncmp(url, "http://", 7) == 0));
}
int HexNibble(char value)
{
if (value >= '0' && value <= '9') {
return value - '0';
}
value = static_cast<char>(
std::tolower(static_cast<unsigned char>(value)));
return value >= 'a' && value <= 'f'
? value - 'a' + 10
: -1;
}
int NextVersionPart(const char** cursor)
{
const char* value = *cursor;
while (*value == 'v' || *value == 'V' ||
*value == '.' || *value == '-' ||
std::isspace(static_cast<unsigned char>(*value))) {
value++;
}
int part = 0;
while (std::isdigit(static_cast<unsigned char>(*value))) {
if (part <= (INT_MAX - 9) / 10) {
part = part * 10 + (*value - '0');
}
value++;
}
while (*value != '\0' && *value != '.') {
value++;
}
*cursor = value;
return part;
}
} // namespace
OtaParseStatus OtaResponseParser::Parse(
const char* json,
size_t size,
const char* current_version,
bool allow_insecure_http,
OtaManifest* manifest,
OtaEndpointConfig* endpoint) const
{
if (json == nullptr || size == 0 ||
current_version == nullptr || manifest == nullptr) {
return OtaParseStatus::kMalformed;
}
*manifest = {};
if (endpoint != nullptr) {
*endpoint = {};
}
cJSON* root = cJSON_ParseWithLength(json, size);
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
return OtaParseStatus::kMalformed;
}
// The websocket block is parsed first and kept across every firmware-block
// outcome below: the server may hand out a new realtime endpoint on a
// response that carries no image at all, and losing it would strand the
// device on the previous host.
const cJSON* websocket =
cJSON_GetObjectItemCaseSensitive(root, "websocket");
if (endpoint != nullptr && cJSON_IsObject(websocket)) {
const char* endpoint_url = StringField(websocket, "url");
const char* endpoint_token = StringField(websocket, "token");
if (endpoint_url != nullptr) {
endpoint->has_url = CopyBounded(
endpoint_url,
endpoint->url.data(),
endpoint->url.size());
}
if (endpoint_token != nullptr) {
endpoint->has_token = CopyBounded(
endpoint_token,
endpoint->token.data(),
endpoint->token.size());
}
}
const cJSON* firmware =
cJSON_GetObjectItemCaseSensitive(root, "firmware");
if (cJSON_IsNull(firmware) || firmware == nullptr) {
cJSON_Delete(root);
return OtaParseStatus::kOk;
}
if (!cJSON_IsObject(firmware)) {
cJSON_Delete(root);
return OtaParseStatus::kInvalidManifest;
}
const char* version = StringField(firmware, "version");
const char* url = StringField(firmware, "url");
const char* sha256 = StringField(firmware, "sha256");
const cJSON* size_value =
cJSON_GetObjectItemCaseSensitive(firmware, "size");
uint8_t digest[32]{};
if (!CopyBounded(
version, manifest->version.data(),
manifest->version.size()) ||
!CopyBounded(
url, manifest->url.data(), manifest->url.size()) ||
!CopyBounded(
sha256, manifest->sha256.data(),
manifest->sha256.size()) ||
!DecodeSha256(sha256, digest) ||
!cJSON_IsNumber(size_value) ||
!std::isfinite(size_value->valuedouble) ||
std::floor(size_value->valuedouble) !=
size_value->valuedouble ||
size_value->valuedouble <= 0 ||
size_value->valuedouble > UINT32_MAX) {
cJSON_Delete(root);
return OtaParseStatus::kInvalidManifest;
}
if (!IsSafeUrl(url, allow_insecure_http)) {
cJSON_Delete(root);
return OtaParseStatus::kUnsafeUrl;
}
if (CompareVersions(version, current_version) <= 0) {
*manifest = {};
cJSON_Delete(root);
return OtaParseStatus::kOk;
}
manifest->size =
static_cast<uint32_t>(size_value->valuedouble);
const cJSON* automatic =
cJSON_GetObjectItemCaseSensitive(root, "auto_update");
const cJSON* forced =
cJSON_GetObjectItemCaseSensitive(root, "force_upgrade");
if ((automatic != nullptr && !cJSON_IsBool(automatic)) ||
(forced != nullptr && !cJSON_IsBool(forced))) {
cJSON_Delete(root);
return OtaParseStatus::kInvalidManifest;
}
if (cJSON_IsTrue(automatic)) {
manifest->policy = OtaUpgradePolicy::kAutomatic;
} else if (cJSON_IsTrue(forced)) {
manifest->policy = OtaUpgradePolicy::kForced;
} else {
manifest->policy = OtaUpgradePolicy::kOptional;
}
cJSON_Delete(root);
return OtaParseStatus::kOk;
}
int OtaResponseParser::CompareVersions(
const char* left,
const char* right)
{
if (left == nullptr || right == nullptr) {
return 0;
}
const char* left_cursor = left;
const char* right_cursor = right;
for (size_t i = 0; i < 8; ++i) {
const int left_part = NextVersionPart(&left_cursor);
const int right_part = NextVersionPart(&right_cursor);
if (left_part != right_part) {
return left_part < right_part ? -1 : 1;
}
if (*left_cursor == '\0' && *right_cursor == '\0') {
return 0;
}
}
return 0;
}
bool OtaResponseParser::DecodeSha256(
const char* hex,
uint8_t output[32])
{
if (hex == nullptr || output == nullptr ||
std::strlen(hex) != 64) {
return false;
}
for (size_t i = 0; i < 32; ++i) {
const int upper = HexNibble(hex[i * 2]);
const int lower = HexNibble(hex[i * 2 + 1]);
if (upper < 0 || lower < 0) {
return false;
}
output[i] = static_cast<uint8_t>((upper << 4) | lower);
}
return true;
}
} // namespace borla

Some files were not shown because too many files have changed in this diff Show More