bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

296
main/application.h Normal file
View File

@@ -0,0 +1,296 @@
#pragma once
#include "protocols/protocol.h"
#include "audio/audio_service.h"
#include "audio/audio_prompt.h"
#include "ota.h"
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <esp_timer.h>
#include <string>
#include <memory>
#include <functional>
#include <vector>
#include <deque>
#include <mutex>
#include <atomic>
enum DeviceState {
kDeviceStateUnknown,
kDeviceStateStarting,
kDeviceStateWifiConfiguring,
kDeviceStateIdle,
kDeviceStateConnecting,
kDeviceStateListening,
kDeviceStateSpeaking,
kDeviceStateRinging, // Incoming call, playing ringtone + mic on for accept detection
kDeviceStateCalling, // Active call, full-duplex audio
kDeviceStateUpgrading,
};
#define MAIN_EVENT_SCHEDULE BIT0
#define MAIN_EVENT_SEND_AUDIO BIT1
#define MAIN_EVENT_ERROR BIT2
#define MAIN_EVENT_CLOCK_TICK BIT3
#define MAIN_EVENT_STATUS_TICK BIT4
#define MAIN_EVENT_WAKE_WORD BIT5
class Board;
class Application {
public:
static Application& GetInstance();
void Start();
DeviceState device_state() const { return device_state_; }
// 对话控制
void ToggleChatState();
void StartListening();
void StopListening();
// 音量
bool SetSpeakerVolume(int volume);
// Schedule 异步任务到主循环
void Schedule(std::function<void()> callback);
// Send text message to server via protocol (thread-safe, scheduled on main loop)
void SendTextMessage(const std::string& text);
// Called by Board when the underlying network (WiFi / 4G modem) goes
// down or comes back up. On down we actively tear down the zombie WS
// so the next send won't stall waiting for a 10s TCP timeout; on the
// up edge (only after a prior down) we eagerly reopen so the device
// is ready before the user talks again.
void NotifyNetworkStateChanged(bool ready);
Protocol* GetProtocol() { return protocol_.get(); }
AudioService audio_service_;
AudioPrompt audio_prompt_;
private:
Application();
~Application();
void MainEventLoop();
void SetDeviceState(DeviceState state);
void SendStatusUpdate();
void AbortSpeaking(AbortReason reason);
void SetListeningMode(ListeningMode mode);
void SetDeviceStateForIdleWatchdog(DeviceState state);
void CheckNewVersion(class Ota& ota);
EventGroupHandle_t event_group_ = nullptr;
esp_timer_handle_t clock_timer_handle_ = nullptr;
esp_timer_handle_t status_timer_handle_ = nullptr;
TaskHandle_t main_event_loop_task_ = nullptr;
std::unique_ptr<Protocol> protocol_;
DeviceState device_state_ = kDeviceStateUnknown;
ListeningMode listening_mode_ = kListeningModeAutoStop;
//2026-6-24 ckkj debug 防止人声未结束马上应答
int64_t listening_start_ms_ = 0; // Timestamp when entering listening state
static constexpr int64_t kMinListeningDurationMs = 5000; // Minimum 5s listening before speaking
std::mutex mutex_;
std::deque<std::function<void()>> main_tasks_;
std::string last_error_message_;
std::atomic<bool> tts_audio_active_{false};
std::string tts_current_text_; // Accumulated sentence_start texts, logged full on tts.stop
std::atomic<bool> local_prompt_playing_{false}; // 2026-6-27 ckkj debug 正在播放本地提示音
// 2026-6-24 ckkj debug 超时保护防止网络不好服务器断开导致卡住
static constexpr int64_t kTtsTimeoutMs = 60000; // 60s timeout
esp_timer_handle_t tts_timeout_timer_ = nullptr;
void StartTtsTimeoutTimer();
void CancelTtsTimeoutTimer();
void OnTtsTimeout();//超时回调,强制切换到 listening 状态
// 2026-6-30 ckkj debug 管理 listening->speaking 的延迟切换 timer,
// 避免状态已变后延迟 timer 仍错误触发
esp_timer_handle_t speaking_delay_timer_ = nullptr;
void CancelSpeakingDelayTimer();
// 2026-6-30 ckkj debug 添加 TTS 流沉寂超时:超过该时间未收到任何 TTS
// 数据/文本则认为服务器流已中断,主动切回 listening,避免无 stop 时卡死
static constexpr int64_t kTtsStreamIdleTimeoutMs = 10000; // 10s idle timeout
esp_timer_handle_t tts_stream_idle_timer_ = nullptr;
void StartTtsStreamIdleTimer();
void CancelTtsStreamIdleTimer();
void OnTtsStreamIdleTimeout();
//debug end
// One-shot guard: set when welcome prompt starts; consumed (cleared without
// audible playback) by the next wake-word-in-idle so the device doesn't say
// "我在" right after the boot greeting which already addressed the child.
std::atomic<bool> suppress_next_wake_response_{false};
// Tracks the last network edge seen via NotifyNetworkStateChanged.
// Only flips to true when we actually observe a down event, so the
// initial "network ready" emitted at boot does NOT trigger a reconnect
// (Application::Start already owns the first OpenAudioChannel).
std::atomic<bool> network_was_down_{false};
// === Low-battery monitoring ===
// See docs/features/low-battery-monitor.md (TODO) — runs every 10 minutes
// via the clock tick. Skipped entirely when board.IsCharging() is true.
// Two thresholds:
// ≤20% → play "我快没电了,请及时充电哦!" every 10 min (idle/listening only)
// <10% → play "我快没电了,帮我连接电源充电哦!我先退下了。" then EnterSoftOff
void CheckLowBatteryPeriodic();
void TriggerLowBatteryShutdown(); // 10% path — waits for current playback, then off
void TriggerLowBatteryWarning20(); // 20% path — skipped if speaking
// Pending 20% warning at boot: when boot battery ≤20%, set so the first
// periodic tick after entering idle plays the warning (rather than
// interrupting boot prompt / welcome).
bool pending_low_battery_warning_at_boot_ = false;
public:
std::atomic<bool> shutting_down_{false}; // Soft power off in progress
// 传感器重构 ADR-006 / 决策 #8 #43:删除 upright_axis_ / upright_threshold_。
// 姿态识别能力保留在 server 侧,未来从 IMU 向量流自行计算。
// Alarm tone selection (index into alarm_set/alarm_wake prompt arrays, -1 = random)
std::atomic<int> alarm_set_tone_index_{-1};
std::atomic<int> alarm_wake_tone_index_{-1};
// Reminder timers (multi, one-shot, set via "set_timer" message from server)
// Stored as a sorted ascending list of esp_timer_get_time() targets.
// Protected by reminder_mutex_ since it is read by both the main loop and the
// soft-off polling loop on a separate task.
mutable std::mutex reminder_mutex_;
std::vector<int64_t> reminder_targets_us_;
void AddReminderTimer(int seconds);
void CancelAllReminderTimers();
void CancelMostRecentReminderTimer(); // removes the next-to-fire timer
bool IsReminderDue() const;
void PlayReminderSound();
int GetReminderCount() const;
// Alarm clock (absolute time, persisted in NVS, set via "set_alarm" from server)
// Completely independent of reminder timers — separate mutex, storage, and play function.
struct AlarmEntry {
int32_t id; // Server-assigned unique ID
uint8_t hour; // 0-23
uint8_t minute; // 0-59
uint8_t repeat_mask; // bit0=Sun..bit6=Sat, 0=one-shot
bool enabled;
int64_t fire_epoch; // One-shot: Unix seconds, 0 = not used
char label[32];
};
static constexpr int kMaxAlarms = 16;
mutable std::mutex alarm_mutex_;
std::vector<AlarmEntry> alarms_;
int alarm_last_fired_minute_{-1}; // Dedup: don't re-fire within same minute
// Shared across PlayReminderSound (timer) and PlayAlarmSound (clock alarm)
// to prevent two reminders/alarms overlapping when they fire close in time.
// The second fire in the same window is merged: its fired IDs are still
// reported to server, but its audio is suppressed until the first finishes.
std::atomic<bool> alarm_reminder_playing_{false};
void LoadAlarmsFromNvs();
void SaveAlarmsToNvs();
void AddOrUpdateAlarm(const AlarmEntry& entry);
void DeleteAlarm(int32_t id);
void SyncAlarms(const std::vector<AlarmEntry>& entries);
void ClearAllAlarms();
void EnsureBuiltInFirstDayPromptAlarm();
void DisableBuiltInFirstDayPromptAlarm();
bool IsWakeOnlyAlarm(const AlarmEntry& entry) const;
bool IsAlarmDue() const;
void PlayAlarmSound();
int GetAlarmCount() const;
// Loop a local prompt (with ~1s gap between rings) until either
// loop_duration_ms elapses or wake-word triggers ResetDecoder. Used by
// PlayReminderSound + PlayAlarmSound so the ringing keeps going for ~1
// minute instead of single-shot. NotifyLocalDone is called internally
// at exit; caller still owns SetDeviceState / tts_audio_active_ etc.
void PlayAlarmLoop(PromptGroup pg, int wake_idx, const char* group_name,
int loop_duration_ms);
// FreeRTOS entry that runs PlayAlarmLoop in its own task so the main
// event loop stays responsive (wake word, button, network, sensor) for
// the 60-second alarm. Without this, PlayAlarmLoop runs synchronously
// inside a Schedule() lambda that blocks MainEventLoop, which means
// the WAKE_WORD bit gets set but never consumed → alarm uninterruptible.
// Receives a heap-allocated AlarmPlaybackParams (defined in .cc), runs,
// posts teardown back via Schedule() (avoids cross-task SetDeviceState
// race), deletes params, vTaskDelete(self).
static void AlarmPlaybackTask(void* arg);
// === IdleWatchdog (firmware-side idle sleep strategy) ===
// See docs/features/idle-sleep-strategy.md for full specification.
public:
// Activity events (button, touch, etc.) call this to keep watchdog from
// firing. Safe to call from any task — Schedule()s its work to the main loop.
void IdleWatchdogResetExternal();
const char* IdleWatchdogHelloConnectReason() const;
bool IdleWatchdogShouldSkipChannelOpenReset() const;
private:
// Two-phase timeout from last activity:
// T+180s: play idle_check ("你还在吗?小朋友") + 15s listening window
// → no response → enter idle sleeping (LED off + WS closed,
// wake-word/button/touch still live)
// T+600s: play idle_goodbye ("那我先退下来…") + 15s VAD window
// → no response → EnterSoftOff (light sleep, button-wake only)
// Reset by any activity: SetDeviceState(Listening/Speaking/Ringing/Calling),
// button click, touch event, energy-VAD voice detection, OnAudioChannelOpened.
enum class IdleWatchdogPhase : uint8_t {
kInactive, // WS not connected / watchdog disabled
kRunning, // Plain idle, master timer counting down to 60s
kPromptingCheck, // Playing idle_check prompt
kAwaitCheckResponse, // Prompt done, 15s listen/VAD/button/touch window
kIdleSleeping, // WS closed, LED off, wake-word/button/touch live
kPromptingGoodbye, // Playing idle_goodbye prompt
kAwaitGoodbyeResponse, // Prompt done, 15s VAD/button/touch window
};
void IdleWatchdogReset(); // Called by any activity
void IdleWatchdogStop(); // Called when leaving idle entirely
void IdleWatchdogOnMasterFire(); // Master timer expired
void IdleWatchdogOnWindowFire(); // 15s window expired
void IdleWatchdogEnterCheckListeningWindow(); // Prompt done → normal listening window
void IdleWatchdogEnterIdleSleeping(); // T+76s no response → low-power idle
void IdleWatchdogWakeFromIdleSleeping(); // Wake word explicitly exits IdleSleeping
static const char* IdleWatchdogPhaseName(IdleWatchdogPhase p);
esp_timer_handle_t idle_master_timer_ = nullptr; // 60s or remaining-to-180s
esp_timer_handle_t idle_window_timer_ = nullptr; // 15s post-prompt window
// === Activation code periodic replay (firmware-side) ===
// Server pushes the activation-code sequence once per hello. To let the user
// hear the code multiple times without relying on WS reconnect, we cache the
// last sequence locally and replay it every kActivationReplayMs until
// (a) the device gets activated (server pushes welcome/tts/play_local for
// anything other than activation_device → StopActivationReplay), or
// (b) idle watchdog enters IdleSleeping (StopActivationReplay).
// Gap between the END of one playback and the START of the next.
// Total cycle ≈ ~14s playback + this gap. Set to 6000ms → ~20s cycle.
static constexpr int kActivationReplayMs = 6000;
std::mutex activation_replay_mutex_;
std::atomic<bool> activation_replay_active_{false};
std::vector<std::pair<PromptGroup, int>> activation_replay_seq_;
esp_timer_handle_t activation_replay_timer_ = nullptr;
void StartActivationReplay(std::vector<std::pair<PromptGroup, int>> seq);
void StopActivationReplay(const char* reason);
void RunActivationSequence(const std::vector<std::pair<PromptGroup, int>>& items);
void OnActivationReplayTimer();
int64_t idle_start_ts_ms_ = 0; // T0 anchor (esp_timer_get_time/1000)
std::atomic<IdleWatchdogPhase> idle_phase_{IdleWatchdogPhase::kInactive};
std::atomic<bool> idle_watchdog_opening_check_channel_{false};
std::atomic<bool> idle_watchdog_internal_state_change_{false};
private:
std::atomic<bool> call_active_{false}; // Phone call in progress
std::string pending_call_id_; // Current call ID from server
// Pending OTA upgrade (decided at startup, executed after WS connect)
std::unique_ptr<Ota> pending_ota_;
std::string pending_ota_reason_; // "auto" or "force"
};