#include "application.h" #include "boards/board.h" #include "boards/wifi_board.h" #include "boards/dual_network_board.h" #include "system_info.h" #include "settings.h" #include "ota.h" #include "memory_cache.h" #include "audio/audio_codec.h" #include "protocols/websocket_protocol.h" #include "conn_error_config.h" #include #include #include #include #include #include #include #include #include #include #include #define TAG "Application" // Built-in first-day prompt wake alarm. Keep this in sync with server sleep_companion.py. static constexpr int32_t kBuiltInFirstDayPromptAlarmId = -203000; static constexpr uint8_t kBuiltInFirstDayPromptHour = 20; static constexpr uint8_t kBuiltInFirstDayPromptMinute = 30; static constexpr uint8_t kBuiltInFirstDayPromptRepeatMask = 0x7F; // daily static constexpr const char *kBuiltInFirstDayPromptLabel = "first_day_prompt"; static constexpr const char *kServerFirstDayPromptLabel = "first_day_sleep_prompt"; static constexpr const char *kDevelopmentWebSocketUrl = "wss://borlaws.lkall.com/v1/ws"; static bool IsKnownSavedEndpoint(const std::string &url) { const bool lkall_host = url.find(".lkall.com") != std::string::npos; return (lkall_host && (url.find("-dev.") != std::string::npos || url.find("-moe.") != std::string::npos || url.find("borlaws.lkall.com") != std::string::npos || url.find("borla-ota.lkall.com") != std::string::npos)) || url.find("192.168.1.121") != std::string::npos || url.find("117.50.44.247") != std::string::npos; } // ADR-004 Phase 7: play_local group name ↔ PromptGroup lookup. // Replaces the long if-else chain so new prompts only need one entry here // instead of a new else-if branch. Forward (name→enum) used by play_local // handler; reverse (enum→name) used by PlayLocal helper when emitting signals. static bool LookupPromptGroupByName(const std::string &name, PromptGroup *out) { static const std::unordered_map kMap = { {"welcome", kPromptWelcome}, {"shutdown", kPromptShutdown}, {"no_network", kPromptNoNetwork}, {"error", kPromptError}, {"wifi_config", kPromptWifiConfig}, {"alarm_set", kPromptAlarmSet}, {"alarm_wake", kPromptAlarmWake}, {"device_already_bound", kPromptDeviceAlreadyBound}, {"boot", kPromptBoot}, {"server_error", kPromptServerError}, {"story_expired", kPromptStoryExpired}, {"wake_response", kPromptWakeResponse}, {"idle_check", kPromptIdleCheck}, {"idle_goodbye", kPromptIdleGoodbye}, {"wifi_success", kPromptWifiSuccess}, {"low_battery_20", kPromptLowBattery20}, {"low_battery_10", kPromptLowBattery10}, {"activation_device", kPromptActivationDevice}, {"digit_0", kPromptDigit0}, {"digit_1", kPromptDigit1}, {"digit_2", kPromptDigit2}, {"digit_3", kPromptDigit3}, {"digit_4", kPromptDigit4}, {"digit_5", kPromptDigit5}, {"digit_6", kPromptDigit6}, {"digit_7", kPromptDigit7}, {"digit_8", kPromptDigit8}, {"digit_9", kPromptDigit9}, }; auto it = kMap.find(name); if (it == kMap.end()) return false; *out = it->second; return true; } static const char *PromptGroupName(PromptGroup g) { switch (g) { case kPromptWelcome: return "welcome"; case kPromptShutdown: return "shutdown"; case kPromptNoNetwork: return "no_network"; case kPromptError: return "error"; case kPromptWifiConfig: return "wifi_config"; case kPromptAlarmSet: return "alarm_set"; case kPromptAlarmWake: return "alarm_wake"; case kPromptDeviceAlreadyBound: return "device_already_bound"; case kPromptBoot: return "boot"; case kPromptServerError: return "server_error"; case kPromptStoryExpired: return "story_expired"; case kPromptWakeResponse: return "wake_response"; case kPromptIdleCheck: return "idle_check"; case kPromptIdleGoodbye: return "idle_goodbye"; case kPromptWifiSuccess: return "wifi_success"; case kPromptLowBattery20: return "low_battery_20"; case kPromptLowBattery10: return "low_battery_10"; case kPromptActivationDevice: return "activation_device"; case kPromptDigit0: return "digit_0"; case kPromptDigit1: return "digit_1"; case kPromptDigit2: return "digit_2"; case kPromptDigit3: return "digit_3"; case kPromptDigit4: return "digit_4"; case kPromptDigit5: return "digit_5"; case kPromptDigit6: return "digit_6"; case kPromptDigit7: return "digit_7"; case kPromptDigit8: return "digit_8"; case kPromptDigit9: return "digit_9"; } return "unknown"; } static const char *const STATE_STRINGS[] = { "unknown", "starting", "configuring", "idle", "connecting", "listening", "speaking", "ringing", "calling", "upgrading", }; Application::Application() { event_group_ = xEventGroupCreate(); esp_timer_create_args_t clock_args = { .callback = [](void *arg) { xEventGroupSetBits(((Application *)arg)->event_group_, MAIN_EVENT_CLOCK_TICK); }, .arg = this, .dispatch_method = ESP_TIMER_TASK, .name = "clock", .skip_unhandled_events = true}; esp_timer_create(&clock_args, &clock_timer_handle_); esp_timer_create_args_t status_args = { .callback = [](void *arg) { xEventGroupSetBits(((Application *)arg)->event_group_, MAIN_EVENT_STATUS_TICK); }, .arg = this, .dispatch_method = ESP_TIMER_TASK, .name = "status", .skip_unhandled_events = true}; esp_timer_create(&status_args, &status_timer_handle_); // IdleWatchdog timers — fire on esp_timer task; both handlers Schedule() // back to MainEventLoop so all watchdog logic runs single-threaded. esp_timer_create_args_t idle_master_args = { .callback = [](void *arg) { auto *app = static_cast(arg); app->Schedule([app]() { app->IdleWatchdogOnMasterFire(); }); }, .arg = this, .dispatch_method = ESP_TIMER_TASK, .name = "idle_master", .skip_unhandled_events = true}; esp_timer_create(&idle_master_args, &idle_master_timer_); esp_timer_create_args_t idle_window_args = { .callback = [](void *arg) { auto *app = static_cast(arg); app->Schedule([app]() { app->IdleWatchdogOnWindowFire(); }); }, .arg = this, .dispatch_method = ESP_TIMER_TASK, .name = "idle_window", .skip_unhandled_events = true}; esp_timer_create(&idle_window_args, &idle_window_timer_); // Activation code replay timer — fires periodically to re-read the code. esp_timer_create_args_t replay_args = { .callback = [](void *arg) { auto *app = static_cast(arg); app->Schedule([app]() { app->OnActivationReplayTimer(); }); }, .arg = this, .dispatch_method = ESP_TIMER_TASK, .name = "activation_replay", .skip_unhandled_events = true}; esp_timer_create(&replay_args, &activation_replay_timer_); } Application::~Application() { esp_timer_stop(clock_timer_handle_); esp_timer_delete(clock_timer_handle_); esp_timer_stop(status_timer_handle_); esp_timer_delete(status_timer_handle_); if (idle_master_timer_) { esp_timer_stop(idle_master_timer_); esp_timer_delete(idle_master_timer_); } if (idle_window_timer_) { esp_timer_stop(idle_window_timer_); esp_timer_delete(idle_window_timer_); } if (activation_replay_timer_) { esp_timer_stop(activation_replay_timer_); esp_timer_delete(activation_replay_timer_); } // 2026-6-24 ckkj debug if (tts_timeout_timer_) { esp_timer_stop(tts_timeout_timer_); esp_timer_delete(tts_timeout_timer_); } // 2026-6-30 ckkj debug if (speaking_delay_timer_) { esp_timer_stop(speaking_delay_timer_); esp_timer_delete(speaking_delay_timer_); } if (tts_stream_idle_timer_) { esp_timer_stop(tts_stream_idle_timer_); esp_timer_delete(tts_stream_idle_timer_); } vEventGroupDelete(event_group_); } Application &Application::GetInstance() { static Application instance; return instance; } void Application::Start() { auto &board = Board::GetInstance(); SetDeviceState(kDeviceStateStarting); ESP_LOGI(TAG, "Borla firmware %s starting (MAC: %s, Chip: %s)", SystemInfo::GetAppVersion().c_str(), SystemInfo::GetMacAddress().c_str(), SystemInfo::GetChipModelName().c_str()); // BOOT_BUTTON_GPIO=0 hold 残留清理。 // 之前版本 EnterSoftOff 用 ext1_wakeup + rtc_gpio_hold_en 让 GPIO0 在 light // sleep 中保持输入+上拉,但 rtc_gpio_deinit 不会清 hold bit。 // 如果用户从那版固件 OTA 到新版(或新版烧录后第一次 re-boot 前还处于 // hold 残留),iot_button 的 gpio_config 会被无效化 → 按钮全死。 // 在 Board 取到后、audio 初始化前主动清一次 hold,保底修复已损设备。 gpio_hold_dis(GPIO_NUM_0); rtc_gpio_hold_dis(GPIO_NUM_0); // 初始化音频 auto *codec = board.GetAudioCodec(); codec->Start(); audio_service_.Initialize(codec); audio_service_.Start(); // ADR-004 Phase 3: restore alarm tone indices from NVS. // Before this, tone indices were memory-only → lost on reboot → the first // alarm after a reboot always plays a random tone. Now we persist them // whenever alarm_config arrives; here we reload so offline alarm fires // (before first hello) use the correct tone too. { Settings alarm_cfg("alarm_cfg", false); int set_idx = alarm_cfg.GetInt("set_idx", -1); int wake_idx = alarm_cfg.GetInt("wake_idx", -1); alarm_set_tone_index_.store(set_idx); alarm_wake_tone_index_.store(wake_idx); if (set_idx != -1 || wake_idx != -1) { ESP_LOGI(TAG, "Alarm tone indices loaded from NVS: set=%d wake=%d", set_idx, wake_idx); } } // 初始化唤醒词检测 // 提前到 boot prompt 之前,使 MainEventLoop 可以在 boot prompt 播放期间 // 并行运行,处理事件(即使 wake word 在 Starting 状态会被忽略)。 if (audio_service_.InitWakeWord()) { audio_service_.wake_word_detector().SetCallback([this]() { xEventGroupSetBits(event_group_, MAIN_EVENT_WAKE_WORD); }); ESP_LOGI(TAG, "Wake word detector initialized"); } else { ESP_LOGW(TAG, "Wake word detector init failed, fallback to button mode"); } // Load memory cache from Flash MemoryCache::GetInstance().Load(); // 音频回调 AudioServiceCallbacks callbacks; callbacks.on_send_queue_available = [this]() { xEventGroupSetBits(event_group_, MAIN_EVENT_SEND_AUDIO); }; // IdleWatchdog: rough VAD fired during 15s wait window or sleeping → reset // Also used to interrupt TTS playback when wake word detection is disabled callbacks.on_voice_detected = [this]() { Schedule([this]() { // ESP_LOGI(TAG, "[IdleWdg] energy VAD fired"); // IdleWatchdogReset(); ESP_LOGI(TAG, "[VAD] energy VAD fired, state=%s", STATE_STRINGS[device_state_]); // 在 Speaking 状态下,能量 VAD 触发可用于打断播放 if (device_state_ == kDeviceStateSpeaking) { ESP_LOGI(TAG, "[VAD] interrupting TTS playback"); audio_service_.ResetDecoder(); CancelTtsTimeoutTimer(); AbortSpeaking(kAbortReasonWakeWordDetected); Schedule([this]() { SetListeningMode(kListeningModeAutoStop); }); } // 重置 IdleWatchdog(适用于所有状态) IdleWatchdogReset(); }); }; audio_service_.SetCallbacks(callbacks); // 启动主事件循环任务 // 提前到 boot prompt 之前,避免 Start() 在 WaitForPlaybackComplete 中 // 阻塞 20 秒期间设备完全无响应。 xTaskCreate([](void *arg) { ((Application*)arg)->MainEventLoop(); vTaskDelete(nullptr); }, "main_loop", 8 * 1024, this, 3, &main_event_loop_task_); // 开机即时提示音:音频管线就绪后立刻播,不等 WiFi/WebSocket。 // 这段音频在用户长按开机后 ~200ms 内就能听到,覆盖后续联网/加载的静默期。 // // 若本次是「双击配网」触发的重启(WifiBoard 在构造时已把 force_ap 消费成 // wifi_config_mode_),紧接着会进配网模式播 wifi_config 提示音。两段同时 // 推到解码队列会叠播混音,所以配网场景下跳过 boot,只让 wifi_config 播。 // // 实际板子继承链是 BorlaS3Board → DualNetworkBoard → Board,WifiBoard 是 // DualNetworkBoard 内部的 unique_ptr 成员(非父类),所以要走 // DualNetworkBoard::IsWifiConfigMode() 这个转发接口。 { auto *dual_board = dynamic_cast(&board); auto *wifi_board = dynamic_cast(&board); bool will_enter_ap = false; if (dual_board) will_enter_ap = dual_board->IsWifiConfigMode(); else if (wifi_board) will_enter_ap = wifi_board->IsWifiConfigMode(); if (will_enter_ap) { ESP_LOGI(TAG, "Boot prompt skipped (entering wifi config)"); } else if (audio_prompt_.HasPrompts(kPromptBoot)) { ESP_LOGI(TAG, "Playing boot prompt"); local_prompt_playing_.store(true);// 2026-6-29 ckkj debug // PlayLocal sends signal only when WS is open; at this point it's // not, so this is effectively PlayRandom — safe. audio_prompt_.PlayLocal(kPromptBoot, audio_service_, protocol_.get(), "boot"); // Note: no NotifyLocalDone here because PlayTask is async and we // don't block Start(). Server won't see done — but server also // can't have been contacted yet at this point, so this is fine. // Once WS connects later, server is already past the race window. // 2026-6-29 ckkj debug 新增:阻塞等待开机提示音完整播放完毕,再往下初始化 audio_service_.WaitForPlaybackComplete(20000); local_prompt_playing_.store(false); // 播放完成清除标记 //debug end } } // === Boot-time battery check === // Read battery immediately so we can: // 1. <10%: play warning, then EnterSoftOff. Don't continue boot. // 2. ≤20%: continue boot, but flag so the periodic check plays the // warning once we reach idle (avoids talking over boot/welcome). // Charging devices skip both paths — the user is already responding. { int boot_battery = board.GetBatteryLevel(); bool boot_charging = board.IsCharging(); ESP_LOGI(TAG, "[LowBatt] boot check: battery=%d%% charging=%d", boot_battery, boot_charging ? 1 : 0); if (!boot_charging && boot_battery >= 0) { if (boot_battery < 10) { ESP_LOGW(TAG, "[LowBatt] boot battery <10%% — shutting down"); // Boot prompt 已在上方 WaitForPlaybackComplete(20000) 确保播完, // 此处无需再等待,直接播放低电量提示音。 if (audio_prompt_.HasPrompts(kPromptLowBattery10)) { audio_prompt_.PlayLocal(kPromptLowBattery10, audio_service_, /*protocol=*/nullptr, "low_battery_10"); audio_service_.WaitForPlaybackComplete(10000); } board.EnterSoftOff(); return; // Start() ends here; device is in light sleep } if (boot_battery <= 20) { pending_low_battery_warning_at_boot_ = true; ESP_LOGI(TAG, "[LowBatt] boot battery ≤20%% — will warn after idle"); } } } // 启动定时器 esp_timer_start_periodic(clock_timer_handle_, 1000000); // 1 秒 esp_timer_start_periodic(status_timer_handle_, 60000000); // 60 秒 // 启动网络(WiFi 或 4G,可能阻塞在 AP 配网) board.StartNetwork(); // OTA 版本检查 + 获取 WebSocket URL Ota ota; CheckNewVersion(ota); // 初始化协议 protocol_ = std::make_unique(); protocol_->OnConnected([this]() { Schedule([this]() { SendStatusUpdate(); // Check if there's a pending OTA upgrade // Delay 2 seconds to ensure hello + components are ready before sending ota_notify // Skip OTA during phone call (M4 guard) if (pending_ota_ && device_state_ != kDeviceStateCalling && device_state_ != kDeviceStateRinging) { esp_timer_handle_t notify_timer = nullptr; esp_timer_create_args_t notify_args = { .callback = [](void* arg) { auto* app = static_cast(arg); std::string reason = app->pending_ota_reason_; std::string msg; // Optional: just inform, no upgrade, no suppression if (reason == "optional") { msg = "当前设备有最新版本,是否进行升级?"; ESP_LOGI("OTA", "Optional upgrade notify"); app->protocol_->SendText("{\"type\":\"ota_notify\",\"text\":\"" + msg + "\",\"optional\":true}"); app->pending_ota_.reset(); app->pending_ota_reason_.clear(); return; } // Auto or Force upgrade if (reason == "auto") { msg = "当前有最新版本,即将开始升级!请耐心等候"; } else { msg = "目前有大版本需要升级,否则设备将不可用,即将升级请耐心等候!"; } // If download URL is empty, notify but don't upgrade if (!app->pending_ota_->CanDownload()) { if (reason == "auto") { msg = "检测到新版本,升级文件准备中,请稍后重试"; } else { msg = "检测到需要升级的版本,升级文件准备中,请稍后重试"; } ESP_LOGW("OTA", "Download URL empty, notify only: %s", reason.c_str()); app->protocol_->SendText("{\"type\":\"ota_notify\",\"text\":\"" + msg + "\"}"); app->pending_ota_.reset(); app->pending_ota_reason_.clear(); return; } ESP_LOGI("OTA", "Sending TTS prompt: %s", reason.c_str()); app->protocol_->SendText("{\"type\":\"ota_notify\",\"text\":\"" + msg + "\"}"); // Delay 8 more seconds for TTS playback, then start upgrade // Use a FreeRTOS task (not esp_timer callback) because OTA // download is blocking and needs a large stack (8KB+). esp_timer_handle_t ota_timer = nullptr; esp_timer_create_args_t ota_args = { .callback = [](void* arg) { auto* a = static_cast(arg); xTaskCreate([](void* p) { auto* app = static_cast(p); ESP_LOGI("OTA", "Starting upgrade (dedicated task)..."); app->SetDeviceState(kDeviceStateUpgrading); if (!app->pending_ota_->StartUpgrade()) { ESP_LOGE("OTA", "Upgrade failed, resuming normal operation"); app->SetDeviceState(kDeviceStateIdle); } vTaskDelete(nullptr); }, "ota_task", 8192, a, 5, nullptr); }, .arg = arg, .dispatch_method = ESP_TIMER_TASK, .name = "ota_start", .skip_unhandled_events = false, }; esp_timer_create(&ota_args, &ota_timer); esp_timer_start_once(ota_timer, 8000000); }, .arg = this, .dispatch_method = ESP_TIMER_TASK, .name = "ota_notify", .skip_unhandled_events = false, }; esp_timer_create(¬ify_args, ¬ify_timer); esp_timer_start_once(notify_timer, 2000000); } }); }); protocol_->OnDisconnected([this]() { ESP_LOGW(TAG, "Protocol disconnected"); //2026-6-22 ckkj debug 防止AEC崩溃 audio_service_.EnableVoiceProcessing(false); // Only disable Call mode if not in listening state // to preserve voice recognition capability if (device_state_ != kDeviceStateListening) { audio_service_.EnableCallMode(false); } audio_service_.EnableBargeInMode(false); // 联网失败后重新联网,升级和启动状态除外 Schedule([this]() { if (device_state_ != kDeviceStateConnecting && device_state_ != kDeviceStateUpgrading && device_state_ != kDeviceStateStarting) { ESP_LOGI(TAG, "Scheduling reconnect after disconnection"); SetDeviceState(kDeviceStateConnecting); for (int attempt = 0; attempt < 3; attempt++) { if (protocol_->OpenAudioChannel()) { //connected = true; break; } ESP_LOGW(TAG, "Reconnect attempt %d failed, retrying...", attempt + 1); vTaskDelay(pdMS_TO_TICKS(2000)); } // if (!connected) { // ESP_LOGW(TAG, "Persistent connection failure, rebooting device..."); // esp_restart(); // } } }); }); protocol_->OnNetworkError([this](const std::string &message) { last_error_message_ = message; xEventGroupSetBits(event_group_, MAIN_EVENT_ERROR); }); protocol_->OnIncomingAudio([this](std::unique_ptr packet) { if (alarm_reminder_playing_.load()) { return; } if (device_state_ == kDeviceStateSpeaking || device_state_ == kDeviceStateCalling || device_state_ == kDeviceStateRinging || tts_audio_active_.load()) { // 2026-6-30 ckkj debug 收到 TTS 音频数据,重置流沉寂超时 if (tts_audio_active_.load()) { StartTtsStreamIdleTimer(); } audio_service_.PushPacketToDecodeQueue(std::move(packet)); } }); protocol_->OnAudioChannelOpened([this, &board]() { board.SetPowerSaveMode(false); if (IdleWatchdogShouldSkipChannelOpenReset()) { ESP_LOGI(TAG, "[IdleWdg] WS opened for idle_check; skip watchdog reset"); return; } // IdleWatchdog: WS up -> start 60s countdown. SetDeviceState(kIdle) // also calls reset, but OnAudioChannelOpened may fire before state // settles to idle (e.g. boot path → Connecting → Idle), so call here // explicitly to guarantee watchdog starts on any successful reconnect. IdleWatchdogReset(); }); protocol_->OnAudioChannelClosed([this, &board]() { tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); // 2026-6-30 ckkj debug WS 断开时取消 TTS 相关 timer,避免断线后误触发状态切换 CancelTtsTimeoutTimer(); CancelTtsStreamIdleTimer(); CancelSpeakingDelayTimer(); // Lazy reconnect (xiaozhi 原版策略):WS 断了就进 idle,不主动重连。 // 下次 SendText/SendAudio 时 WebsocketProtocol 会自动重新 OpenAudioChannel。 // 避免每次 ML307 瞬断都触发 10s 级别的 SSL/WS 握手让用户感知到"卡住"。 Schedule([this]() { if (device_state_ == kDeviceStateWifiConfiguring) return; if (shutting_down_.load()) return; if (device_state_ == kDeviceStateConnecting) return; SetDeviceState(kDeviceStateIdle); }); }); protocol_->OnIncomingJson([this](const cJSON *root) { auto* type = cJSON_GetObjectItem(root, "type"); if (!cJSON_IsString(type)) return; if (strcmp(type->valuestring, "tts") == 0) { auto* state = cJSON_GetObjectItem(root, "state"); if (!cJSON_IsString(state)) return; if (alarm_reminder_playing_.load()) { ESP_LOGI(TAG, "Ignoring TTS %s while alarm/reminder is playing", state->valuestring); return; } if (strcmp(state->valuestring, "start") == 0) { // Server is starting normal TTS — device must be activated now, // stop the activation-code replay loop. StopActivationReplay("tts started"); tts_audio_active_.store(true); tts_current_text_.clear(); // Order matters: ResetDecoder sets cancel=true (for in-flight // prompt teardown). SetPlaybackHint(true) MUST come after to // clear that flag, otherwise AudioOutputTask drops every TTS // frame on dequeue. Reversed order = silent TTS (root-caused). //2026-6-27 ckkj debug 正在播放,跳过ResetDecoder //audio_service_.ResetDecoder(); if (!local_prompt_playing_.load()) { audio_service_.ResetDecoder(); } audio_service_.SetPlaybackHint(true); // 2026-6-24 ckkj debug 启动 TTS 超时定时器,防止服务端没有发送 tts.stop 时设备卡住 StartTtsTimeoutTimer(); // 2026-6-30 ckkj debug 启动 TTS 流沉寂超时,监控数据流是否中断 StartTtsStreamIdleTimer(); Schedule([this]() { if ((device_state_ == kDeviceStateIdle || device_state_ == kDeviceStateListening) && tts_audio_active_.load()) { SetDeviceState(kDeviceStateSpeaking); } }); } else if (strcmp(state->valuestring, "stop") == 0) { //2026-6-21 ckkj debug 修复充电模式下立马被打断 //audio_service_.EnableBargeInMode(false); if (!tts_current_text_.empty()) { ESP_LOGI(TAG, "<< [full] %s", tts_current_text_.c_str()); tts_current_text_.clear(); } // 2026-6-23 ckkj debug 清空协议层的当前播放内容 if (protocol_) { protocol_->ClearCurrentPlaybackText(); } // 修复缺陷2:同时检查tts_audio_active_标志,避免标志状态不一致。 // 如果tts_audio_active_为true,即使不在speaking状态也应处理STOP(至少清理标志) if (device_state() != kDeviceStateSpeaking && !tts_audio_active_.load()) { ESP_LOGW(TAG, "no speaking ignore TTS STOP...."); return; } // 2026-6-30 ckkj debug 若当前仍在 listening(例如延迟切换期间收到 stop), // 清理 TTS 活跃标志并取消延迟 timer,避免后续错误切到 speaking tts_audio_active_.store(false); if (device_state() == kDeviceStateListening) { CancelSpeakingDelayTimer(); CancelTtsStreamIdleTimer(); audio_service_.SetPlaybackHint(false); ESP_LOGW(TAG, "TTS STOP received in listening state, cleaned up TTS flags"); return; } //2026-6-24 ckkj debug 取消 TTS 超时定时器 ESP_LOGW(TAG, "===== Server send TTS STOP, interrupt playback ====="); CancelTtsTimeoutTimer(); // 2026-6-30 ckkj debug 收到 tts.stop 说明流正常结束,取消流沉寂超时 CancelTtsStreamIdleTimer(); audio_service_.SetPlaybackHint(false); //audio_service_.WaitForPlaybackComplete(10000);//2026-6-28 ckkj debug阻塞等待所有TTS音频播放完毕,再切换监听 // Schedule([this]() { // if (device_state_ == kDeviceStateSpeaking) { // // Auto continue listening (continuous conversation mode) // SetListeningMode(kListeningModeAutoStop); // } // // Calling/Ringing: clear flags but don't change state // }); // 【核心修改】异步丢入子任务等待,主线程立刻释放处理网络报文 /*xTaskCreate([](void* arg){ auto self = static_cast(arg); self->audio_service_.WaitForPlaybackComplete(10000); self->Schedule([self](){ if (self->device_state_ == kDeviceStateSpeaking) { self->SetListeningMode(kListeningModeAutoStop); } }); vTaskDelete(nullptr); }, "wait_play", 3072, this, 5, nullptr);*/ // 动态等待时长:空队列快速退出,有音频等完整播放 bool decode_empty, play_empty; audio_service_.GetQueueEmptyStatus(decode_empty, play_empty); // 修复缺陷1:队列为空时不应仅等3ms,改为200ms给服务器新TTS数据留出到达窗口 int wait_ms = (decode_empty && play_empty) ? 200 : 10000; // 堆分配参数结构体:同时传递 Application 指针和等待时长, // 避免将 int 值强转为 void* 导致 Application* 指针为垃圾值。 struct WaitPlayParams { Application* self; int wait_ms; }; auto* params = new WaitPlayParams{this, wait_ms}; xTaskCreate([](void* arg){ auto* p = static_cast(arg); p->self->audio_service_.WaitForPlaybackComplete(p->wait_ms); p->self->Schedule([self = p->self](){ if (self->device_state_ == kDeviceStateSpeaking && !self->tts_audio_active_.load()) { self->SetListeningMode(kListeningModeAutoStop); } }); delete p; vTaskDelete(nullptr); }, "wait_play", 3072, params, 5, nullptr); } else if (strcmp(state->valuestring, "sentence_start") == 0) { StartTtsTimeoutTimer(); // 2026-6-30 ckkj debug 收到新的 TTS 文本,重置流沉寂超时 StartTtsStreamIdleTimer(); // 2026-6-25 ckkj debug 修复:TTS 被打断后忽略后续文本 if (!tts_audio_active_.load()) { ESP_LOGD(TAG, "Ignoring sentence_start: TTS already aborted"); return; } //debug end auto* text = cJSON_GetObjectItem(root, "text"); if (cJSON_IsString(text)) { ESP_LOGI(TAG, "<< %s", text->valuestring); tts_current_text_ += text->valuestring; // 2026-6-23 ckkj debug 更新协议层的当前播放内容,用于上下文保持 if (protocol_) { protocol_->SetCurrentPlaybackText(tts_current_text_); } } } } else if (strcmp(type->valuestring, "stt") == 0) { auto* text = cJSON_GetObjectItem(root, "text"); if (cJSON_IsString(text)) { ESP_LOGI(TAG, ">> %s", text->valuestring); } } else if (strcmp(type->valuestring, "llm") == 0) { auto* emotion = cJSON_GetObjectItem(root, "emotion"); if (cJSON_IsString(emotion)) { ESP_LOGI(TAG, "Emotion: %s", emotion->valuestring); } } else if (strcmp(type->valuestring, "control") == 0) { auto* action = cJSON_GetObjectItem(root, "action"); if (cJSON_IsString(action) && strcmp(action->valuestring, "volume") == 0) { auto* volume = cJSON_GetObjectItem(root, "volume"); if (cJSON_IsNumber(volume)) { int vol = volume->valueint; if (vol < AUDIO_CODEC_MIN_OUTPUT_VOLUME) vol = AUDIO_CODEC_MIN_OUTPUT_VOLUME; if (vol > AUDIO_CODEC_MAX_OUTPUT_VOLUME) vol = AUDIO_CODEC_MAX_OUTPUT_VOLUME; ESP_LOGI(TAG, "Control: set volume to %d", vol); SetSpeakerVolume(vol); } } else if (cJSON_IsString(action) && strcmp(action->valuestring, "wake_word") == 0) { auto* enabled = cJSON_GetObjectItem(root, "enabled"); bool enable = cJSON_IsTrue(enabled); ESP_LOGI(TAG, "Control: wake_word detection %s", enable ? "ON" : "OFF"); audio_service_.EnableWakeWordDetection(enable); } else if (cJSON_IsString(action) && strcmp(action->valuestring, "barge_in") == 0) { auto* enabled = cJSON_GetObjectItem(root, "enabled"); bool enable = cJSON_IsTrue(enabled); ESP_LOGI(TAG, "Control: TTS barge-in %s", enable ? "ON" : "OFF"); audio_service_.EnableBargeInMode(enable); if (device_state_ == kDeviceStateSpeaking) { audio_service_.EnableVoiceProcessing( enable && audio_service_.IsBargeInModeEnabled()); } } else if (cJSON_IsString(action) && strcmp(action->valuestring, "light_sleep") == 0) { ESP_LOGI(TAG, "Control: enter light sleep"); Schedule([this]() { IdleWatchdogStop(); IdleWatchdogEnterIdleSleeping(); }); } } else if (strcmp(type->valuestring, "play_local") == 0) { // Any other prompt (welcome / shutdown / alarm_set / ...) means the // device is no longer in the unactivated readout state — stop the // periodic activation-code replay. StopActivationReplay("play_local arrived"); auto* group_json = cJSON_GetObjectItem(root, "group"); if (cJSON_IsString(group_json)) { std::string group = group_json->valuestring; ESP_LOGI(TAG, "Play local audio: %s", group.c_str()); if (group == "snore_light") { Schedule([this, group]() { tts_audio_active_.store(true); audio_service_.ResetDecoder(); audio_service_.SetPlaybackHint(true); SetDeviceState(kDeviceStateSpeaking); for (int i = 0; i < 10; ++i) { audio_service_.PlayTone(82, 450, 0.05f); vTaskDelay(pdMS_TO_TICKS(550)); } tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); SetDeviceState(kDeviceStateIdle); protocol_->SendText("{\"type\":\"play_local\",\"state\":\"done\",\"group\":\"" + group + "\"}"); }); return; } // ADR-004 Phase 7: string→enum table lookup (was long if-else chain) PromptGroup pg; bool valid = LookupPromptGroupByName(group, &pg); if (valid) { // ADR-004 Phase 4: parse optional post_action / block_reconnect // fields from server so we no longer hard-code group=="shutdown" // semantics in firmware. // // post_action = "enter_soft_off" → same as long-press shutdown // block_reconnect = true → freeze WS reconnect // // Back-compat: if neither field is present AND group=="shutdown", // apply legacy behaviour (block reconnect + LED off after playback). auto* pa_json = cJSON_GetObjectItem(root, "post_action"); auto* br_json = cJSON_GetObjectItem(root, "block_reconnect"); std::string post_action = cJSON_IsString(pa_json) ? pa_json->valuestring : ""; bool explicit_block_reconnect = cJSON_IsTrue(br_json); bool any_new_field = !post_action.empty() || cJSON_IsBool(br_json); // Resolve final actions (new path takes precedence; legacy // fallback only when server didn't send any new field). bool block_reconnect = false; bool do_soft_off = false; if (any_new_field) { block_reconnect = explicit_block_reconnect; do_soft_off = (post_action == "enter_soft_off"); } else if (pg == kPromptShutdown) { // Legacy shutdown flow — preserve exact original behaviour block_reconnect = true; } if (block_reconnect) { ESP_LOGI(TAG, "play_local(%s): blocking auto-reconnect", group.c_str()); shutting_down_.store(true); } // Optional: play_local with index for preview int play_index = -1; auto* idx_json = cJSON_GetObjectItem(root, "index"); if (cJSON_IsNumber(idx_json)) play_index = idx_json->valueint; // Preempt: clear any in-flight playback queue NOW //audio_service_.ResetDecoder();//2026-6-27 ckkj debug 正在播放,跳过ResetDecoder Schedule([this, pg, group, play_index, block_reconnect, do_soft_off]() { tts_audio_active_.store(true); local_prompt_playing_.store(true);//2026-6-27 ckkj debug 正在播放本地提示音 // Suppress wake-word detection while the speaker is // playing the local prompt — otherwise prompts whose // text contains the wake word trigger self-abort via // ResetDecoder at application.cc:921, cutting off the // prompt mid-playback. bool wake_was_enabled = audio_service_.IsWakeWordDetectionEnabled(); if (wake_was_enabled) { audio_service_.EnableWakeWordDetection(false); } // ResetDecoder sets cancel=true; SetPlaybackHint(true) // must follow to clear it before frames are pushed. audio_service_.ResetDecoder(); audio_service_.SetPlaybackHint(true); SetDeviceState(kDeviceStateSpeaking); if (play_index >= 0) { audio_prompt_.PlayByIndex(pg, play_index, audio_service_); } else { audio_prompt_.PlayRandom(pg, audio_service_); } // PlayRandom pushes to decode queue async in a new task vTaskDelay(pdMS_TO_TICKS(400)); audio_service_.WaitForPlaybackComplete(20000); tts_audio_active_.store(false); local_prompt_playing_.store(false);//2026-6-27 ckkj debug audio_service_.SetPlaybackHint(false); // 状态保护:确保唤醒词检测被正确启用 if (wake_was_enabled) { audio_service_.EnableWakeWordDetection(true); } // Welcome 播完直接接 Listening(连续对话语义,与 TTS stop // 后的 SetListeningMode 路径一致),用户讲完一句 VAD // 自动停。其它 prompt 仍然回 Idle。 // if (pg == kPromptWelcome && !do_soft_off && // !(pg == kPromptShutdown && block_reconnect)) { // SetListeningMode(kListeningModeAutoStop); if ((pg == kPromptWelcome || pg == kPromptWakeResponse) && !do_soft_off && !(pg == kPromptShutdown && block_reconnect)) { if (device_state_ != kDeviceStateListening) { SetListeningMode(kListeningModeAutoStop); } } else { SetDeviceState(kDeviceStateIdle); } protocol_->SendText("{\"type\":\"play_local\",\"state\":\"done\",\"group\":\"" + group + "\"}"); // After shutdown-like prompts: LED off, stay idle. // Triggered by either explicit post_action="enter_soft_off" // or the legacy group=="shutdown" fallback (block_reconnect // was set above in that case too). if (do_soft_off || (pg == kPromptShutdown && block_reconnect)) { ESP_LOGI(TAG, "Shutdown-like prompt done, sleeping (WS blocked)"); Board::GetInstance().GetLed()->SetState(LedState::kOff); SetDeviceState(kDeviceStateIdle); } }); } } } else if (strcmp(type->valuestring, "play_local_sequence") == 0) { // Serial playback of multiple local prompts — used for activation // code readout where prompt + digit OGGs are concatenated. // // Payload: {"type":"play_local_sequence","sequence":[{"group":"..."},...]} // Each item may also include "index" (0-based) to pick a specific // file inside the group; omitted means PlayRandom. auto* seq_json = cJSON_GetObjectItem(root, "sequence"); if (cJSON_IsArray(seq_json)) { std::vector> items; bool is_activation = false; cJSON* entry = nullptr; cJSON_ArrayForEach(entry, seq_json) { if (!cJSON_IsObject(entry)) continue; auto* g_json = cJSON_GetObjectItem(entry, "group"); if (!cJSON_IsString(g_json)) continue; PromptGroup pg; if (!LookupPromptGroupByName(g_json->valuestring, &pg)) { ESP_LOGW(TAG, "play_local_sequence: unknown group %s", g_json->valuestring); continue; } if (!audio_prompt_.HasPrompts(pg)) { ESP_LOGW(TAG, "play_local_sequence: group %s has no prompts", g_json->valuestring); continue; } if (pg == kPromptActivationDevice) is_activation = true; int play_index = -1; auto* idx_json = cJSON_GetObjectItem(entry, "index"); if (cJSON_IsNumber(idx_json)) play_index = idx_json->valueint; items.push_back({pg, play_index}); } if (items.empty()) { ESP_LOGW(TAG, "play_local_sequence: empty / invalid sequence"); } else { ESP_LOGI(TAG, "play_local_sequence: %zu item(s)", items.size()); audio_service_.ResetDecoder(); Schedule([this, items]() { RunActivationSequence(items); }); if (is_activation) { // Cache + start 30s replay timer so the user hears the // code repeatedly until activated (or device sleeps). StartActivationReplay(items); } } } } else if (strcmp(type->valuestring, "wifi_config") == 0) { // Server requests device to enter BLE provisioning mode (e.g. device unbound) ESP_LOGI(TAG, "Server requested wifi_config mode, restarting..."); Schedule([this]() { Settings("wifi", true).SetInt("force_ap", 1); vTaskDelay(pdMS_TO_TICKS(500)); esp_restart(); }); } else if (strcmp(type->valuestring, "set_timer") == 0) { auto* dur = cJSON_GetObjectItem(root, "duration"); if (cJSON_IsNumber(dur)) { int seconds = dur->valueint; ESP_LOGI(TAG, "Server requested set_timer: %d seconds", seconds); AddReminderTimer(seconds); } } else if (strcmp(type->valuestring, "cancel_timer") == 0) { auto* scope_json = cJSON_GetObjectItem(root, "scope"); const char* scope = (cJSON_IsString(scope_json)) ? scope_json->valuestring : "all"; ESP_LOGI(TAG, "Server requested cancel_timer scope=%s", scope); if (strcmp(scope, "recent") == 0) { CancelMostRecentReminderTimer(); } else { CancelAllReminderTimers(); } } else if (strcmp(type->valuestring, "set_alarm") == 0) { auto* alarm_obj = cJSON_GetObjectItem(root, "alarm"); if (cJSON_IsObject(alarm_obj)) { AlarmEntry entry = {}; auto* a_id = cJSON_GetObjectItem(alarm_obj, "id"); if (cJSON_IsNumber(a_id)) entry.id = a_id->valueint; auto* a_h = cJSON_GetObjectItem(alarm_obj, "hour"); if (cJSON_IsNumber(a_h)) entry.hour = (uint8_t)a_h->valueint; auto* a_m = cJSON_GetObjectItem(alarm_obj, "minute"); if (cJSON_IsNumber(a_m)) entry.minute = (uint8_t)a_m->valueint; auto* a_r = cJSON_GetObjectItem(alarm_obj, "repeat_mask"); if (cJSON_IsNumber(a_r)) entry.repeat_mask = (uint8_t)a_r->valueint; auto* a_e = cJSON_GetObjectItem(alarm_obj, "enabled"); entry.enabled = cJSON_IsBool(a_e) ? cJSON_IsTrue(a_e) : true; auto* a_fe = cJSON_GetObjectItem(alarm_obj, "fire_epoch"); if (cJSON_IsNumber(a_fe)) entry.fire_epoch = (int64_t)a_fe->valuedouble; auto* a_l = cJSON_GetObjectItem(alarm_obj, "label"); if (cJSON_IsString(a_l)) { strncpy(entry.label, a_l->valuestring, sizeof(entry.label) - 1); } ESP_LOGI(TAG, "set_alarm: id=%d %02d:%02d mask=%d", (int)entry.id, (int)entry.hour, (int)entry.minute, (int)entry.repeat_mask); AddOrUpdateAlarm(entry); } } else if (strcmp(type->valuestring, "delete_alarm") == 0) { auto* a_id = cJSON_GetObjectItem(root, "id"); if (cJSON_IsNumber(a_id)) { ESP_LOGI(TAG, "delete_alarm: id=%d", a_id->valueint); DeleteAlarm(a_id->valueint); } } else if (strcmp(type->valuestring, "sync_alarms") == 0) { auto* arr = cJSON_GetObjectItem(root, "alarms"); if (cJSON_IsArray(arr)) { std::vector entries; int n = cJSON_GetArraySize(arr); for (int i = 0; i < n; i++) { auto* item = cJSON_GetArrayItem(arr, i); if (!cJSON_IsObject(item)) continue; AlarmEntry entry = {}; auto* a_id = cJSON_GetObjectItem(item, "id"); if (cJSON_IsNumber(a_id)) entry.id = a_id->valueint; auto* a_h = cJSON_GetObjectItem(item, "hour"); if (cJSON_IsNumber(a_h)) entry.hour = (uint8_t)a_h->valueint; auto* a_m = cJSON_GetObjectItem(item, "minute"); if (cJSON_IsNumber(a_m)) entry.minute = (uint8_t)a_m->valueint; auto* a_r = cJSON_GetObjectItem(item, "repeat_mask"); if (cJSON_IsNumber(a_r)) entry.repeat_mask = (uint8_t)a_r->valueint; auto* a_e = cJSON_GetObjectItem(item, "enabled"); entry.enabled = cJSON_IsBool(a_e) ? cJSON_IsTrue(a_e) : true; auto* a_fe = cJSON_GetObjectItem(item, "fire_epoch"); if (cJSON_IsNumber(a_fe)) entry.fire_epoch = (int64_t)a_fe->valuedouble; auto* a_l = cJSON_GetObjectItem(item, "label"); if (cJSON_IsString(a_l)) { strncpy(entry.label, a_l->valuestring, sizeof(entry.label) - 1); } entries.push_back(entry); } ESP_LOGI(TAG, "sync_alarms: %d entries", (int)entries.size()); SyncAlarms(entries); // If the new list is empty and an alarm sound is currently // playing, stop it — user explicitly cancelled everything. if (entries.empty() && alarm_reminder_playing_.load()) { audio_service_.ResetDecoder(); ESP_LOGI(TAG, "sync_alarms empty: also stopped in-flight playback"); } } } else if (strcmp(type->valuestring, "alarm_config") == 0) { // Alarm tone selection from server (synced from user's miniprogram settings). // ADR-004 Phase 3: persist to NVS so next boot keeps the same tone even // before the first hello (e.g. offline alarm fires after reboot). auto* set_tone = cJSON_GetObjectItem(root, "set_tone_index"); auto* wake_tone = cJSON_GetObjectItem(root, "wake_tone_index"); Settings alarm_cfg("alarm_cfg", true); if (cJSON_IsNumber(set_tone)) { int v = set_tone->valueint; alarm_set_tone_index_.store(v); alarm_cfg.SetInt("set_idx", v); } if (cJSON_IsNumber(wake_tone)) { int v = wake_tone->valueint; alarm_wake_tone_index_.store(v); alarm_cfg.SetInt("wake_idx", v); } ESP_LOGI(TAG, "alarm_config: set_tone=%d, wake_tone=%d (persisted)", alarm_set_tone_index_.load(), alarm_wake_tone_index_.load()); } else if (strcmp(type->valuestring, "call") == 0) { auto* call_state = cJSON_GetObjectItem(root, "state"); if (!cJSON_IsString(call_state)) return; if (strcmp(call_state->valuestring, "ring") == 0) { // Caller: waiting for callee to answer auto* call_id = cJSON_GetObjectItem(root, "call_id"); if (cJSON_IsString(call_id)) pending_call_id_ = call_id->valuestring; call_active_.store(false); audio_service_.ResetDecoder(); tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); Schedule([this]() { SetDeviceState(kDeviceStateCalling); }); ESP_LOGI(TAG, "Call ring: waiting for callee"); } else if (strcmp(call_state->valuestring, "invite") == 0) { // Callee: incoming call auto* call_id = cJSON_GetObjectItem(root, "call_id"); auto* caller_name = cJSON_GetObjectItem(root, "caller_name"); if (cJSON_IsString(call_id)) pending_call_id_ = call_id->valuestring; call_active_.store(false); audio_service_.ResetDecoder(); tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); Schedule([this]() { SetDeviceState(kDeviceStateRinging); }); ESP_LOGI(TAG, "Incoming call from %s", cJSON_IsString(caller_name) ? caller_name->valuestring : "unknown"); } else if (strcmp(call_state->valuestring, "connected") == 0) { // Call connected — enter full-duplex mode call_active_.store(true); audio_service_.ResetDecoder(); tts_audio_active_.store(false); // ResetDecoder aborts playback by setting playback_cancelled_. // A phone call still needs downlink audio immediately after the // old ring TTS is cleared, so resume output before entering // calling state. audio_service_.BeginNewPlayback(); audio_service_.SetPlaybackHint(false); Schedule([this]() { SetDeviceState(kDeviceStateCalling); }); ESP_LOGI(TAG, "Call connected"); } else if (strcmp(call_state->valuestring, "ended") == 0 || strcmp(call_state->valuestring, "missed") == 0) { // Call ended call_active_.store(false); pending_call_id_.clear(); audio_service_.ResetDecoder(); tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); Schedule([this]() { SetDeviceState(kDeviceStateIdle); }); auto* reason = cJSON_GetObjectItem(root, "reason"); ESP_LOGI(TAG, "Call ended: %s", cJSON_IsString(reason) ? reason->valuestring : "unknown"); } } else if (strcmp(type->valuestring, "memory_sync") == 0) { ESP_LOGI(TAG, "Received memory_sync from server"); MemoryCache::GetInstance().UpdateFromServerSync(root); } else { ESP_LOGW(TAG, "Unknown message type: %s", type->valuestring); } }); protocol_->Start(); SystemInfo::PrintHeapStats(); // Connect WebSocket with retries before giving up SetDeviceState(kDeviceStateConnecting); bool ws_connected = false; for (int attempt = 0; attempt < 3; attempt++) { if (protocol_->OpenAudioChannel()) { ws_connected = true; break; } ESP_LOGW(TAG, "WebSocket connection attempt %d failed, retrying...", attempt + 1); vTaskDelay(pdMS_TO_TICKS(2000)); } if (ws_connected) { ESP_LOGI(TAG, "WebSocket connected, device ready"); SetDeviceState(kDeviceStateIdle); } else { // 设备能走到这里,说明 WiFi 已连且 DHCP 完成(否则 WebSocket 不会尝试)。 // 因此 OpenAudioChannel 失败 = 服务端不可达(404/连接超时/DNS 失败)。 // 优先播放 server_error 提示音,若固件未 seed 则回退到 no_network。 ESP_LOGW(TAG, "WebSocket connection failed after retries → server unreachable"); SetDeviceState(kDeviceStateIdle); // ADR-004 Phase 1: prompt group chosen by server config (NVS) with fallback PromptGroup fail_group = conn_error_config::GetGroupForReason( ConnErrorReason::kServerUnreachable); if (audio_prompt_.HasPrompts(fail_group)) { audio_service_.EnableWakeWordDetection(false); SetDeviceState(kDeviceStateSpeaking); audio_prompt_.PlayLocal(fail_group, audio_service_, protocol_.get(), PromptGroupName(fail_group)); audio_service_.EnableWakeWordDetection(true); SetDeviceState(kDeviceStateIdle); } } // Skip boot sound — server will send play_local welcome after hello // If we restarted because a reminder fired during shutdown, the NVS flag // tells us to play the reminder right after audio is ready. // Load alarms from NVS (timers and alarms only fire while device is ON) LoadAlarmsFromNvs(); ESP_LOGI(TAG, "Device ready (version %s)", ota.GetCurrentVersion().c_str()); } void Application::CheckNewVersion(Ota &ota) { SetDeviceState(kDeviceStateStarting); if (!ota.CheckVersion()) { ESP_LOGW(TAG, "Version check failed, using fallback WebSocket URL"); // OTA 失败时,检查 NVS 中是否已有 WebSocket URL,如果没有则写入默认值 Settings ws_settings("websocket", true); std::string existing_url = ws_settings.GetString("url"); if (existing_url.empty() || IsKnownSavedEndpoint(existing_url)) { ws_settings.SetString("url", kDevelopmentWebSocketUrl); ws_settings.SetInt("version", 3); ESP_LOGI(TAG, "Set fallback WebSocket URL: %s", kDevelopmentWebSocketUrl); } else { ESP_LOGI(TAG, "Using existing WebSocket URL: %s", existing_url.c_str()); } return; } ota.MarkCurrentVersionValid(); // Decide if OTA upgrade is needed (actual upgrade happens after WS connect for TTS) pending_ota_ = nullptr; pending_ota_reason_.clear(); if (ota.IsAutoUpgradeType()) { ESP_LOGI(TAG, "Auto-upgrade: %s -> %s", ota.GetCurrentVersion().c_str(), ota.GetNewVersion().c_str()); pending_ota_ = std::make_unique(std::move(ota)); pending_ota_reason_ = "auto"; } else if (ota.IsForceUpgradeType()) { ESP_LOGI(TAG, "Force-upgrade (incompatible versions): %s -> %s", ota.GetCurrentVersion().c_str(), ota.GetNewVersion().c_str()); pending_ota_ = std::make_unique(std::move(ota)); pending_ota_reason_ = "force"; } else if (ota.IsOptionalUpgradeType()) { ESP_LOGI(TAG, "Optional upgrade available but skipped (not auto, all compatible): %s -> %s", ota.GetCurrentVersion().c_str(), ota.GetNewVersion().c_str()); // Don't set pending_ota_, enter normal use directly } else if (ota.HasNewVersion()) { ESP_LOGI(TAG, "New firmware available but not upgrading: %s (auto_update=%d, force=%d)", ota.GetNewVersion().c_str(), ota.IsAutoUpdate(), ota.IsForceUpgrade()); } } // === 主事件循环 === void Application::MainEventLoop() { while (true) { auto bits = xEventGroupWaitBits(event_group_, MAIN_EVENT_SCHEDULE | MAIN_EVENT_SEND_AUDIO | MAIN_EVENT_ERROR | MAIN_EVENT_CLOCK_TICK | MAIN_EVENT_STATUS_TICK | MAIN_EVENT_WAKE_WORD, pdTRUE, pdFALSE, portMAX_DELAY); if (bits & MAIN_EVENT_ERROR) { SetDeviceState(kDeviceStateIdle); ESP_LOGE(TAG, "Error: %s", last_error_message_.c_str()); } if (bits & MAIN_EVENT_SEND_AUDIO) { // while (auto packet = audio_service_.PopPacketFromSendQueue()) // { // ESP_LOGI(TAG, "[Audio] Sending %zu bytes", packet->payload.size()); // if (protocol_ && !protocol_->SendAudio(std::move(packet))) // { // break; // } // } // 2026-6-25 ckkj debug constexpr size_t kMaxSendPerTick = 20; // 单次最多发20包,强制让出循环 size_t sent = 0; while (sent < kMaxSendPerTick) { auto packet = audio_service_.PopPacketFromSendQueue(); if (!packet) break; // ESP_LOGI(TAG, "[Audio] Sending %zu bytes", packet->payload.size()); if (!protocol_ || !protocol_->SendAudio(std::move(packet))) { break; } sent++; } // ESP_LOGI(TAG, "[AudioTick] send count this tick: %zu", sent); } if (bits & MAIN_EVENT_SCHEDULE) { std::deque> tasks; { std::lock_guard lock(mutex_); tasks = std::move(main_tasks_); } for (auto &task : tasks) { task(); } } if (bits & MAIN_EVENT_STATUS_TICK) { SendStatusUpdate(); } if (bits & MAIN_EVENT_CLOCK_TICK) { // Reminder timer check (active mode). When in soft-off, the // shutdown loop in borla_s3_board polls IsReminderDue() instead. if (IsReminderDue() && device_state_ != kDeviceStateSpeaking) { ESP_LOGI(TAG, "Reminder due (active mode), playing reminder"); PlayReminderSound(); } // Alarm clock check (absolute time, independent of reminder timers) if (IsAlarmDue() && device_state_ != kDeviceStateSpeaking) { ESP_LOGI(TAG, "Alarm due (active mode), handling alarm/wake"); PlayAlarmSound(); } // WebSocket heartbeat — ping every 1s, kill dead channel after // 20s silence (see protocols/websocket_protocol.md §心跳). if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendHeartbeat(); //if (protocol_->HeartbeatTimedOut())//2026-6-30 ckkj debug在播放期间暂停心跳超时检测,避免因播放导致的误断连 if (!tts_audio_active_.load() && protocol_->HeartbeatTimedOut()) { ESP_LOGW(TAG, "[HB] no incoming for >20s, tearing down dead WS"); protocol_->CloseAudioChannel(); } } // Periodic battery sample (every 10s). GetBatteryLevel() itself // logs a full diagnostic line inside borla_s3_board.cc — we just // need to trigger it on a fixed cadence. static int battery_log_counter = 0; if (++battery_log_counter >= 10) { battery_log_counter = 0; Board::GetInstance().GetBatteryLevel(); } // Low-battery check: every 10 minutes, OR right after entering // idle for the first time when boot detected ≤20% (so the warning // doesn't collide with boot prompt / welcome). Charging devices // are skipped inside CheckLowBatteryPeriodic. static int low_batt_counter = 0; constexpr int kLowBattCheckIntervalTicks = 600; // 10 min @ 1 tick/s bool low_batt_due = (++low_batt_counter >= kLowBattCheckIntervalTicks); bool low_batt_at_boot = pending_low_battery_warning_at_boot_ && device_state_ == kDeviceStateIdle; if (low_batt_due || low_batt_at_boot) { low_batt_counter = 0; pending_low_battery_warning_at_boot_ = false; CheckLowBatteryPeriodic(); } } if (bits & MAIN_EVENT_WAKE_WORD) { ESP_LOGI(TAG, "Wake word detected in state: %s", STATE_STRINGS[device_state_]); if (device_state_ == kDeviceStateIdle) { IdleWatchdogWakeFromIdleSleeping(); // 唤醒应答:先进入 Listening 状态,再播放 "我在。"(OGG)。 // 这样设备在播放唤醒响应时仍保持 listening 状态,用户可以立即说话。 bool suppress = suppress_next_wake_response_.exchange(false); if (suppress) { ESP_LOGI(TAG, "Wake response suppressed (post-welcome)"); ToggleChatState(); } else { // 先进入 listening 状态 ToggleChatState(); // 在 listening 状态下播放唤醒响应(不阻塞,不发送 play_local 消息) if (audio_prompt_.HasPrompts(kPromptWakeResponse)) { audio_prompt_.PlayRandom(kPromptWakeResponse, audio_service_); } } } else if (device_state_ == kDeviceStateSpeaking) { // Interrupt current playback and start new conversation. // ResetDecoder drops any queued local OGG frames (alarm / reminder / // story boot prompt), so WaitForPlaybackComplete returns promptly // instead of blocking for the full prompt duration. audio_service_.ResetDecoder(); // 2026-6-24 ckkj debug 取消 TTS 超时定时器 CancelTtsTimeoutTimer(); AbortSpeaking(kAbortReasonWakeWordDetected); // 2026-6-23 ckkj debug 直接重置 listening 状态,避免通过 ToggleChatState 引入额外延迟 // ToggleChatState(); Schedule([this]() { SetListeningMode(kListeningModeAutoStop); }); } else if (device_state_ == kDeviceStateListening) { // Already listening, just reset the listening mode AbortSpeaking(kAbortReasonWakeWordDetected); // 2026-6-23 ckkj debug 直接重置 listening 状态,避免通过 ToggleChatState 引入额外延迟 // ToggleChatState(); Schedule([this]() { SetListeningMode(kListeningModeAutoStop); }); } } } } void Application::Schedule(std::function callback) { { std::lock_guard lock(mutex_); main_tasks_.push_back(std::move(callback)); } xEventGroupSetBits(event_group_, MAIN_EVENT_SCHEDULE); } void Application::SendTextMessage(const std::string &text) { Schedule([this, text]() { if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendText(text); } }); } // === Reminder timers (multi) === // // Multiple one-shot wake-up reminders. The user says "30 minutes later wake me up", // server detects the intent and sends {"type":"set_timer","duration":N}. // // Multiple timers can coexist; they are stored sorted ascending by target_us. // Cancel scopes: // - "all" → clear the entire list ("取消所有计时器") // - "recent" → drop the next-to-fire one ("取消最近的计时器") // Wake word during ringing aborts playback via the existing abort path; the // timer is already removed before playback so it does not re-fire. void Application::AddReminderTimer(int seconds) { if (seconds <= 0) return; int64_t target_us = esp_timer_get_time() + (int64_t)seconds * 1000000LL; { std::lock_guard lock(reminder_mutex_); // Insert sorted ascending so the next-to-fire is at the front auto it = std::lower_bound(reminder_targets_us_.begin(), reminder_targets_us_.end(), target_us); reminder_targets_us_.insert(it, target_us); } ESP_LOGI(TAG, "Reminder added: %d seconds (target_us=%lld), total=%d", seconds, target_us, GetReminderCount()); // Note: confirmation OGG (闹钟_设定提示音) is triggered by server via play_local("alarm_set") } void Application::CancelAllReminderTimers() { int count; { std::lock_guard lock(reminder_mutex_); count = (int)reminder_targets_us_.size(); reminder_targets_us_.clear(); } Settings("reminder", true).SetInt("pending", 0); // Also stop any reminder sound currently playing — user just asked to // cancel, so we shouldn't keep ringing. if (alarm_reminder_playing_.load()) { audio_service_.ResetDecoder(); ESP_LOGI(TAG, "Cancelled all reminders: also stopped in-flight playback"); } ESP_LOGI(TAG, "Cancelled all reminders (%d removed)", count); } void Application::CancelMostRecentReminderTimer() { bool removed = false; int remaining; { std::lock_guard lock(reminder_mutex_); if (!reminder_targets_us_.empty()) { // The "next to fire" = smallest target_us = front of the sorted list reminder_targets_us_.erase(reminder_targets_us_.begin()); removed = true; } remaining = (int)reminder_targets_us_.size(); } ESP_LOGI(TAG, "Cancel most-recent reminder: removed=%d, remaining=%d", removed ? 1 : 0, remaining); } bool Application::IsReminderDue() const { std::lock_guard lock(reminder_mutex_); if (reminder_targets_us_.empty()) return false; return esp_timer_get_time() >= reminder_targets_us_.front(); } int Application::GetReminderCount() const { std::lock_guard lock(reminder_mutex_); return (int)reminder_targets_us_.size(); } void Application::PlayAlarmLoop(PromptGroup pg, int wake_idx, const char *group_name, int loop_duration_ms) { constexpr int kInterRingGapMs = 1000; const int64_t deadline_us = esp_timer_get_time() + (int64_t)loop_duration_ms * 1000; int iter = 0; bool cancelled = false; while (esp_timer_get_time() < deadline_us) { iter++; // Each PlayLocal* internally calls ResetDecoder + (synchronous) // BeginNewPlayback, so the cancel flag is reset at the start of every // iteration. PlayTask is async — frame pushing starts within ~tens of ms. if (wake_idx >= 0) { audio_prompt_.PlayLocalByIndex(pg, wake_idx, audio_service_, protocol_.get(), group_name); } else { audio_prompt_.PlayLocal(pg, audio_service_, protocol_.get(), group_name); } // Give async PlayTask time to start pushing frames so // WaitForPlaybackComplete doesn't return on initially-empty queue. vTaskDelay(pdMS_TO_TICKS(400)); // Single ring is ~1s; cap wait at 5s as safety net. audio_service_.WaitForPlaybackComplete(5000); // After wait: cancelled=true means wake word fired during this ring. if (audio_service_.IsPlaybackCancelled()) { cancelled = true; ESP_LOGI(TAG, "PlayAlarmLoop[%s] cancelled by wake word at iter=%d", group_name, iter); break; } // Inter-ring gap, also cancellation-aware so wake word during silence // works. Bail early when overall deadline is reached. const int64_t gap_end_us = esp_timer_get_time() + (int64_t)kInterRingGapMs * 1000; while (esp_timer_get_time() < gap_end_us && esp_timer_get_time() < deadline_us) { if (audio_service_.IsPlaybackCancelled()) { cancelled = true; break; } vTaskDelay(pdMS_TO_TICKS(50)); } if (cancelled) { ESP_LOGI(TAG, "PlayAlarmLoop[%s] cancelled during gap at iter=%d", group_name, iter); break; } } if (!cancelled) { ESP_LOGI(TAG, "PlayAlarmLoop[%s] completed %d iterations", group_name, iter); } audio_prompt_.NotifyLocalDone(protocol_.get(), group_name); } // Heap-allocated handoff to AlarmPlaybackTask. group_name is owned (std::string) // because the original `const char*` may come from PromptGroupName() returning // a literal that's safe across tasks, but copying defends against future churn. struct AlarmPlaybackParams { Application *self; PromptGroup pg; int wake_idx; std::string group_name; }; void Application::AlarmPlaybackTask(void *arg) { auto *p = static_cast(arg); auto *self = p->self; // 60-second loop. PlayLocal* / audio_service all use atomic+mutex internally; // protocol_->SendText (NotifyLocalDone) goes through WebSocket's send_mutex_. // No cross-task hazard. self->PlayAlarmLoop(p->pg, p->wake_idx, p->group_name.c_str(), 60 * 1000); // Teardown back on the main event loop: // - device_state_ is plain (non-atomic); writing it from this task races // against MainEventLoop's wake-word handler that may already have // transitioned us to listening/connecting. // - SetDeviceState also calls protocol_->SendStartListening (when going // to listening), which we want to keep on the main event-loop owner. self->Schedule([self]() { self->tts_audio_active_.store(false); self->audio_service_.SetPlaybackHint(false); if (self->device_state_ == kDeviceStateSpeaking) { self->SetDeviceState(kDeviceStateIdle); } self->alarm_reminder_playing_.store(false); }); delete p; vTaskDelete(nullptr); } void Application::PlayReminderSound() { // Pop ALL due timers in one batch so simultaneously-due timers ring once. int popped = 0; { std::lock_guard lock(reminder_mutex_); int64_t now = esp_timer_get_time(); while (!reminder_targets_us_.empty() && reminder_targets_us_.front() <= now) { reminder_targets_us_.erase(reminder_targets_us_.begin()); popped++; } } if (popped == 0) { // Called without any due timers (e.g., from boot pending flag) popped = 1; } Schedule([this, popped]() { ESP_LOGI(TAG, "Playing reminder sound (popped %d due timers)", popped); // Mutex: if another reminder/alarm is already playing (e.g. two timers // fired 1s apart), skip audio to avoid overlapping playback. Timers are // already dequeued so they still count as "fired" for the user. if (alarm_reminder_playing_.exchange(true)) { ESP_LOGW(TAG, "Reminder sound suppressed (another already playing)"); return; } // Use alarm_wake OGG as the reminder sound, fallback to welcome PromptGroup reminder_pg = audio_prompt_.HasPrompts(kPromptAlarmWake) ? kPromptAlarmWake : kPromptWelcome; if (audio_prompt_.HasPrompts(reminder_pg)) { // Keep wake word ON so user can interrupt the reminder loop. // Wake word handler calls ResetDecoder which both drains the // playback queue and sets playback_cancelled_, which PlayAlarmLoop // polls between rings to break out early. audio_service_.EnableWakeWordDetection(true); tts_audio_active_.store(true); if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendAbortSpeaking(kAbortReasonNone); } // ResetDecoder before SetPlaybackHint — Reset sets cancel=true, // SetPlaybackHint(true) must follow to clear it (otherwise the // alarm prompt's first frames get dropped at I2S write). audio_service_.ResetDecoder(); // clear any residual TTS frames audio_service_.SetPlaybackHint(true); SetDeviceState(kDeviceStateSpeaking); int wake_idx = alarm_wake_tone_index_.load(); const char* group_name = PromptGroupName(reminder_pg); // Run the 60s loop in a dedicated task so MainEventLoop stays // responsive (wake word, button, network). Teardown // (tts_audio_active_, SetPlaybackHint, SetDeviceState, // alarm_reminder_playing_) is dispatched back via Schedule() // inside the task — see AlarmPlaybackTask. auto* params = new AlarmPlaybackParams{ this, reminder_pg, wake_idx, group_name}; xTaskCreate(AlarmPlaybackTask, "alarm_play", 4096, params, 3, nullptr); // alarm_reminder_playing_ is released by the task's teardown lambda. } else { // No prompts → release mutex immediately, nothing to play. alarm_reminder_playing_.store(false); } }); } // === Alarm clock (absolute time, independent of reminder timers) === void Application::LoadAlarmsFromNvs() { Settings s("alarm", true); int count = s.GetInt("count"); if (count <= 0) { EnsureBuiltInFirstDayPromptAlarm(); return; } if (count > kMaxAlarms) count = kMaxAlarms; std::string blob = s.GetString("list"); if (blob.size() < (size_t)(count * sizeof(AlarmEntry))) { ESP_LOGW(TAG, "Alarm NVS blob too small, ignoring"); EnsureBuiltInFirstDayPromptAlarm(); return; } { std::lock_guard lock(alarm_mutex_); alarms_.resize(count); memcpy(alarms_.data(), blob.data(), count * sizeof(AlarmEntry)); } ESP_LOGI(TAG, "Loaded %d alarms from NVS", count); EnsureBuiltInFirstDayPromptAlarm(); } void Application::SaveAlarmsToNvs() { Settings s("alarm", true); std::lock_guard lock(alarm_mutex_); int count = (int)alarms_.size(); s.SetInt("count", count); if (count > 0) { std::string blob((const char *)alarms_.data(), count * sizeof(AlarmEntry)); s.SetString("list", blob); } ESP_LOGI(TAG, "Saved %d alarms to NVS", count); } void Application::AddOrUpdateAlarm(const AlarmEntry &entry) { { std::lock_guard lock(alarm_mutex_); // Update if exists for (auto &a : alarms_) { if (a.id == entry.id) { a = entry; goto done; } } if ((int)alarms_.size() >= kMaxAlarms) { ESP_LOGW(TAG, "Max alarms reached (%d), ignoring", kMaxAlarms); return; } alarms_.push_back(entry); } done: SaveAlarmsToNvs(); } void Application::EnsureBuiltInFirstDayPromptAlarm() { Settings s("alarm", true); if (s.GetInt("first_day_prompt_consumed", 0) == 1) { bool removed = false; { std::lock_guard lock(alarm_mutex_); auto old_size = alarms_.size(); alarms_.erase( std::remove_if(alarms_.begin(), alarms_.end(), [this](const AlarmEntry &a) { return IsWakeOnlyAlarm(a); }), alarms_.end()); removed = alarms_.size() != old_size; } if (removed) { ESP_LOGI(TAG, "Removed stale first-day wake alarm after consumed"); SaveAlarmsToNvs(); } return; } AlarmEntry builtin{}; builtin.id = kBuiltInFirstDayPromptAlarmId; builtin.hour = kBuiltInFirstDayPromptHour; builtin.minute = kBuiltInFirstDayPromptMinute; builtin.repeat_mask = kBuiltInFirstDayPromptRepeatMask; builtin.enabled = true; builtin.fire_epoch = 0; strncpy(builtin.label, kBuiltInFirstDayPromptLabel, sizeof(builtin.label) - 1); bool changed = false; bool found = false; { std::lock_guard lock(alarm_mutex_); for (auto &a : alarms_) { if (a.id == kBuiltInFirstDayPromptAlarmId || strcmp(a.label, kBuiltInFirstDayPromptLabel) == 0) { if (a.id != builtin.id || a.hour != builtin.hour || a.minute != builtin.minute || a.repeat_mask != builtin.repeat_mask || a.enabled != builtin.enabled || a.fire_epoch != builtin.fire_epoch || strcmp(a.label, builtin.label) != 0) { a = builtin; changed = true; } found = true; break; } } if (!found && (int)alarms_.size() >= kMaxAlarms) { ESP_LOGW(TAG, "Cannot add built-in first-day alarm: max alarms reached"); return; } if (!found) { alarms_.push_back(builtin); changed = true; } } if (changed) { ESP_LOGI(TAG, "Ensured built-in first-day alarm at %02d:%02d", kBuiltInFirstDayPromptHour, kBuiltInFirstDayPromptMinute); SaveAlarmsToNvs(); } } void Application::DisableBuiltInFirstDayPromptAlarm() { Settings s("alarm", true); s.SetInt("first_day_prompt_consumed", 1); bool removed = false; { std::lock_guard lock(alarm_mutex_); auto old_size = alarms_.size(); alarms_.erase( std::remove_if(alarms_.begin(), alarms_.end(), [this](const AlarmEntry &a) { return IsWakeOnlyAlarm(a); }), alarms_.end()); removed = alarms_.size() != old_size; } ESP_LOGI(TAG, "Disabled built-in first-day wake alarm%s", removed ? " and removed stale entry" : ""); SaveAlarmsToNvs(); } void Application::DeleteAlarm(int32_t id) { if (id == kBuiltInFirstDayPromptAlarmId) { DisableBuiltInFirstDayPromptAlarm(); return; } { std::lock_guard lock(alarm_mutex_); alarms_.erase( std::remove_if(alarms_.begin(), alarms_.end(), [id](const AlarmEntry &a) { return a.id == id; }), alarms_.end()); } SaveAlarmsToNvs(); } void Application::SyncAlarms(const std::vector &entries) { { std::lock_guard lock(alarm_mutex_); alarms_ = entries; if ((int)alarms_.size() > kMaxAlarms) { alarms_.resize(kMaxAlarms); } } EnsureBuiltInFirstDayPromptAlarm(); SaveAlarmsToNvs(); } void Application::ClearAllAlarms() { { std::lock_guard lock(alarm_mutex_); alarms_.clear(); } EnsureBuiltInFirstDayPromptAlarm(); SaveAlarmsToNvs(); } bool Application::IsWakeOnlyAlarm(const AlarmEntry &entry) const { return entry.id == kBuiltInFirstDayPromptAlarmId || strcmp(entry.label, kBuiltInFirstDayPromptLabel) == 0 || strcmp(entry.label, kServerFirstDayPromptLabel) == 0; } bool Application::IsAlarmDue() const { time_t now_epoch = time(nullptr); if (now_epoch < 1700000000) return false; // Clock not synced yet struct tm tm_now; localtime_r(&now_epoch, &tm_now); int cur_hour = tm_now.tm_hour; int cur_min = tm_now.tm_min; int cur_wday = tm_now.tm_wday; // 0=Sun, 1=Mon, ..., 6=Sat // Deduplicate: don't fire again within the same minute int minute_id = cur_hour * 60 + cur_min; if (minute_id == alarm_last_fired_minute_) return false; std::lock_guard lock(alarm_mutex_); for (const auto &a : alarms_) { if (!a.enabled) continue; if (a.hour != cur_hour || a.minute != cur_min) continue; if (a.repeat_mask == 0) { // One-shot: check fire_epoch date matches today if (a.fire_epoch > 0) { struct tm tm_fire; time_t fe = (time_t)a.fire_epoch; localtime_r(&fe, &tm_fire); if (tm_fire.tm_year != tm_now.tm_year || tm_fire.tm_yday != tm_now.tm_yday) { continue; } } return true; } else { // Repeating: check weekday bitmask if (a.repeat_mask & (1 << cur_wday)) { return true; } } } return false; } int Application::GetAlarmCount() const { std::lock_guard lock(alarm_mutex_); return (int)alarms_.size(); } void Application::PlayAlarmSound() { // Collect fired alarm IDs and record minute to prevent re-fire std::vector audio_fired_ids; std::vector notify_fired_ids; bool wake_only_fired = false; { time_t now_epoch = time(nullptr); struct tm tm_now; localtime_r(&now_epoch, &tm_now); alarm_last_fired_minute_ = tm_now.tm_hour * 60 + tm_now.tm_min; std::lock_guard lock(alarm_mutex_); int cur_wday = tm_now.tm_wday; for (const auto &a : alarms_) { if (!a.enabled) continue; if (a.hour != tm_now.tm_hour || a.minute != tm_now.tm_min) continue; if (a.repeat_mask == 0 || (a.repeat_mask & (1 << cur_wday))) { if (a.id > 0) { notify_fired_ids.push_back(a.id); } if (IsWakeOnlyAlarm(a)) { wake_only_fired = true; } else { audio_fired_ids.push_back(a.id); } } } } Schedule([this, audio_fired_ids, notify_fired_ids, wake_only_fired]() { if (audio_fired_ids.empty() && wake_only_fired) { ESP_LOGI(TAG, "Wake-only first-day alarm fired, skip alarm sound"); DisableBuiltInFirstDayPromptAlarm(); if (device_state_ == kDeviceStateSpeaking) { SetDeviceState(kDeviceStateIdle); } for (int32_t aid : notify_fired_ids) { char buf[128]; snprintf(buf, sizeof(buf), "{\"type\":\"alarm_fired\",\"id\":%d,\"fired_at\":%lld}", (int)aid, (long long)time(nullptr)); if (protocol_) { protocol_->SendText(std::string(buf)); } } return; } ESP_LOGI(TAG, "Playing alarm sound (%d alarms fired)", (int)audio_fired_ids.size()); // Mutex shared with PlayReminderSound — see its comment. bool already_playing = alarm_reminder_playing_.exchange(true); // Use alarm_wake OGG, fallback to welcome PromptGroup alarm_pg = audio_prompt_.HasPrompts(kPromptAlarmWake) ? kPromptAlarmWake : kPromptWelcome; if (!already_playing && audio_prompt_.HasPrompts(alarm_pg)) { // Keep wake word ON so user can interrupt the alarm loop. // Wake word handler calls ResetDecoder which sets playback_cancelled_, // which PlayAlarmLoop polls between rings to break out early. audio_service_.EnableWakeWordDetection(true); tts_audio_active_.store(true); if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendAbortSpeaking(kAbortReasonNone); } // ResetDecoder before SetPlaybackHint — Reset sets cancel=true, // SetPlaybackHint(true) must follow to clear it (otherwise the // alarm prompt's first frames get dropped at I2S write). audio_service_.ResetDecoder(); // clear any residual TTS frames audio_service_.SetPlaybackHint(true); SetDeviceState(kDeviceStateSpeaking); int wake_idx2 = alarm_wake_tone_index_.load(); const char* group_name = PromptGroupName(alarm_pg); // Run 60s loop in dedicated task so MainEventLoop stays responsive // (wake word, button, network). Teardown is dispatched back via // Schedule() inside the task — see AlarmPlaybackTask. // alarm_reminder_playing_ is released by the task's teardown lambda. auto* params = new AlarmPlaybackParams{ this, alarm_pg, wake_idx2, group_name}; xTaskCreate(AlarmPlaybackTask, "alarm_play", 4096, params, 3, nullptr); } else if (already_playing) { ESP_LOGW(TAG, "Alarm sound suppressed (another already playing)"); } else { // Already-not-playing but no prompts — release mutex immediately. alarm_reminder_playing_.store(false); } // Notify server of each fired alarm (for one-shot auto-disable) for (int32_t aid : notify_fired_ids) { char buf[128]; snprintf(buf, sizeof(buf), "{\"type\":\"alarm_fired\",\"id\":%d,\"fired_at\":%lld}", (int)aid, (long long)time(nullptr)); if (protocol_) { protocol_->SendText(std::string(buf)); } } }); } // === 状态管理 === void Application::SetDeviceState(DeviceState state) { if (device_state_ == state) return; // 2026-6-24 ckkj debug 解决人声识别不完全就开始应答 if (device_state_ == kDeviceStateListening && state == kDeviceStateSpeaking) { int64_t elapsed = (esp_timer_get_time() / 1000) - listening_start_ms_; if (elapsed < kMinListeningDurationMs) { ESP_LOGW(TAG, "Ignoring premature speaking state change: only %lldms elapsed, need %lldms", (long long)elapsed, (long long)kMinListeningDurationMs); // Schedule a delayed state change if still in listening after the minimum duration auto delay_ms = kMinListeningDurationMs - elapsed; ESP_LOGI(TAG, "Scheduling delayed speaking state change in %lldms", (long long)delay_ms); // 2026-6-30 ckkj debug 复用成员 timer,状态变化时取消,避免延迟触发错误切换 if (!speaking_delay_timer_) { esp_timer_create_args_t timer_args = { .callback = [](void *arg) { Application *app = reinterpret_cast(arg); app->Schedule([app]() { // 2026-6-30 ckkj debug 延迟切换前再次确认仍有活跃 TTS, // 防止 TTS STOP 已取消 timer 但 lambda 仍在队列中导致误切 if (app->device_state_ == kDeviceStateListening && app->tts_audio_active_.load()) { app->SetDeviceState(kDeviceStateSpeaking); } }); }, .arg = this, .name = "listening_delay"}; esp_timer_create(&timer_args, &speaking_delay_timer_); } esp_timer_stop(speaking_delay_timer_); esp_timer_start_once(speaking_delay_timer_, delay_ms * 1000); return; } } // 状态要离开 listening 时,取消未触发的延迟 speaking 切换 if (device_state_ == kDeviceStateListening && state != kDeviceStateSpeaking) { CancelSpeakingDelayTimer(); } // debug end device_state_ = state; ESP_LOGI(TAG, "STATE: %s", STATE_STRINGS[state]); auto &board = Board::GetInstance(); auto *led = board.GetLed(); // Any non-call state must tear down AEC+NS+AGC to release memory and // Note: kDeviceStateListening also needs AEC/NS/AGC for proper voice recognition if (state != kDeviceStateRinging && state != kDeviceStateCalling && state != kDeviceStateListening) { audio_service_.EnableCallMode(false); } audio_service_.EnableEnergyVad(false);//kDeviceStateIdle,kDeviceStateConnecting,kDeviceStateListening switch (state) { case kDeviceStateIdle: audio_service_.EnableVoiceProcessing(false); audio_service_.EnableWakeWordDetection(true); led->SetState(LedState::kIdle); break; case kDeviceStateConnecting: audio_service_.EnableVoiceProcessing(false); audio_service_.EnableWakeWordDetection(false); led->SetState(LedState::kConnecting); break; case kDeviceStateListening: audio_service_.EnableWakeWordDetection(false); protocol_->SendStartListening(listening_mode_); audio_service_.EnableVoiceProcessing(true); // Explicitly leave barge-in mode when starting to listen. Previously // it could stay enabled for ~395 ms after TTS ended and starve the // audio task with heavy NS FFT processing. audio_service_.EnableBargeInMode(false); led->SetState(LedState::kListening); // 2026-6-24 记录监听开始时间 listening_start_ms_ = esp_timer_get_time() / 1000; break; case kDeviceStateSpeaking: ESP_LOGI(TAG, "[State] Entering speaking state, barge_in=%d, listening_mode=%d", audio_service_.IsBargeInModeEnabled(), listening_mode_); // 2026-6-23 ckkj debug // if (listening_mode_ != kListeningModeRealtime && // !audio_service_.IsBargeInModeEnabled()) // { // audio_service_.EnableVoiceProcessing(false); // } // else // { // audio_service_.EnableVoiceProcessing(true); // } // // Disable wake word during audio playback to prevent // // false triggering from playback audio or environmental noise // if (audio_service_.IsIdle()) { // // Server controls wake word via {"type":"control","action":"wake_word"} // // so user can interrupt TTS with wake word // } else { // audio_service_.EnableWakeWordDetection(false); // } // 启用唤醒词检测,允许用户用唤醒词打断播放 // audio_service_.EnableWakeWordDetection(true); // 保持语音处理开启,以便唤醒词检测使用 AEC 处理后的数据 // 这样可以消除扬声器播放的回声,防止误触发 audio_service_.EnableWakeWordDetection(false); // 防止唤醒词打断播放 audio_service_.EnableVoiceProcessing(true); audio_service_.EnableBargeInMode(true); // 2026-6-26 ckkj debug modify false-->true audio_service_.EnableEnergyVad(true); // 启用能量 VAD 用于打断播放 ESP_LOGI(TAG, " speaking......"); led->SetState(LedState::kSpeaking); break; case kDeviceStateRinging: audio_service_.EnableVoiceProcessing(true); // Mic on for accept detection audio_service_.EnableWakeWordDetection(false); audio_service_.EnableCallMode(true); // AEC+NS+AGC on mic path led->SetState(LedState::kRinging); break; case kDeviceStateCalling: audio_service_.EnableVoiceProcessing(true); // Mic on for call audio audio_service_.EnableWakeWordDetection(false); audio_service_.SetPlaybackHint(false); // Allow simultaneous encode+decode audio_service_.EnableCallMode(true); // Ensure AEC enabled (safe on transition) led->SetState(LedState::kCalling); break; case kDeviceStateUpgrading: audio_service_.EnableVoiceProcessing(false); audio_service_.EnableWakeWordDetection(false); led->SetState(LedState::kUpgrading); break; case kDeviceStateWifiConfiguring: led->SetState(LedState::kWifiConfig); break; default: break; } // === IdleWatchdog hook === if (idle_watchdog_internal_state_change_.load()) { ESP_LOGI(TAG, "[IdleWdg] internal state change to %s: skip watchdog reset hook", STATE_STRINGS[state]); return; } // Idle: start (or restart) the 60s/180s countdown. // Active interaction states: also reset so any prior watchdog timing dies. // Upgrading / WifiConfiguring: stop watchdog entirely. // Connecting: leave whatever is running (pre-connect → inactive; reconnect // mid-watchdog → wait for OnAudioChannelOpened to re-arm). switch (state) { case kDeviceStateIdle: case kDeviceStateListening: case kDeviceStateSpeaking: case kDeviceStateRinging: case kDeviceStateCalling: IdleWatchdogReset(); break; case kDeviceStateUpgrading: case kDeviceStateWifiConfiguring: IdleWatchdogStop(); break; default: break; } } // === 对话控制 === void Application::SetDeviceStateForIdleWatchdog(DeviceState state) { bool previous = idle_watchdog_internal_state_change_.exchange(true); SetDeviceState(state); idle_watchdog_internal_state_change_.store(previous); } void Application::ToggleChatState() { if (!protocol_) return; // Wake from voice-command sleep (shutting_down_ without light sleep) if (shutting_down_.load()) { ESP_LOGI(TAG, "Waking from sleep mode (button/wake word)"); shutting_down_.store(false); } if (device_state_ == kDeviceStateIdle) { Schedule([this]() { // Reconnect if WebSocket dropped if (!protocol_->IsAudioChannelOpened()) { SetDeviceState(kDeviceStateConnecting); if (!protocol_->OpenAudioChannel()) { ESP_LOGW(TAG, "Wake reconnect failed → server unreachable"); SetDeviceState(kDeviceStateIdle); // ADR-004 Phase 1: prompt group chosen by server config (NVS) with fallback PromptGroup fail_group = conn_error_config::GetGroupForReason( ConnErrorReason::kServerUnreachable); if (audio_prompt_.HasPrompts(fail_group)) { SetDeviceState(kDeviceStateSpeaking); // PlayLocal: WS is down → no signal sent, just plays local audio_prompt_.PlayLocal(fail_group, audio_service_, protocol_.get(), PromptGroupName(fail_group)); SetDeviceState(kDeviceStateIdle); } return; } } SetListeningMode(kListeningModeAutoStop); }); } else if (device_state_ == kDeviceStateSpeaking) { // Schedule([this]() // { // AbortSpeaking(kAbortReasonNone); // SetListeningMode(kListeningModeAutoStop); }); // audio_service_.ResetDecoder(); // 2026-6-25 ckkj debug CancelTtsTimeoutTimer(); // 全部异步,主线立刻释放 Schedule([this]() { AbortSpeaking(kAbortReasonWakeWordDetected); SetListeningMode(kListeningModeAutoStop); }); } else if (device_state_ == kDeviceStateListening) { Schedule([this]() { // Stop listening but keep WebSocket connected (don't close channel) audio_service_.EnableVoiceProcessing(false); audio_service_.EnableWakeWordDetection(true); SetDeviceState(kDeviceStateIdle); }); } else if (device_state_ == kDeviceStateRinging) { // Accept incoming call via button press Schedule([this]() { if (!pending_call_id_.empty() && protocol_) { char buf[256]; snprintf(buf, sizeof(buf), "{\"type\":\"call\",\"state\":\"accept\",\"call_id\":\"%s\"}", pending_call_id_.c_str()); protocol_->SendText(buf); ESP_LOGI(TAG, "Call accepted via button"); } }); } else if (device_state_ == kDeviceStateCalling) { // Hang up via button press Schedule([this]() { if (protocol_) { char buf[256]; snprintf(buf, sizeof(buf), "{\"type\":\"call\",\"state\":\"hangup\",\"call_id\":\"%s\"}", pending_call_id_.c_str()); protocol_->SendText(buf); ESP_LOGI(TAG, "Call hangup via button"); } }); } } void Application::NotifyNetworkStateChanged(bool ready) { int64_t uptime_ms = esp_timer_get_time() / 1000; bool ws_open = protocol_ ? protocol_->IsAudioChannelOpened() : false; ESP_LOGI(TAG, "[4G] NotifyNetworkStateChanged(ready=%d) entered at uptime=%lldms | device_state=%d ws_open=%d shutting_down=%d was_down=%d", ready ? 1 : 0, uptime_ms, static_cast(device_state_), ws_open ? 1 : 0, shutting_down_.load() ? 1 : 0, network_was_down_.load() ? 1 : 0); if (!ready) { network_was_down_.store(true); ESP_LOGW(TAG, "[4G] network_was_down_ latched → will trigger reconnect on next ready edge"); Schedule([this]() { if (!protocol_) { ESP_LOGW(TAG, "[4G] down-handler: protocol_ is null, skip"); return; } bool was_open = protocol_->IsAudioChannelOpened(); ESP_LOGI(TAG, "[4G] down-handler running on main loop | ws_open=%d device_state=%d", was_open ? 1 : 0, static_cast(device_state_)); if (was_open) { ESP_LOGW(TAG, "[4G] down-handler: closing zombie audio channel"); int64_t t0 = esp_timer_get_time() / 1000; protocol_->CloseAudioChannel(); int64_t dt = esp_timer_get_time() / 1000 - t0; ESP_LOGI(TAG, "[4G] down-handler: CloseAudioChannel done in %lldms", dt); } else { ESP_LOGI(TAG, "[4G] down-handler: channel was already closed, nothing to tear down"); } tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); if (shutting_down_.load()) { ESP_LOGI(TAG, "[4G] down-handler: shutting_down → skip state transition"); return; } if (device_state_ == kDeviceStateWifiConfiguring || device_state_ == kDeviceStateUpgrading || device_state_ == kDeviceStateConnecting) { ESP_LOGI(TAG, "[4G] down-handler: state=%d is protected, skip transition", static_cast(device_state_)); return; } if (device_state_ != kDeviceStateIdle) { ESP_LOGI(TAG, "[4G] down-handler: transitioning %d → Idle", static_cast(device_state_)); SetDeviceState(kDeviceStateIdle); } else { ESP_LOGI(TAG, "[4G] down-handler: already Idle, no transition"); } }); return; } // Only reopen on the down→up edge; the first "ready" after boot is // already handled by Application::Start(). bool expected = true; if (!network_was_down_.compare_exchange_strong(expected, false)) { ESP_LOGI(TAG, "[4G] up-handler: initial ready edge (not a reconnect), skipping — Application::Start owns the first OpenAudioChannel"); return; } ESP_LOGI(TAG, "[4G] up-handler: down→up edge detected, scheduling reconnect"); Schedule([this]() { if (!protocol_) { ESP_LOGW(TAG, "[4G] up-handler: protocol_ is null, skip"); return; } if (shutting_down_.load()) { ESP_LOGI(TAG, "[4G] up-handler: shutting_down → skip reconnect"); return; } if (device_state_ == kDeviceStateWifiConfiguring || device_state_ == kDeviceStateUpgrading || device_state_ == kDeviceStateConnecting) { ESP_LOGI(TAG, "[4G] up-handler: state=%d is protected, skip reconnect", static_cast(device_state_)); return; } if (protocol_->IsAudioChannelOpened()) { ESP_LOGI(TAG, "[4G] up-handler: channel already open (race), skip"); return; } ESP_LOGI(TAG, "[4G] up-handler: network restored → reopening audio channel (state %d → Connecting)", static_cast(device_state_)); SetDeviceState(kDeviceStateConnecting); int64_t t0 = esp_timer_get_time() / 1000; bool ok = protocol_->OpenAudioChannel(); int64_t dt = esp_timer_get_time() / 1000 - t0; SetDeviceState(kDeviceStateIdle); if (ok) { ESP_LOGI(TAG, "[4G] up-handler: reconnect SUCCESS in %lldms, state → Idle", dt); } else { ESP_LOGW(TAG, "[4G] up-handler: reconnect FAILED after %lldms → Idle (lazy retry on next user action)", dt); } }); } void Application::StartListening() { if (!protocol_) return; if (device_state_ == kDeviceStateIdle) { Schedule([this]() { if (!protocol_->IsAudioChannelOpened()) { SetDeviceState(kDeviceStateConnecting); if (!protocol_->OpenAudioChannel()) return; } SetListeningMode(kListeningModeManualStop); }); } } void Application::StopListening() { if (device_state_ != kDeviceStateListening) return; Schedule([this]() { protocol_->SendStopListening(); // 不切 idle — 等 server 的 tts.stop 消息后再切换状态 // server pipeline: ASR → LLM → TTS → tts.stop → 设备切 idle ESP_LOGI(TAG, "Sent listen.stop, waiting for server response..."); }); } void Application::AbortSpeaking(AbortReason reason) { ESP_LOGI(TAG, "[Playback] AbortSpeaking called, reason=%d", reason); tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); // 2026-6-30 ckkj debug 人为中断 TTS 时取消相关超时/延迟 timer CancelTtsStreamIdleTimer(); CancelSpeakingDelayTimer(); if (protocol_) { protocol_->SendAbortSpeaking(reason); } } void Application::SetListeningMode(ListeningMode mode) { listening_mode_ = mode; ESP_LOGW(TAG, "SetListeningMode (%s)%d", static_cast(mode) == 0 ? "kListeningModeAutoStop" : "", static_cast(mode)); // 2026-6-22 ckkj debug // 监听过程降低噪声 // audio_service_.EnableBargeInMode(true); // audio_service_.EnableCallMode(true); // debug end SetDeviceState(kDeviceStateListening); } bool Application::SetSpeakerVolume(int volume) { if (volume < AUDIO_CODEC_MIN_OUTPUT_VOLUME) volume = AUDIO_CODEC_MIN_OUTPUT_VOLUME; if (volume > AUDIO_CODEC_MAX_OUTPUT_VOLUME) volume = AUDIO_CODEC_MAX_OUTPUT_VOLUME; auto *codec = Board::GetInstance().GetAudioCodec(); if (!codec) return false; codec->SetOutputVolume(volume); SendStatusUpdate(); return true; } void Application::SendStatusUpdate() { if (!protocol_ || device_state_ == kDeviceStateWifiConfiguring) return; auto &board = Board::GetInstance(); cJSON *root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "type", "status"); auto *codec = board.GetAudioCodec(); if (codec) { cJSON_AddNumberToObject(root, "volume", codec->output_volume()); } int battery = board.GetBatteryLevel(); if (battery >= 0) { cJSON_AddNumberToObject(root, "battery", battery); } char *json = cJSON_PrintUnformatted(root); if (json) { SendTextMessage(std::string(json)); cJSON_free(json); } cJSON_Delete(root); } // === TTS timeout protection === // 2026-6-24 ckkj debug 防止设备卡住 void Application::StartTtsTimeoutTimer() { if (!tts_timeout_timer_) { esp_timer_create_args_t args = {}; args.callback = [](void *arg) { static_cast(arg)->OnTtsTimeout(); }; args.arg = this; args.name = "tts_timeout"; esp_timer_create(&args, &tts_timeout_timer_); } esp_timer_stop(tts_timeout_timer_); esp_timer_start_once(tts_timeout_timer_, kTtsTimeoutMs * 1000); ESP_LOGI(TAG, "[TTS] Timeout timer started: %lld ms", (long long)kTtsTimeoutMs); } void Application::CancelTtsTimeoutTimer() { if (tts_timeout_timer_) { esp_timer_stop(tts_timeout_timer_); } } void Application::CancelSpeakingDelayTimer() { if (speaking_delay_timer_) { esp_timer_stop(speaking_delay_timer_); } } void Application::StartTtsStreamIdleTimer() { if (!tts_stream_idle_timer_) { esp_timer_create_args_t args = {}; args.callback = [](void *arg) { static_cast(arg)->OnTtsStreamIdleTimeout(); }; args.arg = this; args.name = "tts_idle"; esp_timer_create(&args, &tts_stream_idle_timer_); } esp_timer_stop(tts_stream_idle_timer_); esp_timer_start_once(tts_stream_idle_timer_, kTtsStreamIdleTimeoutMs * 1000); } void Application::CancelTtsStreamIdleTimer() { if (tts_stream_idle_timer_) { esp_timer_stop(tts_stream_idle_timer_); } } void Application::OnTtsStreamIdleTimeout() { ESP_LOGW(TAG, "[TTS] Stream idle timeout: no TTS data for %lld ms, forcing state transition", (long long)kTtsStreamIdleTimeoutMs); Schedule([this]() { if (device_state_ == kDeviceStateSpeaking || tts_audio_active_.load()) { tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); CancelSpeakingDelayTimer(); CancelTtsTimeoutTimer(); SetListeningMode(kListeningModeAutoStop); } }); } void Application::OnTtsTimeout() { ESP_LOGW(TAG, "[TTS] Timeout: no tts.stop received within %lld ms, forcing state transition", (long long)kTtsTimeoutMs); // 2026-6-30 ckkj debug 将状态检查移到主循环,避免在 timer 回调中直接访问非原子 state; // 同时检查 tts_audio_active_,防止 listening 状态延迟切换期间 TTS 流中断无人处理。 Schedule([this]() { if (device_state_ == kDeviceStateSpeaking || tts_audio_active_.load()) { tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); CancelSpeakingDelayTimer(); CancelTtsStreamIdleTimer(); SetListeningMode(kListeningModeAutoStop); } }); } // === Low-battery monitoring === // Runs every 10 minutes from MainEventLoop's clock-tick handler. Charging // devices are skipped entirely (no warning, no shutdown) per product spec. void Application::CheckLowBatteryPeriodic() { auto &board = Board::GetInstance(); if (board.IsCharging()) { ESP_LOGI(TAG, "[LowBatt] charging, skip check"); return; } int battery = board.GetBatteryLevel(); if (battery < 0) { ESP_LOGW(TAG, "[LowBatt] battery read failed, skip"); return; } ESP_LOGI(TAG, "[LowBatt] periodic check: battery=%d%%", battery); if (battery < 10) { TriggerLowBatteryShutdown(); } else if (battery <= 20) { TriggerLowBatteryWarning20(); } } void Application::TriggerLowBatteryShutdown() { ESP_LOGW(TAG, "[LowBatt] <10%% — preparing shutdown"); auto &board = Board::GetInstance(); // Suppress further reconnect attempts and signal teardown early. shutting_down_.store(true); // Wait for any active TTS/local playback to finish gracefully so we don't // cut the child off mid-sentence. Cap at 30s to handle stuck playback. audio_service_.WaitForPlaybackComplete(30000); // Re-check charging — user might have plugged in USB during the wait. // If so, abort the shutdown (user responded to the previous warning). if (board.IsCharging()) { ESP_LOGI(TAG, "[LowBatt] USB plugged in during wait — cancelling shutdown"); shutting_down_.store(false); return; } // Close WS upfront so server stops pushing TTS while the goodbye prompt plays. if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendText("{\"type\":\"goodbye\"}"); vTaskDelay(pdMS_TO_TICKS(50)); protocol_->CloseAudioChannel(); } audio_service_.ResetDecoder(); if (audio_prompt_.HasPrompts(kPromptLowBattery10)) { audio_prompt_.PlayLocal(kPromptLowBattery10, audio_service_, /*protocol=*/nullptr, "low_battery_10"); vTaskDelay(pdMS_TO_TICKS(100)); audio_service_.WaitForPlaybackComplete(15000); } else { ESP_LOGW(TAG, "[LowBatt] low_battery_10 prompt missing, shutting down without audio"); } ESP_LOGI(TAG, "[LowBatt] Entering soft-off"); board.EnterSoftOff(); } void Application::TriggerLowBatteryWarning20() { // Don't interrupt an in-progress conversation — skip if speaking. // Next 10-minute tick will retry (no per-window dedup needed since the // periodic counter itself enforces the 10-min cadence). if (device_state_ == kDeviceStateSpeaking) { ESP_LOGI(TAG, "[LowBatt] device speaking, skip 20%% warning this tick"); return; } if (!audio_prompt_.HasPrompts(kPromptLowBattery20)) { ESP_LOGW(TAG, "[LowBatt] low_battery_20 prompt missing"); return; } ESP_LOGI(TAG, "[LowBatt] playing 20%% warning"); audio_prompt_.PlayLocal(kPromptLowBattery20, audio_service_, protocol_.get(), "low_battery_20"); } // === End low-battery monitoring === // === IdleWatchdog implementation === // See docs/features/idle-sleep-strategy.md. namespace { // All durations are in milliseconds. constexpr int64_t kIdleCheckMs = 180LL * 1000; // T+3min → idle_check prompt constexpr int64_t kIdleSleepMs = 600LL * 1000; // T+10min → idle_goodbye + soft off constexpr int64_t kIdleWindowMs = 15LL * 1000; // VAD/button window after each prompt int64_t now_ms() { return esp_timer_get_time() / 1000; } } // namespace const char *Application::IdleWatchdogPhaseName(IdleWatchdogPhase p) { switch (p) { case IdleWatchdogPhase::kInactive: return "Inactive"; case IdleWatchdogPhase::kRunning: return "Running"; case IdleWatchdogPhase::kPromptingCheck: return "PromptingCheck"; case IdleWatchdogPhase::kAwaitCheckResponse: return "AwaitCheckResponse"; case IdleWatchdogPhase::kIdleSleeping: return "IdleSleeping"; case IdleWatchdogPhase::kPromptingGoodbye: return "PromptingGoodbye"; case IdleWatchdogPhase::kAwaitGoodbyeResponse: return "AwaitGoodbyeResponse"; } return "?"; } void Application::IdleWatchdogResetExternal() { // Schedule into main loop so the actual reset runs single-threaded with // SetDeviceState / timer callbacks. Safe to call from any task / ISR-like // callback (button event, touch task). Schedule([this]() { IdleWatchdogReset(); }); } const char *Application::IdleWatchdogHelloConnectReason() const { return idle_watchdog_opening_check_channel_.load() ? "idle_check" : ""; } bool Application::IdleWatchdogShouldSkipChannelOpenReset() const { return idle_watchdog_opening_check_channel_.load(); } void Application::IdleWatchdogReset() { auto cur_phase = idle_phase_.load(); // In IdleSleeping, only the wake-word path may wake the device. Generic // activity resets (touch edges / rough energy VAD) are intentionally // ignored so they cannot reopen WS and trigger server-side L4 prompts. if (cur_phase == IdleWatchdogPhase::kIdleSleeping) { ESP_LOGI(TAG, "[IdleWdg] reset ignored: IdleSleeping waits for wake word"); return; } bool ws_ok = protocol_ && protocol_->IsAudioChannelOpened(); // WS bounce while watchdog is already armed: keep counting. // Reasoning: WS dropping due to heartbeat / network blip is NOT user // activity — it's the protocol layer recovering. Resetting watchdog to // Inactive here would let a 21s heartbeat timeout永远 cancel the 1-min // countdown. Once watchdog is started (R8: only the *initial* arm needs // WS), it should survive WS bounces and play local prompts on schedule // (idle_check / idle_goodbye are local ogg, don't need WS). if (!ws_ok && cur_phase != IdleWatchdogPhase::kInactive) { ESP_LOGI(TAG, "[IdleWdg] reset: ws=down but phase=%s already armed → keep counting", IdleWatchdogPhaseName(cur_phase)); return; } if (!ws_ok) { // Was already inactive, stay inactive — initial arm requires WS up ESP_LOGI(TAG, "[IdleWdg] reset: ws=down, phase=Inactive → no countdown"); return; } // Standard reset (ws_ok=true, user activity): stop everything, re-arm fresh if (idle_master_timer_) esp_timer_stop(idle_master_timer_); if (idle_window_timer_) esp_timer_stop(idle_window_timer_); audio_service_.EnableEnergyVad(false); idle_phase_.store(IdleWatchdogPhase::kRunning); idle_start_ts_ms_ = now_ms(); esp_timer_start_once(idle_master_timer_, kIdleCheckMs * 1000); // µs // 只在真正发生阶段切换时打日志;连续触摸 / VAD 在 Running 内反复 refresh // 计时器无需刷屏(行为完全一致:T+kIdleCheckMs 触发提示)。 if (cur_phase != IdleWatchdogPhase::kRunning) { ESP_LOGI(TAG, "[IdleWdg] reset: prev=%s → Running, armed for %lld ms (T+%llds prompt)", IdleWatchdogPhaseName(cur_phase), (long long)kIdleCheckMs, (long long)(kIdleCheckMs / 1000)); } } void Application::IdleWatchdogStop() { auto prev = idle_phase_.load(); if (idle_master_timer_) esp_timer_stop(idle_master_timer_); if (idle_window_timer_) esp_timer_stop(idle_window_timer_); audio_service_.EnableEnergyVad(false); idle_phase_.store(IdleWatchdogPhase::kInactive); ESP_LOGI(TAG, "[IdleWdg] stop: prev=%s → Inactive", IdleWatchdogPhaseName(prev)); } void Application::IdleWatchdogOnMasterFire() { auto phase = idle_phase_.load(); // Defer firing while the device is actually producing audio. // - Speaking: long TTS (multi-sentence story) doesn't re-trigger // SetDeviceState, so the original 60s arm would expire mid-story // and idle_check would cut off the playback. // - Ringing / Calling: phone-call states are mid-interaction. // NOT included on purpose: // - Listening: child may have stopped responding; if no activity for 60s // we genuinely want idle_check to ask "你还在吗". if (phase == IdleWatchdogPhase::kRunning && (device_state_ == kDeviceStateSpeaking || device_state_ == kDeviceStateRinging || device_state_ == kDeviceStateCalling)) { ESP_LOGI(TAG, "[IdleWdg] master fire deferred: state=%s active, re-arm %lldms", STATE_STRINGS[device_state_], (long long)kIdleCheckMs); if (idle_master_timer_) { esp_timer_stop(idle_master_timer_); esp_timer_start_once(idle_master_timer_, kIdleCheckMs * 1000); } return; } if (phase == IdleWatchdogPhase::kRunning) { ESP_LOGI(TAG, "[IdleWdg] master fire @T+%llds → PromptingCheck (idle_check)", (long long)((now_ms() - idle_start_ts_ms_) / 1000)); idle_phase_.store(IdleWatchdogPhase::kPromptingCheck); if (!audio_prompt_.HasPrompts(kPromptIdleCheck)) { ESP_LOGW(TAG, "[IdleWdg] idle_check prompt missing → check listening window (no audio)"); IdleWatchdogEnterCheckListeningWindow(); return; } if (device_state_ == kDeviceStateListening) { if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendStopListening(); } SetDeviceStateForIdleWatchdog(kDeviceStateIdle); ESP_LOGI(TAG, "[IdleWdg] pause listening before local idle_check prompt"); } else { audio_service_.EnableVoiceProcessing(false); } if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendAbortSpeaking(kAbortReasonNone); } audio_service_.ResetDecoder(); Board::GetInstance().GetLed()->SetState(LedState::kSpeaking); audio_prompt_.PlayLocal(kPromptIdleCheck, audio_service_, protocol_.get(), "idle_check"); audio_service_.WaitForPlaybackComplete(8000); audio_prompt_.NotifyLocalDone(protocol_.get(), "idle_check"); ESP_LOGI(TAG, "[IdleWdg] idle_check playback done"); // Drain I2S DMA tail + speaker decay + room reverb before opening VAD, // otherwise the device hears its own prompt and self-triggers (no AEC // in idle mode — AEC is only on in call_mode). vTaskDelay(pdMS_TO_TICKS(800)); IdleWatchdogEnterCheckListeningWindow(); return; } if (phase == IdleWatchdogPhase::kIdleSleeping) { ESP_LOGI(TAG, "[IdleWdg] master fire @T+%llds → PromptingGoodbye (idle_goodbye)", (long long)((now_ms() - idle_start_ts_ms_) / 1000)); idle_phase_.store(IdleWatchdogPhase::kPromptingGoodbye); if (!audio_prompt_.HasPrompts(kPromptIdleGoodbye)) { ESP_LOGW(TAG, "[IdleWdg] idle_goodbye prompt missing → AwaitGoodbyeResponse (no audio)"); idle_phase_.store(IdleWatchdogPhase::kAwaitGoodbyeResponse); audio_service_.EnableEnergyVad(true); esp_timer_start_once(idle_window_timer_, kIdleWindowMs * 1000); return; } audio_service_.ResetDecoder(); Board::GetInstance().GetLed()->SetState(LedState::kSpeaking); audio_prompt_.PlayLocal(kPromptIdleGoodbye, audio_service_, /*protocol=*/nullptr, "idle_goodbye"); audio_service_.WaitForPlaybackComplete(8000); ESP_LOGI(TAG, "[IdleWdg] idle_goodbye playback done"); // Same I2S/reverb drain as idle_check (see comment above). vTaskDelay(pdMS_TO_TICKS(800)); idle_phase_.store(IdleWatchdogPhase::kAwaitGoodbyeResponse); Board::GetInstance().GetLed()->SetState(LedState::kOff); audio_service_.EnableEnergyVad(true); esp_timer_start_once(idle_window_timer_, kIdleWindowMs * 1000); ESP_LOGI(TAG, "[IdleWdg] → AwaitGoodbyeResponse, VAD on, window %llds", (long long)(kIdleWindowMs / 1000)); return; } ESP_LOGW(TAG, "[IdleWdg] master fired in unexpected phase=%s", IdleWatchdogPhaseName(phase)); } void Application::IdleWatchdogEnterCheckListeningWindow() { bool ws_ok = protocol_ && protocol_->IsAudioChannelOpened(); if (!ws_ok && protocol_) { ESP_LOGW(TAG, "[IdleWdg] idle_check window: WS down, trying reconnect for listening"); idle_watchdog_opening_check_channel_.store(true); ws_ok = protocol_->OpenAudioChannel(); idle_watchdog_opening_check_channel_.store(false); } if (idle_master_timer_) esp_timer_stop(idle_master_timer_); if (idle_window_timer_) esp_timer_stop(idle_window_timer_); idle_phase_.store(IdleWatchdogPhase::kAwaitCheckResponse); if (ws_ok && protocol_) { if (device_state_ == kDeviceStateListening) { protocol_->SendStopListening(); SetDeviceStateForIdleWatchdog(kDeviceStateIdle); } listening_mode_ = kListeningModeAutoStop; SetDeviceStateForIdleWatchdog(kDeviceStateListening); ESP_LOGI(TAG, "[IdleWdg] → AwaitCheckResponse, normal listening on, window %llds", (long long)(kIdleWindowMs / 1000)); } else { Board::GetInstance().GetLed()->SetState(LedState::kIdle); ESP_LOGW(TAG, "[IdleWdg] → AwaitCheckResponse, WS unavailable; VAD-only fallback, window %llds", (long long)(kIdleWindowMs / 1000)); } audio_service_.EnableEnergyVad(true); esp_timer_start_once(idle_window_timer_, kIdleWindowMs * 1000); } void Application::IdleWatchdogOnWindowFire() { auto phase = idle_phase_.load(); audio_service_.EnableEnergyVad(false); if (phase == IdleWatchdogPhase::kAwaitCheckResponse) { ESP_LOGI(TAG, "[IdleWdg] AwaitCheck listening window expired (15s no response) → IdleSleeping"); if (device_state_ != kDeviceStateIdle && device_state_ != kDeviceStateListening) { ESP_LOGI(TAG, "[IdleWdg] AwaitCheck expired but state=%s is active → reset instead", STATE_STRINGS[device_state_]); IdleWatchdogReset(); return; } if (device_state_ == kDeviceStateListening) { if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendStopListening(); } SetDeviceStateForIdleWatchdog(kDeviceStateIdle); } IdleWatchdogEnterIdleSleeping(); return; } if (phase == IdleWatchdogPhase::kAwaitGoodbyeResponse) { ESP_LOGI(TAG, "[IdleWdg] AwaitGoodbye window expired (15s no response) → EnterSoftOff (light sleep)"); IdleWatchdogStop(); Board::GetInstance().EnterSoftOff(); return; } ESP_LOGW(TAG, "[IdleWdg] window fired in unexpected phase=%s", IdleWatchdogPhaseName(phase)); } void Application::IdleWatchdogEnterIdleSleeping() { ESP_LOGI(TAG, "[IdleWdg] enter IdleSleeping: closing WS, LED off, keep wake-word/button/touch"); idle_phase_.store(IdleWatchdogPhase::kIdleSleeping); // Going to sleep — drop activation code replay so we don't ring the // speaker on a battery-saving device. Next wake will get a fresh hello. StopActivationReplay("idle sleeping"); // Block lazy-reconnect on WS close, send goodbye, close channel shutting_down_.store(true); if (protocol_ && protocol_->IsAudioChannelOpened()) { protocol_->SendText("{\"type\":\"goodbye\"}"); vTaskDelay(pdMS_TO_TICKS(100)); protocol_->CloseAudioChannel(); } // LED off; wake-word/button/touch/MIC stay live (handled by audio_service) Board::GetInstance().GetLed()->SetState(LedState::kOff); // Re-arm energy VAD so audible voice can wake the device (alongside // wake-word, button, touch). The reset path drops shutting_down_ etc. audio_service_.EnableEnergyVad(true); // Schedule master timer for the remaining time until T+180s. int64_t elapsed = now_ms() - idle_start_ts_ms_; int64_t remaining = kIdleSleepMs - elapsed; if (remaining < 1000) remaining = 1000; esp_timer_start_once(idle_master_timer_, remaining * 1000); ESP_LOGI(TAG, "[IdleWdg] sleeping; goodbye in %lld ms", (long long)remaining); } void Application::IdleWatchdogWakeFromIdleSleeping() { auto phase = idle_phase_.load(); if (phase != IdleWatchdogPhase::kIdleSleeping) { return; } ESP_LOGI(TAG, "[IdleWdg] wake word exits IdleSleeping → reconnect"); if (idle_master_timer_) esp_timer_stop(idle_master_timer_); if (idle_window_timer_) esp_timer_stop(idle_window_timer_); audio_service_.EnableEnergyVad(false); idle_phase_.store(IdleWatchdogPhase::kInactive); shutting_down_.store(false); Board::GetInstance().GetLed()->SetState(LedState::kIdle); } // === Activation code periodic replay === void Application::RunActivationSequence(const std::vector> &items) { if (!activation_replay_active_.load()) { ESP_LOGI(TAG, "[Activation] sequence skipped (replay stopped)"); return; } tts_audio_active_.store(true); // Activation prompt text contains the wake word "播乐"; mute wake-word // detection during playback to avoid self-abort. bool wake_was_enabled = audio_service_.IsWakeWordDetectionEnabled(); if (wake_was_enabled) { audio_service_.EnableWakeWordDetection(false); } audio_service_.ResetDecoder(); audio_service_.SetPlaybackHint(true); SetDeviceState(kDeviceStateSpeaking); for (size_t i = 0; i < items.size(); ++i) { if (!activation_replay_active_.load()) { ESP_LOGI(TAG, "[Activation] sequence aborted before item %u", static_cast(i)); break; } const auto &it = items[i]; int play_idx = it.second >= 0 ? it.second : 0; int num_frames = audio_prompt_.GetFrameCount(it.first, play_idx); if (num_frames <= 0) continue; audio_prompt_.PlayByIndex(it.first, play_idx, audio_service_); // Derive wait from frame count (each frame = 20ms) + 500ms latency buffer. int wait_ms = num_frames * 20 + 500; int waited_ms = 0; while (waited_ms < wait_ms && activation_replay_active_.load()) { int step_ms = std::min(100, wait_ms - waited_ms); vTaskDelay(pdMS_TO_TICKS(step_ms)); waited_ms += step_ms; } if (!activation_replay_active_.load()) { ESP_LOGI(TAG, "[Activation] sequence aborted during item %u", static_cast(i)); break; } if (i + 1 < items.size()) { for (int waited_gap_ms = 0; waited_gap_ms < 400 && activation_replay_active_.load(); waited_gap_ms += 100) { vTaskDelay(pdMS_TO_TICKS(100)); } } } tts_audio_active_.store(false); audio_service_.SetPlaybackHint(false); SetDeviceState(kDeviceStateIdle); if (wake_was_enabled) { audio_service_.EnableWakeWordDetection(true); } // Re-arm replay timer ONLY at the end of playback so the gap between // playbacks is true silence (not measured from message arrival). If a // stop trigger (tts/play_local/sleep) cleared the cache while we were // playing, skip rearming and let the loop terminate. if (activation_replay_active_.load() && activation_replay_timer_) { esp_timer_start_once(activation_replay_timer_, (int64_t)kActivationReplayMs * 1000); ESP_LOGI(TAG, "[Activation] next replay in %d ms", kActivationReplayMs); } } void Application::StartActivationReplay(std::vector> seq) { // Cache only — timer is started at the end of RunActivationSequence so // the kActivationReplayMs gap is measured from playback END. if (activation_replay_timer_) { esp_timer_stop(activation_replay_timer_); } size_t replay_count = seq.size(); { std::lock_guard lock(activation_replay_mutex_); activation_replay_seq_ = std::move(seq); activation_replay_active_.store(true); } ESP_LOGI(TAG, "[Activation] replay enabled: %zu items, %d ms inter-cycle gap", replay_count, kActivationReplayMs); } void Application::StopActivationReplay(const char *reason) { if (activation_replay_timer_) { esp_timer_stop(activation_replay_timer_); } bool was_active = activation_replay_active_.exchange(false); { std::lock_guard lock(activation_replay_mutex_); activation_replay_seq_.clear(); } if (!was_active) { return; } ESP_LOGI(TAG, "[Activation] replay stopped (%s)", reason ? reason : ""); } void Application::OnActivationReplayTimer() { // Re-fire only if the cached sequence is still valid (not cleared by // tts/play_local/sleep handlers in the interim). if (!activation_replay_active_.load()) return; std::vector> items; { std::lock_guard lock(activation_replay_mutex_); if (!activation_replay_active_.load() || activation_replay_seq_.empty()) return; items = activation_replay_seq_; } ESP_LOGI(TAG, "[Activation] replay fire (%zu items)", items.size()); Schedule([this, items]() { RunActivationSequence(items); }); // Note: RunActivationSequence rearms the timer at its tail, so we don't // schedule the next cycle here — that would shorten the gap. }