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

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