commit e96d6d19dfb58977033dae35d4108da52afd4478 Author: Zhangyanmei <251404981@qq.com> Date: Fri Nov 27 16:38:11 2026 +0800 bolar_2 backup diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..9d90057 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f313f27 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +build/ +build-host/ +managed_components/ +dependencies.lock +sdkconfig +sdkconfig.old +temp/ diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..3e549df --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,23 @@ +{ + "configurations": [ + { + "name": "ESP-IDF", + "compilerPath": "${config:idf.toolsPathWin}\\tools\\xtensa-esp-elf\\esp-14.2.0_20260121\\xtensa-esp-elf\\bin\\xtensa-esp32s3-elf-gcc.exe", + "compileCommands": "${config:idf.buildPath}/compile_commands.json", + "includePath": [ + "${config:idf.espIdfPath}/components/**", + "${config:idf.espIdfPathWin}/components/**", + "${workspaceFolder}/**" + ], + "browse": { + "path": [ + "${config:idf.espIdfPath}/components", + "${config:idf.espIdfPathWin}/components", + "${workspaceFolder}" + ], + "limitSymbolsToIncludedHeaders": true + } + } + ], + "version": 4 +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2511a38 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "type": "gdbtarget", + "request": "attach", + "name": "Eclipse CDT GDB Adapter" + }, + { + "type": "espidf", + "name": "Launch", + "request": "launch" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..e425632 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "C_Cpp.intelliSenseEngine": "default", + "idf.portWin": "COM12", + "idf.flashType": "UART", + "idf.pythonInstallPath": "d:\\software\\Espressif\\frameworks\\esp-idf-v5.4.3\\tools\\tools\\idf-python\\3.11.2\\python.exe", + "idf.espIdfPathWin": "d:\\software\\Espressif\\frameworks\\esp-idf-v5.4.3", + "idf.toolsPathWin": "d:\\software\\Espressif\\frameworks\\esp-idf-v5.4.3\\tools" +} diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..5f38588 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,39 @@ +cmake_minimum_required(VERSION 3.16) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +set(PROJECT_VER "2.0.0-dev") +project(borla-firmware2 VERSION ${PROJECT_VER}) + +# ESP-SR creates its selected model image first. The Borla product WakeNet +# model is private to this firmware, so inject it into that generated image +# and repack without making firmware2 depend on the legacy firmware sources. +idf_build_get_property(build_dir BUILD_DIR) +set(pack_model_py + "${CMAKE_SOURCE_DIR}/managed_components/espressif__esp-sr/model/pack_model.py") +add_custom_command( + OUTPUT "${build_dir}/srmodels/.borla_custom_done" + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${CMAKE_SOURCE_DIR}/model_data/wn9l_ni3hao3bo1le4" + "${build_dir}/srmodels/wn9l_ni3hao3bo1le4" + COMMAND python "${pack_model_py}" + -m "${build_dir}/srmodels" -o srmodels.bin + COMMAND ${CMAKE_COMMAND} -E touch + "${build_dir}/srmodels/.borla_custom_done" + DEPENDS + "${build_dir}/srmodels/srmodels.bin" + "${CMAKE_SOURCE_DIR}/model_data/wn9l_ni3hao3bo1le4/_MODEL_INFO_" + "${CMAKE_SOURCE_DIR}/model_data/wn9l_ni3hao3bo1le4/wn9_data" + "${CMAKE_SOURCE_DIR}/model_data/wn9l_ni3hao3bo1le4/wn9_index" + WORKING_DIRECTORY "${build_dir}/srmodels" + COMMENT "Injecting Borla WakeNet model" + VERBATIM +) +add_custom_target( + firmware2_custom_wakeword ALL + DEPENDS "${build_dir}/srmodels/.borla_custom_done") +add_dependencies(firmware2_custom_wakeword srmodels_bin) +add_dependencies(flash firmware2_custom_wakeword) diff --git a/README.md b/README.md new file mode 100644 index 0000000..6d347fa --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# Borla Firmware 2 + +`firmware2/` 是 Borla ESP32-S3 固件的渐进式重构工程。它不引用或修改 +`firmware/` 的源码;旧工程只作为迁移期间的行为参考。 + +## 当前范围 + +当前版本已完成路线图阶段 0~13 的代码,包括控制面、板级、统一播放、WiFi/4G、 +WebSocket v3、音频数据面、Voice Frontend、BLE 配网、传感器、日程、电源、OTA、 +通话、好友、激活码和记忆缓存: + +- 固定容量、无堆分配的 FreeRTOS 事件队列 +- 正交的设备运行状态 +- 纯 C++ 状态归约器 +- 状态不变量校验 +- Effect/Port 边界 +- CompositionRoot 和真实 EffectRouter 装配 +- Borla-S3 GPIO4/GPIO6 电源轨、设备身份和重启 +- GPIO11 WS2812 基础灯效 +- GPIO12 单击、双击、多击和长按事件输入 +- ES8311、24kHz 单声道 I2S 输出和软件音量 +- 单一扬声器任务、固定 PSRAM 帧池和 Opus 解码 +- PlaybackSession、优先级、抢占、唯一 ID 取消、generation 追踪和播放指标 +- 45 个构建期校验的嵌入式 Ogg/Opus 提示音和常驻 PSRAM producer(含睡眠鼾声) +- ESP-NETIF/ESP WiFi transport、兼容旧固件的 NVS 凭据存储 +- 静态任务驱动的连接管理、SSID 轮换、指数退避和连接诊断 +- ML307 UART/AT/LTE/PPP、弱网/断网自动切换和四击手动切网 +- TLS WebSocket transport、PSRAM 握手内存、v3 hello、心跳、黑洞检测和协议退避 +- 强类型 ServerMessageDispatcher 与固定大小协议诊断 +- 24kHz 全双工 I2S、16kHz Opus 上行和 24kHz Opus 下行 +- WebSocket v3 二进制批量音频、整包校验、背压和指标 +- ESP-SR WakeNet、能量 VAD、AEC/NS/AGC 和实际播放 reference +- FF01~FF07 BLE GATT、MTU 分包、WiFi 预扫描和 DHCP 后凭据落盘 +- 五路 Touch 基线/阈值/消抖、BMI270 50Hz IMU、Gravity 旁路,以及带物理 + 有效性门禁的电池估算 +- Reminder、持久化闹钟、Idle、低电量策略、light-sleep 和本地唤醒 +- HTTPS OTA、optional/auto/force、流式 A/B 写入、SHA256 和回滚确认 +- 双设备 call 信令、专用全双工会话、接听/挂断和断网收敛 +- BLE 好友扫描/广播、候选选择、NVS 离线优先和重连补传 +- 旧 `device`/`friends` NVS 好友与设备昵称数据向 `friend_v2` 的保留式迁移 +- 本地提示音序列、激活码节奏与 6 秒重复播放 +- 记忆快照 NVS、ClientHello 回传、server 同步和旧 `claude_mem` 迁移 +- ServerHello 三击/四击映射和连接异常提示持久化、三击/四击遥测上报 +- 运行时音量、唤醒词、TTS 插话、轻睡眠和临时安全红灯控制 +- 本地提示音 start/done 生命周期上报,睡眠场景可等待鼾声播完再进入轻睡眠 +- TTS 期间上行门控,关闭插话后立即丢弃残留批次且不再发送语音 +- 配网、轻睡眠与关机前发送 goodbye,再确定性关闭 Realtime +- 周期性内部 heap、PSRAM 和全部 FreeRTOS 任务栈高水位诊断 +- 可在 macOS/Linux 执行的状态机、Effect、播放、连接、协议、VAD、BLE、传感器、 + 日程和 OTA 测试 + +阶段 1~13 的代码和本地构建已完成,但 ESP32-S3 播放/录音/声学、网络、server、 +小程序、传感器、低功耗、OTA、双设备和长稳尚未验收。因此这些阶段仍保持 +“进行中”,不能仅凭编译通过标记为完成。 + +## 目录 + +```text +firmware2/ +├── main/ +│ ├── app/ # 单写者事件循环 +│ ├── core/ # 纯 C++ 事件、状态、归约器 +│ ├── ports/ # 音频、网络、协议、硬件接口 +│ ├── adapters/ # Effect 路由和音频引擎 +│ ├── audio/ # 播放会话、帧管线、Opus 和本地提示音 +│ ├── connectivity/ # WiFi 连接策略、退避、凭据和 manager +│ ├── diagnostics/ # heap、PSRAM 和 FreeRTOS 任务栈诊断 +│ ├── friend/ # 好友候选、NVS 与离线补传 +│ ├── memory/ # 记忆快照、校验和旧分区迁移 +│ ├── activation/ # 本地序列与激活码重复播放 +│ ├── protocol/ # WebSocket v3 transport 边界、JSON 和实时协议 +│ ├── provisioning/ # BLE 配网编解码和工作流 +│ ├── sensor/ # Touch/IMU/Gravity/电池纯逻辑和服务 +│ ├── schedule/ # Reminder、闹钟持久化与响铃协调 +│ ├── power/ # Idle、低电量、关机收敛和唤醒 +│ ├── ota/ # 版本检查、A/B 下载、校验和回滚 +│ └── platform/ # 电源、LED、按键、音频、WiFi、ML307 和 NimBLE +├── host_tests/ # 不依赖 ESP-IDF 的状态测试 +└── partitions/ # A/B OTA 分区基础 +``` + +## 验证 + +宿主机测试: + +```bash +cmake -S firmware2/host_tests -B /tmp/borla-firmware2-tests +cmake --build /tmp/borla-firmware2-tests +ctest --test-dir /tmp/borla-firmware2-tests --output-on-failure +``` + +ESP-IDF: + +```bash +cd firmware2 +idf.py set-target esp32s3 +idf.py build +``` + +当前验证结果和真机步骤分别见 +[验证矩阵](docs/validation-matrix.md) 与 +[真机验证清单](docs/hardware-validation-checklist.md)。旧固件功能的迁移 +状态见 [迁移清单](docs/migration-from-firmware.md)。 + +## 迁移约束 + +1. `protocols/` 仍是跨系统通信的唯一契约来源。 +2. 原 `firmware/` 不作为链接依赖,不从中复制可变全局状态。 +3. 音频数据不进入 `AppEventQueue`,控制面和数据面严格分离。 +4. 业务状态只允许 `Application` 事件循环写入。 +5. timer、ISR、网络、音频和传感器任务只能发布事件。 +6. 每迁移一个模块先补行为测试;阶段 13 已从构建和 `CompositionRoot` 清除 + 全部 `Pending*` Stub,后续不得重新接入占位实现。 +7. 任何本地或远程声音都必须经过 `PlaybackSession`,禁止直接写 I2S。 diff --git a/assets/README.md b/assets/README.md new file mode 100644 index 0000000..ead8095 --- /dev/null +++ b/assets/README.md @@ -0,0 +1,15 @@ +# 本地提示音资源 + +`prompts/` 中的 OGG 文件是 `firmware2` 自己持有的构建输入,不引用旧 +`firmware/` 路径。 + +构建时 `gen_audio_prompts.py` 会: + +1. 校验每个文件确实是 Ogg/Opus。 +2. 校验 Ogg page 和跨 page packet 完整性。 +3. 去掉 `OpusHead` / `OpusTags`。 +4. 生成 `[帧数][帧长度][Opus 帧]...` 格式的只读 C++ 数据。 +5. 文件名不属于已知提示音分组时让构建失败。 + +生成文件位于构建目录,不提交到源码目录。增加或替换资源后重新执行 +`idf.py build` 即可。 diff --git a/assets/gen_audio_prompts.py b/assets/gen_audio_prompts.py new file mode 100644 index 0000000..6013b17 --- /dev/null +++ b/assets/gen_audio_prompts.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Generate deterministic packed-Opus prompt data for firmware2. + +The input directory may contain .ogg or .opus files, but every file must be +an Ogg/Opus container. Output format per asset: + + [frame_count:u16-le][frame_size:u16-le][frame_bytes]... + +Only the OpusHead and OpusTags packets are removed. Packet continuation across +Ogg pages is supported and malformed/truncated input fails the build. +""" + +from __future__ import annotations + +import argparse +import pathlib +import re +import struct +import sys + + +GROUPS = ( + "activation_device", + "device_already_bound", + "server_error", + "alarm_wake", + "alarm_set", + "no_network", + "wifi_config", + "wake_response", + "story_expired", + "idle_check", + "idle_goodbye", + "snore_light", + "wifi_success", + "welcome", + "shutdown", + "boot", + "error", + "low_battery_20", + "low_battery_10", + "net4g_boot_on", + "net4g_off", + "net4g_on", + "net4g_no_wifi", + *(f"digit_{digit}" for digit in range(10)), +) + + +def classify(path: pathlib.Path) -> str | None: + stem = path.stem.lower() + for group in sorted(GROUPS, key=len, reverse=True): + if stem == group or stem.startswith(group + "_"): + return group + return None + + +def parse_ogg_opus(path: pathlib.Path) -> list[bytes]: + data = path.read_bytes() + offset = 0 + packet = bytearray() + packets: list[bytes] = [] + expected_sequence = 0 + + while offset < len(data): + if len(data) - offset < 27 or data[offset : offset + 4] != b"OggS": + raise ValueError(f"{path}: malformed Ogg page at byte {offset}") + if data[offset + 4] != 0: + raise ValueError(f"{path}: unsupported Ogg version") + + sequence = struct.unpack_from(" len(data): + raise ValueError(f"{path}: truncated Ogg segment table") + + cursor = payload_start + for segment_size in data[table_start:payload_start]: + end = cursor + segment_size + if end > len(data): + raise ValueError(f"{path}: truncated Ogg page payload") + packet.extend(data[cursor:end]) + cursor = end + if segment_size < 255: + packets.append(bytes(packet)) + packet.clear() + offset = cursor + + if packet: + raise ValueError(f"{path}: unterminated packet at end of Ogg stream") + if len(packets) < 2 or not packets[0].startswith(b"OpusHead"): + marker = packets[0][:8] if packets else b"" + raise ValueError(f"{path}: not Ogg/Opus, first packet={marker!r}") + if not packets[1].startswith(b"OpusTags"): + raise ValueError(f"{path}: missing OpusTags packet") + + frames = [packet for packet in packets[2:] if packet] + if not frames: + raise ValueError(f"{path}: contains no Opus audio packets") + if len(frames) > 0xFFFF: + raise ValueError(f"{path}: too many Opus packets") + for frame in frames: + if len(frame) > 0xFFFF: + raise ValueError(f"{path}: Opus packet exceeds uint16 size") + return frames + + +def pack_frames(frames: list[bytes]) -> bytes: + output = bytearray(struct.pack(" str: + stem = re.sub(r"[^a-zA-Z0-9_]", "_", path.stem) + return f"prompt_{stem}_{index}" + + +def bytes_as_cpp(data: bytes) -> list[str]: + lines = [] + for offset in range(0, len(data), 16): + chunk = ", ".join(f"0x{value:02x}" for value in data[offset : offset + 16]) + lines.append(f" {chunk},") + return lines + + +def generate(input_dir: pathlib.Path, output: pathlib.Path) -> None: + candidates = sorted( + ( + path + for path in input_dir.iterdir() + if path.is_file() and path.suffix.lower() in {".ogg", ".opus"} + ), + key=lambda path: path.name, + ) + assets = [] + for index, path in enumerate(candidates): + group = classify(path) + if group is None: + raise ValueError(f"{path}: filename does not match a prompt group") + frames = parse_ogg_opus(path) + packed = pack_frames(frames) + assets.append((identifier(path, index), group, path.name, frames, packed)) + + if not assets: + raise ValueError(f"{input_dir}: no prompt assets found") + + lines = [ + "#pragma once", + "", + "// Generated by assets/gen_audio_prompts.py. Do not edit.", + "#include ", + "#include ", + "", + "namespace borla::generated_prompts {", + "", + "struct PromptBlob {", + " const char* group;", + " const char* filename;", + " const uint8_t* data;", + " size_t size;", + "};", + "", + ] + total = 0 + max_frame = 0 + for name, group, filename, frames, packed in assets: + lines.append( + f"// {filename}: {len(frames)} frames, {len(packed)} packed bytes" + ) + lines.append(f"static const uint8_t {name}[] = {{") + lines.extend(bytes_as_cpp(packed)) + lines.extend(("};", "")) + total += len(packed) + max_frame = max(max_frame, *(len(frame) for frame in frames)) + + lines.append("static const PromptBlob kPromptBlobs[] = {") + for name, group, filename, _frames, _packed in assets: + lines.append( + f' {{"{group}", "{filename}", {name}, sizeof({name})}},' + ) + lines.extend( + ( + "};", + "", + "static constexpr size_t kPromptBlobCount =", + " sizeof(kPromptBlobs) / sizeof(kPromptBlobs[0]);", + "", + "} // namespace borla::generated_prompts", + "", + ) + ) + + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text("\n".join(lines), encoding="utf-8") + print( + f"generated {output}: assets={len(assets)} " + f"packed={total} bytes max_frame={max_frame}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("input_dir", type=pathlib.Path) + parser.add_argument("output", type=pathlib.Path) + args = parser.parse_args() + try: + generate(args.input_dir, args.output) + except (OSError, ValueError) as error: + print(f"audio prompt generation failed: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/assets/prompts/activation_device.ogg b/assets/prompts/activation_device.ogg new file mode 100644 index 0000000..a3c8bbb Binary files /dev/null and b/assets/prompts/activation_device.ogg differ diff --git a/assets/prompts/alarm_set_1.ogg b/assets/prompts/alarm_set_1.ogg new file mode 100644 index 0000000..7d89976 Binary files /dev/null and b/assets/prompts/alarm_set_1.ogg differ diff --git a/assets/prompts/alarm_set_2.ogg b/assets/prompts/alarm_set_2.ogg new file mode 100644 index 0000000..e13916f Binary files /dev/null and b/assets/prompts/alarm_set_2.ogg differ diff --git a/assets/prompts/alarm_set_3.ogg b/assets/prompts/alarm_set_3.ogg new file mode 100644 index 0000000..1271a86 Binary files /dev/null and b/assets/prompts/alarm_set_3.ogg differ diff --git a/assets/prompts/alarm_wake_1.ogg b/assets/prompts/alarm_wake_1.ogg new file mode 100644 index 0000000..32f0255 Binary files /dev/null and b/assets/prompts/alarm_wake_1.ogg differ diff --git a/assets/prompts/alarm_wake_2.ogg b/assets/prompts/alarm_wake_2.ogg new file mode 100644 index 0000000..52964b7 Binary files /dev/null and b/assets/prompts/alarm_wake_2.ogg differ diff --git a/assets/prompts/alarm_wake_3.ogg b/assets/prompts/alarm_wake_3.ogg new file mode 100644 index 0000000..ecfce04 Binary files /dev/null and b/assets/prompts/alarm_wake_3.ogg differ diff --git a/assets/prompts/alarm_wake_4.ogg b/assets/prompts/alarm_wake_4.ogg new file mode 100644 index 0000000..4e27736 Binary files /dev/null and b/assets/prompts/alarm_wake_4.ogg differ diff --git a/assets/prompts/boot.ogg b/assets/prompts/boot.ogg new file mode 100644 index 0000000..cb7397b Binary files /dev/null and b/assets/prompts/boot.ogg differ diff --git a/assets/prompts/device_already_bound.ogg b/assets/prompts/device_already_bound.ogg new file mode 100644 index 0000000..464de8c Binary files /dev/null and b/assets/prompts/device_already_bound.ogg differ diff --git a/assets/prompts/digit_0.ogg b/assets/prompts/digit_0.ogg new file mode 100644 index 0000000..2164d60 Binary files /dev/null and b/assets/prompts/digit_0.ogg differ diff --git a/assets/prompts/digit_1.ogg b/assets/prompts/digit_1.ogg new file mode 100644 index 0000000..6e4912d Binary files /dev/null and b/assets/prompts/digit_1.ogg differ diff --git a/assets/prompts/digit_2.ogg b/assets/prompts/digit_2.ogg new file mode 100644 index 0000000..0f19028 Binary files /dev/null and b/assets/prompts/digit_2.ogg differ diff --git a/assets/prompts/digit_3.ogg b/assets/prompts/digit_3.ogg new file mode 100644 index 0000000..0d2dfb2 Binary files /dev/null and b/assets/prompts/digit_3.ogg differ diff --git a/assets/prompts/digit_4.ogg b/assets/prompts/digit_4.ogg new file mode 100644 index 0000000..83fb6dd Binary files /dev/null and b/assets/prompts/digit_4.ogg differ diff --git a/assets/prompts/digit_5.ogg b/assets/prompts/digit_5.ogg new file mode 100644 index 0000000..908d3b4 Binary files /dev/null and b/assets/prompts/digit_5.ogg differ diff --git a/assets/prompts/digit_6.ogg b/assets/prompts/digit_6.ogg new file mode 100644 index 0000000..4d5f2c5 Binary files /dev/null and b/assets/prompts/digit_6.ogg differ diff --git a/assets/prompts/digit_7.ogg b/assets/prompts/digit_7.ogg new file mode 100644 index 0000000..e452d48 Binary files /dev/null and b/assets/prompts/digit_7.ogg differ diff --git a/assets/prompts/digit_8.ogg b/assets/prompts/digit_8.ogg new file mode 100644 index 0000000..5837d54 Binary files /dev/null and b/assets/prompts/digit_8.ogg differ diff --git a/assets/prompts/digit_9.ogg b/assets/prompts/digit_9.ogg new file mode 100644 index 0000000..3872ec3 Binary files /dev/null and b/assets/prompts/digit_9.ogg differ diff --git a/assets/prompts/error_1.ogg b/assets/prompts/error_1.ogg new file mode 100644 index 0000000..686112f Binary files /dev/null and b/assets/prompts/error_1.ogg differ diff --git a/assets/prompts/error_2.ogg b/assets/prompts/error_2.ogg new file mode 100644 index 0000000..073f731 Binary files /dev/null and b/assets/prompts/error_2.ogg differ diff --git a/assets/prompts/error_3.ogg b/assets/prompts/error_3.ogg new file mode 100644 index 0000000..3605de5 Binary files /dev/null and b/assets/prompts/error_3.ogg differ diff --git a/assets/prompts/error_4.ogg b/assets/prompts/error_4.ogg new file mode 100644 index 0000000..e1168ed Binary files /dev/null and b/assets/prompts/error_4.ogg differ diff --git a/assets/prompts/idle_check.ogg b/assets/prompts/idle_check.ogg new file mode 100644 index 0000000..28590d8 Binary files /dev/null and b/assets/prompts/idle_check.ogg differ diff --git a/assets/prompts/idle_goodbye.ogg b/assets/prompts/idle_goodbye.ogg new file mode 100644 index 0000000..a9d1412 Binary files /dev/null and b/assets/prompts/idle_goodbye.ogg differ diff --git a/assets/prompts/low_battery_10.ogg b/assets/prompts/low_battery_10.ogg new file mode 100644 index 0000000..beea25d Binary files /dev/null and b/assets/prompts/low_battery_10.ogg differ diff --git a/assets/prompts/low_battery_20.ogg b/assets/prompts/low_battery_20.ogg new file mode 100644 index 0000000..cd004a4 Binary files /dev/null and b/assets/prompts/low_battery_20.ogg differ diff --git a/assets/prompts/net4g_boot_on.ogg b/assets/prompts/net4g_boot_on.ogg new file mode 100644 index 0000000..ed0287b Binary files /dev/null and b/assets/prompts/net4g_boot_on.ogg differ diff --git a/assets/prompts/net4g_no_wifi.ogg b/assets/prompts/net4g_no_wifi.ogg new file mode 100644 index 0000000..75a7545 Binary files /dev/null and b/assets/prompts/net4g_no_wifi.ogg differ diff --git a/assets/prompts/net4g_off.ogg b/assets/prompts/net4g_off.ogg new file mode 100644 index 0000000..7f5ca4e Binary files /dev/null and b/assets/prompts/net4g_off.ogg differ diff --git a/assets/prompts/net4g_on.ogg b/assets/prompts/net4g_on.ogg new file mode 100644 index 0000000..77a1587 Binary files /dev/null and b/assets/prompts/net4g_on.ogg differ diff --git a/assets/prompts/no_network.ogg b/assets/prompts/no_network.ogg new file mode 100644 index 0000000..4219990 Binary files /dev/null and b/assets/prompts/no_network.ogg differ diff --git a/assets/prompts/server_error_1.ogg b/assets/prompts/server_error_1.ogg new file mode 100644 index 0000000..f6957c5 Binary files /dev/null and b/assets/prompts/server_error_1.ogg differ diff --git a/assets/prompts/server_error_2.ogg b/assets/prompts/server_error_2.ogg new file mode 100644 index 0000000..c7e00bc Binary files /dev/null and b/assets/prompts/server_error_2.ogg differ diff --git a/assets/prompts/shutdown.ogg b/assets/prompts/shutdown.ogg new file mode 100644 index 0000000..7df55f7 Binary files /dev/null and b/assets/prompts/shutdown.ogg differ diff --git a/assets/prompts/snore_light.ogg b/assets/prompts/snore_light.ogg new file mode 100644 index 0000000..b8121e3 Binary files /dev/null and b/assets/prompts/snore_light.ogg differ diff --git a/assets/prompts/story_expired.ogg b/assets/prompts/story_expired.ogg new file mode 100644 index 0000000..0eb64c9 Binary files /dev/null and b/assets/prompts/story_expired.ogg differ diff --git a/assets/prompts/wake_response.ogg b/assets/prompts/wake_response.ogg new file mode 100644 index 0000000..3abfa1c Binary files /dev/null and b/assets/prompts/wake_response.ogg differ diff --git a/assets/prompts/welcome_1.ogg b/assets/prompts/welcome_1.ogg new file mode 100644 index 0000000..b6682d0 Binary files /dev/null and b/assets/prompts/welcome_1.ogg differ diff --git a/assets/prompts/welcome_2.ogg b/assets/prompts/welcome_2.ogg new file mode 100644 index 0000000..559912e Binary files /dev/null and b/assets/prompts/welcome_2.ogg differ diff --git a/assets/prompts/welcome_3.ogg b/assets/prompts/welcome_3.ogg new file mode 100644 index 0000000..89e13ca Binary files /dev/null and b/assets/prompts/welcome_3.ogg differ diff --git a/assets/prompts/welcome_4.ogg b/assets/prompts/welcome_4.ogg new file mode 100644 index 0000000..37b5155 Binary files /dev/null and b/assets/prompts/welcome_4.ogg differ diff --git a/assets/prompts/wifi_config.ogg b/assets/prompts/wifi_config.ogg new file mode 100644 index 0000000..b9ee448 Binary files /dev/null and b/assets/prompts/wifi_config.ogg differ diff --git a/assets/prompts/wifi_success.ogg b/assets/prompts/wifi_success.ogg new file mode 100644 index 0000000..88f68e9 Binary files /dev/null and b/assets/prompts/wifi_success.ogg differ diff --git a/build_diag.log b/build_diag.log new file mode 100644 index 0000000..eff7173 --- /dev/null +++ b/build_diag.log @@ -0,0 +1,1857 @@ +Executing action: all (aliases: build) +Running ninja in directory D:\4_Program\firmware2_9\build +Executing "ninja all"... +[0/1] Re-running CMake... +-- ccache will be used for faster recompilation +-- Building ESP-IDF components for target esp32s3 +NOTICE: +Following dependencies have new versions available: +Dependency "espressif/dl_fft": "0.6.0" -> "0.7.0" +Consider running "idf.py update-dependencies" to update your lock file. +NOTICE: Processing 12 dependencies: +NOTICE: [1/12] 78/esp-opus (1.0.5) +NOTICE: [2/12] espressif/button (4.1.3) +NOTICE: [3/12] espressif/cjson (1.7.19~2) +NOTICE: [4/12] espressif/cmake_utilities (1.1.1) +NOTICE: [5/12] espressif/dl_fft (0.6.0) +NOTICE: [6/12] espressif/esp-dl (3.3.11) +NOTICE: [7/12] espressif/esp-dsp (1.8.0) +NOTICE: [8/12] espressif/esp-sr (2.5.0) +NOTICE: [9/12] espressif/esp_codec_dev (1.4.0) +NOTICE: [10/12] espressif/esp_new_jpeg (1.0.2) +NOTICE: [11/12] espressif/led_strip (3.0.3) +NOTICE: [12/12] idf (5.4.3) +-- CONFIG_ESP32P4_SELECTS_REV_LESS_V3 is +-- IDF_VERSION_MAJOR is 5 +-- IDF_VERSION_MINOR is 4 +-- IDF_VERSION_PATCH is 3 +-- TARGET_LIB_PATH is set to: esp32s3 +-- Project sdkconfig file D:/4_Program/firmware2_9/sdkconfig +Loading defaults file D:/4_Program/firmware2_9/sdkconfig.defaults... +-- Compiler supported targets: xtensa-esp-elf +-- USING O3 +-- App "borla-firmware2" version: 2.0.0-dev +-- Adding linker script D:/4_Program/firmware2_9/build/esp-idf/esp_system/ld/memory.ld +-- Adding linker script D:/4_Program/firmware2_9/build/esp-idf/esp_system/ld/sections.ld.in +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.api.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.bt_funcs.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.libgcc.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.wdt.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.version.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.ble_cca.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.ble_test.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.newlib.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/soc/esp32s3/ld/esp32s3.peripherals.ld +-- BUTTON: 4.1.3 +-- CONFIG_ESP32P4_SELECTS_REV_LESS_V3 is +-- IDF_VERSION_MAJOR is 5 +-- IDF_VERSION_MINOR is 4 +-- IDF_VERSION_PATCH is 3 +-- TARGET_LIB_PATH is set to: esp32s3 +-- Components: 78__esp-opus app_trace app_update bootloader bootloader_support bt cmock console cxx driver efuse esp-tls esp_adc esp_app_format esp_bootloader_format esp_coex esp_common esp_driver_ana_cmpr esp_driver_cam esp_driver_dac esp_driver_gpio esp_driver_gptimer esp_driver_i2c esp_driver_i2s esp_driver_isp esp_driver_jpeg esp_driver_ledc esp_driver_mcpwm esp_driver_parlio esp_driver_pcnt esp_driver_ppa esp_driver_rmt esp_driver_sdio esp_driver_sdm esp_driver_sdmmc esp_driver_sdspi esp_driver_spi esp_driver_touch_sens esp_driver_tsens esp_driver_uart esp_driver_usb_serial_jtag esp_eth esp_event esp_gdbstub esp_hid esp_http_client esp_http_server esp_https_ota esp_https_server esp_hw_support esp_lcd esp_local_ctrl esp_mm esp_netif esp_netif_stack esp_partition esp_phy esp_pm esp_psram esp_ringbuf esp_rom esp_security esp_system esp_timer esp_vfs_console esp_wifi espcoredump espressif__button espressif__cjson espressif__cmake_utilities espressif__dl_fft espressif__esp-dl espressif__esp-dsp espressif__esp-sr espressif__esp_codec_dev espressif__esp_new_jpeg espressif__led_strip esptool_py fatfs freertos hal heap http_parser idf_test ieee802154 json log lwip main mbedtls mqtt newlib nvs_flash nvs_sec_provider openthread partition_table perfmon protobuf-c protocomm pthread rt sdmmc soc spi_flash spiffs tcp_transport touch_element ulp unity usb vfs wear_levelling wifi_provisioning wpa_supplicant xtensa +-- Component paths: D:/4_Program/firmware2_9/managed_components/78__esp-opus D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/app_trace D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/app_update D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader_support D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bt D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/cmock D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/console D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/cxx D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/driver D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/efuse D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp-tls D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_adc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_app_format D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_bootloader_format D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_coex D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_common D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_ana_cmpr D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_cam D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_dac D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_gpio D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_gptimer D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_i2c D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_i2s D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_isp D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_jpeg D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_ledc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_mcpwm D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_parlio D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_pcnt D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_ppa D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_rmt D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_sdio D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_sdm D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_sdmmc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_sdspi D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_spi D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_touch_sens D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_tsens D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_uart D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_driver_usb_serial_jtag D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_eth D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_event D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_gdbstub D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_hid D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_http_client D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_http_server D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_https_ota D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_https_server D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_hw_support D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_lcd D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_local_ctrl D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_mm D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_netif D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_netif_stack D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_partition D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_phy D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_pm D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_psram D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_ringbuf D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_security D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_system D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_timer D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_vfs_console D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_wifi D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/espcoredump D:/4_Program/firmware2_9/managed_components/espressif__button D:/4_Program/firmware2_9/managed_components/espressif__cjson D:/4_Program/firmware2_9/managed_components/espressif__cmake_utilities D:/4_Program/firmware2_9/managed_components/espressif__dl_fft D:/4_Program/firmware2_9/managed_components/espressif__esp-dl D:/4_Program/firmware2_9/managed_components/espressif__esp-dsp D:/4_Program/firmware2_9/managed_components/espressif__esp-sr D:/4_Program/firmware2_9/managed_components/espressif__esp_codec_dev D:/4_Program/firmware2_9/managed_components/espressif__esp_new_jpeg D:/4_Program/firmware2_9/managed_components/espressif__led_strip D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esptool_py D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/fatfs D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/freertos D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/hal D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/heap D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/http_parser D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/idf_test D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/ieee802154 D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/json D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/log D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/lwip D:/4_Program/firmware2_9/main D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/mqtt D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/newlib D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/nvs_flash D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/nvs_sec_provider D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/openthread D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/partition_table D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/perfmon D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/protobuf-c D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/protocomm D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/pthread D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/rt D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/sdmmc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/soc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/spi_flash D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/spiffs D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/tcp_transport D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/touch_element D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/ulp D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/unity D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/usb D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/vfs D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/wear_levelling D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/wifi_provisioning D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/wpa_supplicant D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/xtensa +-- Configuring done (12.0s) +-- Generating done (1.1s) +-- Build files have been written to: D:/4_Program/firmware2_9/build +[1/1743] Building C object esp-idf/esp_http_client/CMakeFiles/__idf_esp_http_client.dir/lib/http_utils.c.obj +[2/1743] Building C object esp-idf/esp_psram/CMakeFiles/__idf_esp_psram.dir/esp_psram.c.obj +[3/1743] Building C object esp-idf/tcp_transport/CMakeFiles/__idf_tcp_transport.dir/transport_socks_proxy.c.obj +[4/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/httpd_uri.c.obj +[5/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/util/ctrl_sock.c.obj +[6/1743] Building C object esp-idf/esp_http_client/CMakeFiles/__idf_esp_http_client.dir/lib/http_auth.c.obj +[7/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/httpd_ws.c.obj +[8/1743] Building C object esp-idf/tcp_transport/CMakeFiles/__idf_tcp_transport.dir/transport_internal.c.obj +[9/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/httpd_parse.c.obj +[10/1743] Building C object esp-idf/esp_http_client/CMakeFiles/__idf_esp_http_client.dir/lib/http_header.c.obj +[11/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/httpd_sess.c.obj +[12/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/httpd_txrx.c.obj +[13/1743] Building C object esp-idf/esp_https_ota/CMakeFiles/__idf_esp_https_ota.dir/src/esp_https_ota.c.obj +[14/1743] Building C object esp-idf/esp_psram/CMakeFiles/__idf_esp_psram.dir/mmu_psram_flash.c.obj +[15/1743] Building C object esp-idf/tcp_transport/CMakeFiles/__idf_tcp_transport.dir/transport.c.obj +[16/1743] Building C object esp-idf/esp_http_server/CMakeFiles/__idf_esp_http_server.dir/src/httpd_main.c.obj +[17/1743] Building C object esp-idf/tcp_transport/CMakeFiles/__idf_tcp_transport.dir/transport_ssl.c.obj +[18/1743] Building C object esp-idf/tcp_transport/CMakeFiles/__idf_tcp_transport.dir/transport_ws.c.obj +[19/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_cali.c.obj +[20/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/deprecated/esp_adc_cal_common_legacy.c.obj +[21/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/esp32s3/curve_fitting_coefficients.c.obj +[22/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_cali_curve_fitting.c.obj +[23/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/deprecated/esp32s3/esp_adc_cal_legacy.c.obj +[24/1743] Building C object esp-idf/esp_http_client/CMakeFiles/__idf_esp_http_client.dir/esp_http_client.c.obj +[25/1743] Building C object esp-idf/esp-tls/CMakeFiles/__idf_esp-tls.dir/esp-tls-crypto/esp_tls_crypto.c.obj +[26/1743] Building C object esp-idf/esp-tls/CMakeFiles/__idf_esp-tls.dir/esp_tls_platform_port.c.obj +[27/1743] Building C object esp-idf/esp_psram/CMakeFiles/__idf_esp_psram.dir/esp32s3/esp_psram_impl_octal.c.obj +[28/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_oneshot.c.obj +[29/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_filter.c.obj +[30/1743] Building C object esp-idf/esp-tls/CMakeFiles/__idf_esp-tls.dir/esp_tls_error_capture.c.obj +[31/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_monitor.c.obj +[32/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_continuous.c.obj +[33/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/gdma/adc_dma.c.obj +[34/1743] Building C object esp-idf/esp_adc/CMakeFiles/__idf_esp_adc.dir/adc_common.c.obj +[35/1743] Building C object esp-idf/esp-tls/CMakeFiles/__idf_esp-tls.dir/esp_tls.c.obj +[36/1743] Building C object esp-idf/esp_gdbstub/CMakeFiles/__idf_esp_gdbstub.dir/src/port/xtensa/gdbstub_xtensa.c.obj +[37/1743] Building C object esp-idf/esp_gdbstub/CMakeFiles/__idf_esp_gdbstub.dir/src/gdbstub_transport.c.obj +[38/1743] Building ASM object esp-idf/esp_gdbstub/CMakeFiles/__idf_esp_gdbstub.dir/src/port/xtensa/gdbstub-entry.S.obj +[39/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/lib_printf.c.obj +[40/1743] Building ASM object esp-idf/esp_gdbstub/CMakeFiles/__idf_esp_gdbstub.dir/src/port/xtensa/xt_debugexception.S.obj +[41/1743] Building C object esp-idf/esp_gdbstub/CMakeFiles/__idf_esp_gdbstub.dir/src/gdbstub.c.obj +[42/1743] Building C object esp-idf/esp_gdbstub/CMakeFiles/__idf_esp_gdbstub.dir/src/packet.c.obj +[43/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/mesh_event.c.obj +[44/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/wifi_default_ap.c.obj +[45/1743] Building C object esp-idf/esp-tls/CMakeFiles/__idf_esp-tls.dir/esp_tls_mbedtls.c.obj +[46/1743] Building C object esp-idf/esp_coex/CMakeFiles/__idf_esp_coex.dir/src/coexist_debug_diagram.c.obj +[47/1743] Building C object esp-idf/esp_coex/CMakeFiles/__idf_esp_coex.dir/src/coexist.c.obj +[48/1743] Building C object esp-idf/http_parser/CMakeFiles/__idf_http_parser.dir/http_parser.c.obj +[49/1743] Building C object esp-idf/esp_coex/CMakeFiles/__idf_esp_coex.dir/src/coexist_debug.c.obj +[50/1743] Building C object esp-idf/esp_coex/CMakeFiles/__idf_esp_coex.dir/src/lib_printf.c.obj +[51/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/wifi_init.c.obj +[52/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/smartconfig.c.obj +[53/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/wifi_netif.c.obj +[54/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/wifi_default.c.obj +[55/1743] Building C object esp-idf/esp_coex/CMakeFiles/__idf_esp_coex.dir/esp32s3/esp_coex_adapter.c.obj +[56/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/src/smartconfig_ack.c.obj +[57/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/port/os_xtensa.c.obj +[58/1743] Building C object esp-idf/esp_wifi/CMakeFiles/__idf_esp_wifi.dir/esp32s3/esp_adapter.c.obj +[59/1743] Linking C static library esp-idf\esp_https_ota\libesp_https_ota.a +[60/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/port/eloop.c.obj +[61/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/ap_config.c.obj +[62/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/common/dragonfly.c.obj +[63/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/ieee802_1x.c.obj +[64/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/comeback_token.c.obj +[65/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/pmksa_cache_auth.c.obj +[66/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/wpa_auth_ie.c.obj +[67/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/sta_info.c.obj +[68/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/bitfield.c.obj +[69/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/ieee802_11.c.obj +[70/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/aes-siv.c.obj +[71/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/common/wpa_common.c.obj +[72/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/ap/wpa_auth.c.obj +[73/1743] Linking C static library esp-idf\esp_http_server\libesp_http_server.a +[74/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha256-kdf.c.obj +[75/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/aes-gcm.c.obj +[76/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/ccmp.c.obj +[77/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/dh_group5.c.obj +[78/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/crypto_ops.c.obj +[79/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/dh_groups.c.obj +[80/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/common/sae.c.obj +[81/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/ms_funcs.c.obj +[82/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha1-tlsprf.c.obj +[83/1743] Linking C static library esp-idf\esp_http_client\libesp_http_client.a +[84/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha256-tlsprf.c.obj +[85/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha256-prf.c.obj +[86/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha384-tlsprf.c.obj +[87/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha384-prf.c.obj +[88/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/md4-internal.c.obj +[89/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha1-prf.c.obj +[90/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/sha1-tprf.c.obj +[91/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_common/eap_wsc_common.c.obj +[92/1743] Linking C static library esp-idf\tcp_transport\libtcp_transport.a +[93/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/chap.c.obj +[94/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/common/ieee802_11_common.c.obj +[95/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_common.c.obj +[96/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_peap_common.c.obj +[97/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap.c.obj +[98/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_peap.c.obj +[99/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_mschapv2.c.obj +[100/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_tls.c.obj +[101/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/mschapv2.c.obj +[102/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_fast_common.c.obj +[103/1743] Linking C static library esp-idf\esp_psram\libesp_psram.a +[104/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_tls_common.c.obj +[105/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/rsn_supp/pmksa_cache.c.obj +[106/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_fast_pac.c.obj +[107/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_ttls.c.obj +[108/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/rsn_supp/wpa_ie.c.obj +[109/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/ext_password.c.obj +[110/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/eap_peer/eap_fast.c.obj +[111/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/base64.c.obj +[112/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/uuid.c.obj +[113/1743] Linking C static library esp-idf\esp_adc\libesp_adc.a +[114/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/common.c.obj +[115/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/wpa_debug.c.obj +[116/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/wpabuf.c.obj +[117/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/rsn_supp/wpa.c.obj +[118/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps.c.obj +[119/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps_attr_parse.c.obj +[120/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps_attr_process.c.obj +[121/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps_attr_build.c.obj +[122/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/utils/json.c.obj +[123/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_wpa2_api_port.c.obj +[124/1743] Linking C static library esp-idf\esp-tls\libesp-tls.a +[125/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps_dev_attr.c.obj +[126/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps_common.c.obj +[127/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_wpas_glue.c.obj +[128/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/common/sae_pk.c.obj +[129/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_wpa_main.c.obj +[130/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_owe.c.obj +[131/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/wps/wps_enrollee.c.obj +[132/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_common.c.obj +[133/1743] Linking C static library esp-idf\http_parser\libhttp_parser.a +[134/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_wpa3.c.obj +[135/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_eap_client.c.obj +[136/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_hostap.c.obj +[137/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/fastpsk.c.obj +[138/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/esp_wps.c.obj +[139/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/crypto_mbedtls-bignum.c.obj +[140/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/crypto_mbedtls.c.obj +[141/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/crypto_mbedtls-rsa.c.obj +[142/1743] Linking C static library esp-idf\esp_gdbstub\libesp_gdbstub.a +[143/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/esp_netif_objects.c.obj +[144/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/esp_netif_handlers.c.obj +[145/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/tls_mbedtls.c.obj +[146/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/aes-wrap.c.obj +[147/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/fastpbkdf2.c.obj +[148/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/esp_netif_defaults.c.obj +[149/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/aes-unwrap.c.obj +[150/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/rc4.c.obj +[151/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/esp_supplicant/src/crypto/crypto_mbedtls-ec.c.obj +[152/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/des-internal.c.obj +[153/1743] Building C object esp-idf/wpa_supplicant/CMakeFiles/__idf_wpa_supplicant.dir/src/crypto/aes-ccm.c.obj +[154/1743] Linking C static library esp-idf\esp_wifi\libesp_wifi.a +[155/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/esp_netif_lwip_defaults.c.obj +[156/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/netif/wlanif.c.obj +[157/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/esp_netif_sntp.c.obj +[158/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/netif/ethernetif.c.obj +[159/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/netif/esp_pbuf_ref.c.obj +[160/1743] Linking C static library esp-idf\esp_coex\libesp_coex.a +[161/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/err.c.obj +[162/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/apps/sntp/sntp.c.obj +[163/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/if_api.c.obj +[164/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/netif/ppp.c.obj +[165/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/netifapi.c.obj +[166/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/netbuf.c.obj +[167/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/netdb.c.obj +[168/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/api_lib.c.obj +[169/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/api_msg.c.obj +[170/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/esp_netif_lwip_ppp.c.obj +[171/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/tcpip.c.obj +[172/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/apps/sntp/sntp.c.obj +[173/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/def.c.obj +[174/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/apps/netbiosns/netbiosns.c.obj +[175/1743] Linking C static library esp-idf\wpa_supplicant\libwpa_supplicant.a +[176/1743] Building C object esp-idf/esp_netif/CMakeFiles/__idf_esp_netif.dir/lwip/esp_netif_lwip.c.obj +[177/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/init.c.obj +[178/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/inet_chksum.c.obj +[179/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/mem.c.obj +[180/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ip.c.obj +[181/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/dns.c.obj +[182/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/memp.c.obj +[183/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/sys.c.obj +[184/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/api/sockets.c.obj +[185/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/raw.c.obj +[186/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/pbuf.c.obj +[187/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/stats.c.obj +[188/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/netif.c.obj +[189/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/autoip.c.obj +[190/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/timeouts.c.obj +[191/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/ip4_napt.c.obj +[192/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/icmp.c.obj +[193/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/udp.c.obj +[194/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/tcp_in.c.obj +[195/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/tcp.c.obj +[196/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/tcp_out.c.obj +[197/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/etharp.c.obj +[198/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/igmp.c.obj +[199/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/ip4.c.obj +[200/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/ethip6.c.obj +[201/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/dhcp6.c.obj +[202/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/ip4_frag.c.obj +[203/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/ip4_addr.c.obj +[204/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/inet6.c.obj +[205/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv4/dhcp.c.obj +[206/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/icmp6.c.obj +[207/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/ip6_addr.c.obj +[208/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/ip6_frag.c.obj +[209/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ethernet.c.obj +[210/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/auth.c.obj +[211/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/ip6.c.obj +[212/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/bridgeif_fdb.c.obj +[213/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/chap-md5.c.obj +[214/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/slipif.c.obj +[215/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/mld6.c.obj +[216/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/ccp.c.obj +[217/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/chap-new.c.obj +[218/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/bridgeif.c.obj +[219/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/demand.c.obj +[220/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/chap_ms.c.obj +[221/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/ecp.c.obj +[222/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/eap.c.obj +[223/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/eui64.c.obj +[224/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/core/ipv6/nd6.c.obj +[225/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/fsm.c.obj +[226/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/ipv6cp.c.obj +[227/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/mppe.c.obj +[228/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/magic.c.obj +[229/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/multilink.c.obj +[230/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/pppcrypt.c.obj +[231/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/upap.c.obj +[232/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/pppapi.c.obj +[233/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/ppp.c.obj +[234/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/pppol2tp.c.obj +[235/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/pppoe.c.obj +[236/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/ipcp.c.obj +[237/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/pppos.c.obj +[238/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/hooks/tcp_isn_default.c.obj +[239/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/lcp.c.obj +[240/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/vj.c.obj +[241/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/hooks/lwip_default_hooks.c.obj +[242/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/utils.c.obj +[243/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/acd_dhcp_check.c.obj +[244/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/sockets_ext.c.obj +[245/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/debug/lwip_debug.c.obj +[246/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/polarssl/arc4.c.obj +[247/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/esp32xx/vfs_lwip.c.obj +[248/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/polarssl/des.c.obj +[249/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/port/freertos/sys_arch.c.obj +[250/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/apps/ping/esp_ping.c.obj +[251/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/polarssl/sha1.c.obj +[252/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/apps/ping/ping.c.obj +[253/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/polarssl/md5.c.obj +[254/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/lwip/src/netif/ppp/polarssl/md4.c.obj +[255/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/apps/ping/ping_sock.c.obj +[256/1743] Linking C static library esp-idf\esp_netif\libesp_netif.a +[257/1743] Building C object esp-idf/vfs/CMakeFiles/__idf_vfs.dir/vfs_eventfd.c.obj +[258/1743] Building C object esp-idf/esp_phy/CMakeFiles/__idf_esp_phy.dir/src/phy_override.c.obj +[259/1743] Building C object esp-idf/lwip/CMakeFiles/__idf_lwip.dir/apps/dhcpserver/dhcpserver.c.obj +[260/1743] Building C object esp-idf/esp_phy/CMakeFiles/__idf_esp_phy.dir/src/lib_printf.c.obj +[261/1743] Building C object esp-idf/esp_phy/CMakeFiles/__idf_esp_phy.dir/esp32s3/phy_init_data.c.obj +[262/1743] Building C object esp-idf/vfs/CMakeFiles/__idf_vfs.dir/vfs_semihost.c.obj +[263/1743] Building C object esp-idf/esp_phy/CMakeFiles/__idf_esp_phy.dir/src/phy_common.c.obj +[264/1743] Building C object esp-idf/esp_vfs_console/CMakeFiles/__idf_esp_vfs_console.dir/vfs_console.c.obj +[265/1743] Building C object esp-idf/esp_phy/CMakeFiles/__idf_esp_phy.dir/src/btbb_init.c.obj +[266/1743] Building C object esp-idf/vfs/CMakeFiles/__idf_vfs.dir/nullfs.c.obj +[267/1743] Building C object esp-idf/esp_phy/CMakeFiles/__idf_esp_phy.dir/src/phy_init.c.obj +[268/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/adc_dma_legacy.c.obj +[269/1743] Building C object esp-idf/vfs/CMakeFiles/__idf_vfs.dir/vfs.c.obj +[270/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/adc_legacy.c.obj +[271/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/timer_legacy.c.obj +[272/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/sigma_delta_legacy.c.obj +[273/1743] Linking C static library esp-idf\lwip\liblwip.a +[274/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/rtc_temperature_legacy.c.obj +[275/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/touch_sensor/touch_sensor_common.c.obj +[276/1743] Building C object esp-idf/esp_driver_usb_serial_jtag/CMakeFiles/__idf_esp_driver_usb_serial_jtag.dir/src/usb_serial_jtag.c.obj +[277/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/mcpwm_legacy.c.obj +[278/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/pcnt_legacy.c.obj +[279/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/i2s_legacy.c.obj +[280/1743] Building C object esp-idf/esp_driver_usb_serial_jtag/CMakeFiles/__idf_esp_driver_usb_serial_jtag.dir/src/usb_serial_jtag_connection_monitor.c.obj +[281/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/i2c/i2c.c.obj +[282/1743] Linking C static library esp-idf\vfs\libvfs.a +[283/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/touch_sensor/esp32s3/touch_sensor.c.obj +[284/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/twai/twai.c.obj +[285/1743] Building C object esp-idf/esp_driver_i2c/CMakeFiles/__idf_esp_driver_i2c.dir/i2c_common.c.obj +[286/1743] Building C object esp-idf/esp_driver_usb_serial_jtag/CMakeFiles/__idf_esp_driver_usb_serial_jtag.dir/src/usb_serial_jtag_vfs.c.obj +[287/1743] Linking C static library esp-idf\esp_vfs_console\libesp_vfs_console.a +[288/1743] Building C object esp-idf/esp_driver_i2c/CMakeFiles/__idf_esp_driver_i2c.dir/i2c_slave.c.obj +[289/1743] Building C object esp-idf/esp_driver_sdspi/CMakeFiles/__idf_esp_driver_sdspi.dir/src/sdspi_crc.c.obj +[290/1743] Building C object esp-idf/driver/CMakeFiles/__idf_driver.dir/deprecated/rmt_legacy.c.obj +[291/1743] Building C object esp-idf/esp_driver_tsens/CMakeFiles/__idf_esp_driver_tsens.dir/src/temperature_sensor.c.obj +[292/1743] Building C object esp-idf/esp_driver_sdm/CMakeFiles/__idf_esp_driver_sdm.dir/src/sdm.c.obj +[293/1743] Building C object esp-idf/esp_driver_rmt/CMakeFiles/__idf_esp_driver_rmt.dir/src/rmt_common.c.obj +[294/1743] Building C object esp-idf/esp_driver_rmt/CMakeFiles/__idf_esp_driver_rmt.dir/src/rmt_encoder.c.obj +[295/1743] Building C object esp-idf/esp_driver_i2c/CMakeFiles/__idf_esp_driver_i2c.dir/i2c_master.c.obj +[296/1743] Linking C static library esp-idf\esp_phy\libesp_phy.a +[297/1743] Building C object esp-idf/esp_driver_sdspi/CMakeFiles/__idf_esp_driver_sdspi.dir/src/sdspi_transaction.c.obj +[298/1743] Building C object esp-idf/esp_driver_ledc/CMakeFiles/__idf_esp_driver_ledc.dir/src/ledc.c.obj +[299/1743] Building C object esp-idf/esp_driver_sdspi/CMakeFiles/__idf_esp_driver_sdspi.dir/src/sdspi_host.c.obj +[300/1743] Building C object esp-idf/esp_driver_rmt/CMakeFiles/__idf_esp_driver_rmt.dir/src/rmt_rx.c.obj +[301/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sd_pwr_ctrl/sd_pwr_ctrl.c.obj +[302/1743] Building C object esp-idf/esp_driver_sdmmc/CMakeFiles/__idf_esp_driver_sdmmc.dir/src/sdmmc_transaction.c.obj +[303/1743] Building C object esp-idf/esp_driver_rmt/CMakeFiles/__idf_esp_driver_rmt.dir/src/rmt_tx.c.obj +[304/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sdmmc_init.c.obj +[305/1743] Linking C static library esp-idf\driver\libdriver.a +[306/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sdmmc_mmc.c.obj +[307/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sdmmc_cmd.c.obj +[308/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sdmmc_common.c.obj +[309/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sdmmc_io.c.obj +[310/1743] Linking C static library esp-idf\esp_driver_usb_serial_jtag\libesp_driver_usb_serial_jtag.a +[311/1743] Building C object esp-idf/esp_driver_sdmmc/CMakeFiles/__idf_esp_driver_sdmmc.dir/src/sdmmc_host.c.obj +[312/1743] Building C object esp-idf/esp_driver_i2s/CMakeFiles/__idf_esp_driver_i2s.dir/i2s_std.c.obj +[313/1743] Building C object esp-idf/sdmmc/CMakeFiles/__idf_sdmmc.dir/sdmmc_sd.c.obj +[314/1743] Building C object esp-idf/esp_driver_i2s/CMakeFiles/__idf_esp_driver_i2s.dir/i2s_platform.c.obj +[315/1743] Building C object esp-idf/esp_driver_i2s/CMakeFiles/__idf_esp_driver_i2s.dir/i2s_tdm.c.obj +[316/1743] Building C object esp-idf/esp_driver_i2s/CMakeFiles/__idf_esp_driver_i2s.dir/i2s_common.c.obj +[317/1743] Building C object esp-idf/esp_driver_i2s/CMakeFiles/__idf_esp_driver_i2s.dir/i2s_pdm.c.obj +[318/1743] Linking C static library esp-idf\esp_driver_ledc\libesp_driver_ledc.a +[319/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_fault.c.obj +[320/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_cmpr.c.obj +[321/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_oper.c.obj +[322/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_cap.c.obj +[323/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_com.c.obj +[324/1743] Linking C static library esp-idf\esp_driver_i2c\libesp_driver_i2c.a +[325/1743] Building C object esp-idf/esp_driver_spi/CMakeFiles/__idf_esp_driver_spi.dir/src/gpspi/spi_dma.c.obj +[326/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_gen.c.obj +[327/1743] Linking C static library esp-idf\esp_driver_sdm\libesp_driver_sdm.a +[328/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_sync.c.obj +[329/1743] Linking C static library esp-idf\esp_driver_tsens\libesp_driver_tsens.a +[330/1743] Building C object esp-idf/esp_driver_mcpwm/CMakeFiles/__idf_esp_driver_mcpwm.dir/src/mcpwm_timer.c.obj +[331/1743] Building C object esp-idf/esp_driver_spi/CMakeFiles/__idf_esp_driver_spi.dir/src/gpspi/spi_slave.c.obj +[332/1743] Building C object esp-idf/esp_driver_spi/CMakeFiles/__idf_esp_driver_spi.dir/src/gpspi/spi_common.c.obj +[333/1743] Linking C static library esp-idf\esp_driver_rmt\libesp_driver_rmt.a +[334/1743] Building C object esp-idf/esp_driver_pcnt/CMakeFiles/__idf_esp_driver_pcnt.dir/src/pulse_cnt.c.obj +[335/1743] Building C object esp-idf/esp_driver_spi/CMakeFiles/__idf_esp_driver_spi.dir/src/gpspi/spi_slave_hd.c.obj +[336/1743] Linking C static library esp-idf\esp_driver_sdspi\libesp_driver_sdspi.a +[337/1743] Building C object esp-idf/esp_driver_spi/CMakeFiles/__idf_esp_driver_spi.dir/src/gpspi/spi_master.c.obj +[338/1743] Linking C static library esp-idf\esp_driver_sdmmc\libesp_driver_sdmmc.a +[339/1743] Linking C static library esp-idf\sdmmc\libsdmmc.a +[340/1743] Building C object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_bootloader.c.obj +[341/1743] Building C object esp-idf/esp_event/CMakeFiles/__idf_esp_event.dir/default_event_loop.c.obj +[342/1743] Linking C static library esp-idf\esp_driver_i2s\libesp_driver_i2s.a +[343/1743] Linking C static library esp-idf\esp_driver_mcpwm\libesp_driver_mcpwm.a +[344/1743] Building C object esp-idf/esp_event/CMakeFiles/__idf_esp_event.dir/esp_event.c.obj +[345/1743] Building C object esp-idf/esp_event/CMakeFiles/__idf_esp_event.dir/esp_event_private.c.obj +[346/1743] Linking C static library esp-idf\esp_driver_spi\libesp_driver_spi.a +[347/1743] Linking C static library esp-idf\esp_driver_pcnt\libesp_driver_pcnt.a +[348/1743] Building C object esp-idf/esp_driver_uart/CMakeFiles/__idf_esp_driver_uart.dir/src/uart_vfs.c.obj +[349/1743] Building C object esp-idf/esp_driver_uart/CMakeFiles/__idf_esp_driver_uart.dir/src/uhci.c.obj +[350/1743] Building C object esp-idf/esp_ringbuf/CMakeFiles/__idf_esp_ringbuf.dir/ringbuf.c.obj +[351/1743] Building C object esp-idf/esp_driver_uart/CMakeFiles/__idf_esp_driver_uart.dir/src/uart.c.obj +[352/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_platform.cpp.obj +[353/1743] Building C object esp-idf/esp_timer/CMakeFiles/__idf_esp_timer.dir/src/esp_timer_init.c.obj +[354/1743] Building C object esp-idf/esp_driver_gptimer/CMakeFiles/__idf_esp_driver_gptimer.dir/src/gptimer_common.c.obj +[355/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_partition.cpp.obj +[356/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_partition_lookup.cpp.obj +[357/1743] Building C object esp-idf/esp_driver_gptimer/CMakeFiles/__idf_esp_driver_gptimer.dir/src/gptimer.c.obj +[358/1743] Building C object esp-idf/esp_timer/CMakeFiles/__idf_esp_timer.dir/src/ets_timer_legacy.c.obj +[359/1743] Building C object esp-idf/esp_timer/CMakeFiles/__idf_esp_timer.dir/src/esp_timer.c.obj +[360/1743] Building C object esp-idf/esp_timer/CMakeFiles/__idf_esp_timer.dir/src/esp_timer_impl_common.c.obj +[361/1743] Building C object esp-idf/esp_timer/CMakeFiles/__idf_esp_timer.dir/src/system_time.c.obj +[362/1743] Building C object esp-idf/esp_timer/CMakeFiles/__idf_esp_timer.dir/src/esp_timer_impl_systimer.c.obj +[363/1743] Building CXX object esp-idf/cxx/CMakeFiles/__idf_cxx.dir/cxx_exception_stubs.cpp.obj +[364/1743] Building CXX object esp-idf/cxx/CMakeFiles/__idf_cxx.dir/cxx_init.cpp.obj +[365/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_cxx_api.cpp.obj +[366/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_handle_simple.cpp.obj +[367/1743] Building CXX object esp-idf/cxx/CMakeFiles/__idf_cxx.dir/cxx_guards.cpp.obj +[368/1743] Building C object esp-idf/pthread/CMakeFiles/__idf_pthread.dir/pthread.c.obj +[369/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_item_hash_list.cpp.obj +[370/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_partition_manager.cpp.obj +[371/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_types.cpp.obj +[372/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_handle_locked.cpp.obj +[373/1743] Building C object esp-idf/pthread/CMakeFiles/__idf_pthread.dir/pthread_cond_var.c.obj +[374/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_encrypted_partition.cpp.obj +[375/1743] Building C object esp-idf/pthread/CMakeFiles/__idf_pthread.dir/pthread_local_storage.c.obj +[376/1743] Building C object esp-idf/pthread/CMakeFiles/__idf_pthread.dir/pthread_semaphore.c.obj +[377/1743] Building C object esp-idf/pthread/CMakeFiles/__idf_pthread.dir/pthread_rwlock.c.obj +[378/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_storage.cpp.obj +[379/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/abort.c.obj +[380/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_page.cpp.obj +[381/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/flockfile.c.obj +[382/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_pagemanager.cpp.obj +[383/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/poll.c.obj +[384/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/pthread.c.obj +[385/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/reent_init.c.obj +[386/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/assert.c.obj +[387/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/heap.c.obj +[388/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/termios.c.obj +[389/1743] Building CXX object esp-idf/nvs_flash/CMakeFiles/__idf_nvs_flash.dir/src/nvs_api.cpp.obj +[390/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/getentropy.c.obj +[391/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/realpath.c.obj +[392/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/random.c.obj +[393/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/newlib_init.c.obj +[394/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/syscalls.c.obj +[395/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/locks.c.obj +[396/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/sysconf.c.obj +[397/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/scandir.c.obj +[398/1743] Linking C static library esp-idf\nvs_flash\libnvs_flash.a +[399/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/port_common.c.obj +[400/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/list.c.obj +[401/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/port/xtensa/stdatomic_s32c1i.c.obj +[402/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/time.c.obj +[403/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/port_systick.c.obj +[404/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/app_startup.c.obj +[405/1743] Linking C static library esp-idf\esp_event\libesp_event.a +[406/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/port/esp_time_impl.c.obj +[407/1743] Building ASM object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/portable/xtensa/portasm.S.obj +[408/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/queue.c.obj +[409/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/heap_idf.c.obj +[410/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/timers.c.obj +[411/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/event_groups.c.obj +[412/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/portable/xtensa/port.c.obj +[413/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/portable/xtensa/xtensa_init.c.obj +[414/1743] Building C object esp-idf/newlib/CMakeFiles/__idf_newlib.dir/stdatomic.c.obj +[415/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/esp_additions/freertos_compatibility.c.obj +[416/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/portable/xtensa/xtensa_overlay_os_hook.c.obj +[417/1743] Linking C static library esp-idf\esp_driver_uart\libesp_driver_uart.a +[418/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/esp_additions/idf_additions.c.obj +[419/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/esp_memory_utils.c.obj +[420/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/esp_additions/idf_additions_event_groups.c.obj +[421/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/stream_buffer.c.obj +[422/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/cpu.c.obj +[423/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/esp_cpu_intr.c.obj +[424/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/cpu_region_protect.c.obj +[425/1743] Linking C static library esp-idf\esp_ringbuf\libesp_ringbuf.a +[426/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/revision.c.obj +[427/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/hw_random.c.obj +[428/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/esp_clk.c.obj +[429/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/clk_ctrl_os.c.obj +[430/1743] Building C object esp-idf/freertos/CMakeFiles/__idf_freertos.dir/FreeRTOS-Kernel/tasks.c.obj +[431/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_modem.c.obj +[432/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/mac_addr.c.obj +[433/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/rtc_module.c.obj +[434/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_console.c.obj +[435/1743] Linking C static library esp-idf\esp_driver_gptimer\libesp_driver_gptimer.a +[436/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/periph_ctrl.c.obj +[437/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_usb.c.obj +[438/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/intr_alloc.c.obj +[439/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_event.c.obj +[440/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/regi2c_ctrl.c.obj +[441/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/esp_gpio_reserve.c.obj +[442/1743] Linking C static library esp-idf\esp_timer\libesp_timer.a +[443/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp_clk_tree_common.c.obj +[444/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/dma/esp_dma_utils.c.obj +[445/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sar_periph_ctrl_common.c.obj +[446/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_gpio.c.obj +[447/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/io_mux.c.obj +[448/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/esp_clk_tree.c.obj +[449/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/dma/gdma_link.c.obj +[450/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/clk_utils.c.obj +[451/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_modes.c.obj +[452/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/spi_share_hw_ctrl.c.obj +[453/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/spi_bus_lock.c.obj +[454/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/dma/esp_async_memcpy.c.obj +[455/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/deprecated/gdma_legacy.c.obj +[456/1743] Linking C static library esp-idf\cxx\libcxx.a +[457/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/systimer.c.obj +[458/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/adc_share_hw_ctrl.c.obj +[459/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/dma/async_memcpy_gdma.c.obj +[460/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/mspi_timing_by_mspi_delay.c.obj +[461/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/mspi_timing_tuning.c.obj +[462/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/sleep_wake_stub.c.obj +[463/1743] Linking C static library esp-idf\pthread\libpthread.a +[464/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/rtc_clk_init.c.obj +[465/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/chip_info.c.obj +[466/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/rtc_clk.c.obj +[467/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp_memprot_conv.c.obj +[468/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/esp_clock_output.c.obj +[469/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/rtc_sleep.c.obj +[470/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/dma/gdma.c.obj +[471/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/sar_periph_ctrl.c.obj +[472/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/rtc_init.c.obj +[473/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/mspi_timing_config.c.obj +[474/1743] Building C object esp-idf/esp_security/CMakeFiles/__idf_esp_security.dir/src/esp_crypto_lock.c.obj +[475/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/rtc_time.c.obj +[476/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/adc_periph.c.obj +[477/1743] Linking C static library esp-idf\newlib\libnewlib.a +[478/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/interrupts.c.obj +[479/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/dport_access_common.c.obj +[480/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/lldesc.c.obj +[481/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/gpio_periph.c.obj +[482/1743] Building C object esp-idf/esp_security/CMakeFiles/__idf_esp_security.dir/src/init.c.obj +[483/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/lowpower/port/esp32s3/sleep_cpu.c.obj +[484/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/uart_periph.c.obj +[485/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/ledc_periph.c.obj +[486/1743] Building C object esp-idf/esp_security/CMakeFiles/__idf_esp_security.dir/src/esp_hmac.c.obj +[487/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/spi_periph.c.obj +[488/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/gdma_periph.c.obj +[489/1743] Building C object esp-idf/esp_security/CMakeFiles/__idf_esp_security.dir/src/esp_ds.c.obj +[490/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/dedic_gpio_periph.c.obj +[491/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/sdm_periph.c.obj +[492/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/pcnt_periph.c.obj +[493/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/rmt_periph.c.obj +[494/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/lcd_periph.c.obj +[495/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/temperature_sensor_periph.c.obj +[496/1743] Linking C static library esp-idf\freertos\libfreertos.a +[497/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/timer_periph.c.obj +[498/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/i2s_periph.c.obj +[499/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/mcpwm_periph.c.obj +[500/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/i2c_periph.c.obj +[501/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/touch_sensor_periph.c.obj +[502/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/sdmmc_periph.c.obj +[503/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/cam_periph.c.obj +[504/1743] Building C object esp-idf/esp_hw_support/CMakeFiles/__idf_esp_hw_support.dir/port/esp32s3/esp_memprot.c.obj +[505/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/twai_periph.c.obj +[506/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/rtc_io_periph.c.obj +[507/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/usb_dwc_periph.c.obj +[508/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/wdt_periph.c.obj +[509/1743] Building C object esp-idf/soc/CMakeFiles/__idf_soc.dir/esp32s3/mpi_periph.c.obj +[510/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/port/esp32s3/memory_layout.c.obj +[511/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/port/memory_layout_utils.c.obj +[512/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/util.c.obj +[513/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/heap_caps_base.c.obj +[514/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/os/log_write.c.obj +[515/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/os/log_lock.c.obj +[516/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/log_level/log_level.c.obj +[517/1743] Linking C static library esp-idf\esp_hw_support\libesp_hw_support.a +[518/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/log_timestamp_common.c.obj +[519/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/log_level/tag_log_level/linked_list/log_linked_list.c.obj +[520/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/os/log_timestamp.c.obj +[521/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/heap_caps.c.obj +[522/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/multi_heap.c.obj +[523/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/buffer/log_buffers.c.obj +[524/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/heap_caps_init.c.obj +[525/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/log_level/tag_log_level/cache/log_binary_heap.c.obj +[526/1743] Building C object esp-idf/log/CMakeFiles/__idf_log.dir/src/log_level/tag_log_level/tag_log_level.c.obj +[527/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/hal_utils.c.obj +[528/1743] Linking C static library esp-idf\esp_security\libesp_security.a +[529/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/esp32s3/efuse_hal.c.obj +[530/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/color_hal.c.obj +[531/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_flash_encrypt_hal_iram.c.obj +[532/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/mmu_hal.c.obj +[533/1743] Building C object esp-idf/heap/CMakeFiles/__idf_heap.dir/tlsf/tlsf.c.obj +[534/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/mpu_hal.c.obj +[535/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_flash_hal.c.obj +[536/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/efuse_hal.c.obj +[537/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/cache_hal.c.obj +[538/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/esp32s3/clk_tree_hal.c.obj +[539/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/systimer_hal.c.obj +[540/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/uart_hal_iram.c.obj +[541/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/uart_hal.c.obj +[542/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_flash_hal_iram.c.obj +[543/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/gpio_hal.c.obj +[544/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/timer_hal.c.obj +[545/1743] Linking C static library esp-idf\soc\libsoc.a +[546/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/rtc_io_hal.c.obj +[547/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/ledc_hal_iram.c.obj +[548/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/ledc_hal.c.obj +[549/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/pcnt_hal.c.obj +[550/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/rmt_hal.c.obj +[551/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/i2c_hal_iram.c.obj +[552/1743] Linking C static library esp-idf\heap\libheap.a +[553/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/gdma_hal_top.c.obj +[554/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/i2c_hal.c.obj +[555/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/uhci_hal.c.obj +[556/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/mcpwm_hal.c.obj +[557/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/sdmmc_hal.c.obj +[558/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/sdm_hal.c.obj +[559/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/twai_hal_iram.c.obj +[560/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/twai_hal.c.obj +[561/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/gdma_hal_ahb_v1.c.obj +[562/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/adc_hal_common.c.obj +[563/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/mpi_hal.c.obj +[564/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/adc_oneshot_hal.c.obj +[565/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/i2s_hal.c.obj +[566/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/aes_hal.c.obj +[567/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/sha_hal.c.obj +[568/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/adc_hal.c.obj +[569/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/lcd_hal.c.obj +[570/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_slave_hal_iram.c.obj +[571/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/brownout_hal.c.obj +[572/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/ds_hal.c.obj +[573/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/cam_hal.c.obj +[574/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/hmac_hal.c.obj +[575/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_slave_hal.c.obj +[576/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_hal.c.obj +[577/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_flash_hal_gpspi.c.obj +[578/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_hal_iram.c.obj +[579/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/usb_serial_jtag_hal.c.obj +[580/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/usb_wrap_hal.c.obj +[581/1743] Linking C static library esp-idf\log\liblog.a +[582/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/spi_slave_hd_hal.c.obj +[583/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/touch_sensor_hal.c.obj +[584/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/esp32s3/touch_sensor_hal.c.obj +[585/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/esp32s3/rtc_cntl_hal.c.obj +[586/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/xt_wdt_hal.c.obj +[587/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_crc.c.obj +[588/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_uart.c.obj +[589/1743] Building C object esp-idf/hal/CMakeFiles/__idf_hal.dir/usb_dwc_hal.c.obj +[590/1743] Building ASM object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_longjmp.S.obj +[591/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_gpio.c.obj +[592/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_spiflash.c.obj +[593/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_sys.c.obj +[594/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_print.c.obj +[595/1743] Building ASM object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_cache_writeback_esp32s3.S.obj +[596/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_cache_esp32s2_esp32s3.c.obj +[597/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_efuse.c.obj +[598/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_systimer.c.obj +[599/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/esp_system_console.c.obj +[600/1743] Building C object esp-idf/esp_rom/CMakeFiles/__idf_esp_rom.dir/patches/esp_rom_wdt.c.obj +[601/1743] Linking C static library esp-idf\hal\libhal.a +[602/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/esp_ipc.c.obj +[603/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/esp_err.c.obj +[604/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/stack_check.c.obj +[605/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/system_time.c.obj +[606/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/crosscore_int.c.obj +[607/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/freertos_hooks.c.obj +[608/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/panic.c.obj +[609/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/esp_system.c.obj +[610/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/int_wdt.c.obj +[611/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/ubsan.c.obj +[612/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/startup.c.obj +[613/1743] Linking C static library esp-idf\esp_rom\libesp_rom.a +[614/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/startup_funcs.c.obj +[615/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/xt_wdt.c.obj +[616/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/task_wdt/task_wdt_impl_timergroup.c.obj +[617/1743] Building ASM object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/esp_ipc_isr_routines.S.obj +[618/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/task_wdt/task_wdt.c.obj +[619/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/image_process.c.obj +[620/1743] Building ASM object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/esp_ipc_isr_handler.S.obj +[621/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/esp_ipc_isr.c.obj +[622/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/esp_ipc_isr_port.c.obj +[623/1743] Building ASM object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/panic_handler_asm.S.obj +[624/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/esp_system_chip.c.obj +[625/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/panic_handler.c.obj +[626/1743] Building C object esp-idf/esp_common/CMakeFiles/__idf_esp_common.dir/src/esp_err_to_name.c.obj +[627/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/cpu_start.c.obj +[628/1743] Building ASM object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/debug_helpers_asm.S.obj +[629/1743] Building ASM object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/expression_with_stack_asm.S.obj +[630/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/brownout.c.obj +[631/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/expression_with_stack.c.obj +[632/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/debug_helpers.c.obj +[633/1743] Building ASM object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/soc/esp32s3/highint_hdl.S.obj +[634/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/debug_stubs.c.obj +[635/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/flash_brownout_hook.c.obj +[636/1743] Linking C static library esp-idf\esp_common\libesp_common.a +[637/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/soc/esp32s3/reset_reason.c.obj +[638/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/trax.c.obj +[639/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/arch/xtensa/panic_arch.c.obj +[640/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_issi.c.obj +[641/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/soc/esp32s3/clk.c.obj +[642/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/soc/esp32s3/apb_backup_dma.c.obj +[643/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/esp32s3/spi_flash_oct_flash_init.c.obj +[644/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_hpm_enable.c.obj +[645/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/soc/esp32s3/cache_err_int.c.obj +[646/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_drivers.c.obj +[647/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_boya.c.obj +[648/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_gd.c.obj +[649/1743] Building C object esp-idf/esp_system/CMakeFiles/__idf_esp_system.dir/port/soc/esp32s3/system_internal.c.obj +[650/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_th.c.obj +[651/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_mxic.c.obj +[652/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_generic.c.obj +[653/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_mxic_opi.c.obj +[654/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/memspi_host_driver.c.obj +[655/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_chip_winbond.c.obj +[656/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_wrap.c.obj +[657/1743] Linking C static library esp-idf\esp_system\libesp_system.a +[658/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/cache_utils.c.obj +[659/1743] Building C object esp-idf/esp_mm/CMakeFiles/__idf_esp_mm.dir/port/esp32s3/ext_mem_layout.c.obj +[660/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_os_func_noos.c.obj +[661/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/spi_flash_os_func_app.c.obj +[662/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/flash_mmap.c.obj +[663/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/flash_ops.c.obj +[664/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/esp_flash_spi_init.c.obj +[665/1743] Building C object esp-idf/esp_mm/CMakeFiles/__idf_esp_mm.dir/esp_cache_utils.c.obj +[666/1743] Building C object esp-idf/esp_mm/CMakeFiles/__idf_esp_mm.dir/esp_cache_msync.c.obj +[667/1743] Building C object esp-idf/esp_mm/CMakeFiles/__idf_esp_mm.dir/heap_align_hw.c.obj +[668/1743] Building C object esp-idf/esp_mm/CMakeFiles/__idf_esp_mm.dir/esp_mmu_map.c.obj +[669/1743] Building C object esp-idf/spi_flash/CMakeFiles/__idf_spi_flash.dir/esp_flash_api.c.obj +[670/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_mem.c.obj +[671/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_common_loader.c.obj +[672/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/flash_encrypt.c.obj +[673/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_random_esp32s3.c.obj +[674/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_random.c.obj +[675/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_common.c.obj +[676/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_efuse.c.obj +[677/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/secure_boot.c.obj +[678/1743] Linking C static library esp-idf\spi_flash\libspi_flash.a +[679/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/bootloader_flash/src/bootloader_flash.c.obj +[680/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_clock_init.c.obj +[681/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/bootloader_flash/src/bootloader_flash_config_esp32s3.c.obj +[682/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/flash_partitions.c.obj +[683/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/idf/bootloader_sha.c.obj +[684/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/bootloader_flash/src/flash_qio_mode.c.obj +[685/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/esp32s3/esp_efuse_table.c.obj +[686/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/esp32s3/secure_boot_secure_features.c.obj +[687/1743] Linking C static library esp-idf\esp_mm\libesp_mm.a +[688/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/esp32s3/esp_efuse_fields.c.obj +[689/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/esp32s3/esp_efuse_rtc_calib.c.obj +[690/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/esp_image_format.c.obj +[691/1743] Building C object esp-idf/bootloader_support/CMakeFiles/__idf_bootloader_support.dir/src/bootloader_utility.c.obj +[692/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/esp32s3/esp_efuse_utility.c.obj +[693/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/src/esp_efuse_fields.c.obj +[694/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/src/esp_efuse_startup.c.obj +[695/1743] Building C object esp-idf/esp_bootloader_format/CMakeFiles/__idf_esp_bootloader_format.dir/esp_bootloader_desc.c.obj +[696/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/src/esp_efuse_utility.c.obj +[697/1743] Building C object esp-idf/esp_partition/CMakeFiles/__idf_esp_partition.dir/partition_target.c.obj +[698/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/debug.c.obj +[699/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/src/efuse_controller/keys/with_key_purposes/esp_efuse_api_key.c.obj +[700/1743] Building C object esp-idf/efuse/CMakeFiles/__idf_efuse.dir/src/esp_efuse_api.c.obj +[701/1743] Building C object esp-idf/app_update/CMakeFiles/__idf_app_update.dir/esp_ota_app_desc.c.obj +[702/1743] Linking C static library esp-idf\bootloader_support\libbootloader_support.a +[703/1743] Building C object esp-idf/esp_app_format/CMakeFiles/__idf_esp_app_format.dir/esp_app_desc.c.obj +[704/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/mps_trace.c.obj +[705/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/mps_reader.c.obj +[706/1743] Building C object esp-idf/esp_partition/CMakeFiles/__idf_esp_partition.dir/partition.c.obj +[707/1743] Building C object esp-idf/app_update/CMakeFiles/__idf_app_update.dir/esp_ota_ops.c.obj +[708/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_ciphersuites.c.obj +[709/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls13_keys.c.obj +[710/1743] Linking C static library esp-idf\efuse\libefuse.a +[711/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_client.c.obj +[712/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_cookie.c.obj +[713/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_debug_helpers_generated.c.obj +[714/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_cache.c.obj +[715/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls13_client.c.obj +[716/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_ticket.c.obj +[717/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/mbedtls_debug.c.obj +[718/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls13_server.c.obj +[719/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls13_generic.c.obj +[720/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_platform_time.c.obj +[721/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls12_client.c.obj +[722/1743] Linking C static library esp-idf\esp_partition\libesp_partition.a +[723/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_msg.c.obj +[724/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls12_server.c.obj +[725/1743] Linking C static library esp-idf\app_update\libapp_update.a +[726/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/pkcs7.c.obj +[727/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/aesce.c.obj +[728/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/net_sockets.c.obj +[729/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/aesni.c.obj +[730/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509_create.c.obj +[731/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509write_crt.c.obj +[732/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509_csr.c.obj +[733/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509write.c.obj +[734/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509_crl.c.obj +[735/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509write_csr.c.obj +[736/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedtls.dir/ssl_tls.c.obj +[737/1743] Linking C static library esp-idf\esp_bootloader_format\libesp_bootloader_format.a +[738/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509.c.obj +[739/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/bignum_mod.c.obj +[740/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/aria.c.obj +[741/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/camellia.c.obj +[742/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/bignum_mod_raw.c.obj +[743/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/aes.c.obj +[744/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/asn1parse.c.obj +[745/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/chacha20.c.obj +[746/1743] Linking C static library esp-idf\esp_app_format\libesp_app_format.a +[747/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/asn1write.c.obj +[748/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/block_cipher.c.obj +[749/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/base64.c.obj +[750/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/chachapoly.c.obj +[751/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedx509.dir/x509_crt.c.obj +[752/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ccm.c.obj +[753/1743] Linking CXX static library esp-idf\mbedtls\mbedtls\library\libmbedtls.a +[754/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/cipher.c.obj +[755/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/constant_time.c.obj +[756/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/bignum_core.c.obj +[757/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/cipher_wrap.c.obj +[758/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/des.c.obj +[759/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/dhm.c.obj +[760/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecdh.c.obj +[761/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/cmac.c.obj +[762/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecjpake.c.obj +[763/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ctr_drbg.c.obj +[764/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecp_curves_new.c.obj +[765/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecdsa.c.obj +[766/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/bignum.c.obj +[767/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/entropy_poll.c.obj +[768/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/entropy.c.obj +[769/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/hkdf.c.obj +[770/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/md5.c.obj +[771/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecp_curves.c.obj +[772/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/hmac_drbg.c.obj +[773/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/error.c.obj +[774/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/memory_buffer_alloc.c.obj +[775/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/padlock.c.obj +[776/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/nist_kw.c.obj +[777/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/lms.c.obj +[778/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/lmots.c.obj +[779/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/gcm.c.obj +[780/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/md.c.obj +[781/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/oid.c.obj +[782/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pk_ecc.c.obj +[783/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pem.c.obj +[784/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecp.c.obj +[785/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pk_wrap.c.obj +[786/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/platform.c.obj +[787/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/platform_util.c.obj +[788/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/poly1305.c.obj +[789/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pk.c.obj +[790/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pkcs12.c.obj +[791/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pkcs5.c.obj +[792/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_client.c.obj +[793/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_aead.c.obj +[794/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pkwrite.c.obj +[795/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/pkparse.c.obj +[796/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_driver_wrappers_no_static.c.obj +[797/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_cipher.c.obj +[798/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_hash.c.obj +[799/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_ffdh.c.obj +[800/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_pake.c.obj +[801/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_se.c.obj +[802/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_mac.c.obj +[803/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_ecp.c.obj +[804/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_rsa.c.obj +[805/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/ripemd160.c.obj +[806/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_storage.c.obj +[807/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_its_file.c.obj +[808/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/sha1.c.obj +[809/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_util.c.obj +[810/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto_slot_management.c.obj +[811/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/rsa_alt_helpers.c.obj +[812/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/sha256.c.obj +[813/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/timing.c.obj +[814/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/sha3.c.obj +[815/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/threading.c.obj +[816/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/sha512.c.obj +[817/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/version.c.obj +[818/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/version_features.c.obj +[819/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/aes/dma/esp_aes_gdma_impl.c.obj +[820/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/sha/dma/esp_sha_gdma_impl.c.obj +[821/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_mem.c.obj +[822/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_hardware.c.obj +[823/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/aes/dma/esp_aes_dma_core.c.obj +[824/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/aes/esp_aes_xts.c.obj +[825/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/aes/esp_aes_common.c.obj +[826/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/sha/esp_sha.c.obj +[827/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/rsa.c.obj +[828/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/crypto_shared_gdma/esp_crypto_shared_gdma.c.obj +[829/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/aes/dma/esp_aes.c.obj +[830/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/sha/dma/sha.c.obj +[831/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_timing.c.obj +[832/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/md/esp_md.c.obj +[833/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_ds/esp_rsa_dec_alt.c.obj +[834/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_ds/esp_ds_common.c.obj +[835/1743] Linking CXX static library esp-idf\mbedtls\mbedtls\library\libmbedx509.a +[836/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/bignum/bignum_alt.c.obj +[837/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/esp_ds/esp_rsa_sign_alt.c.obj +[838/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/sha/dma/esp_sha1.c.obj +[839/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/bignum/esp_bignum.c.obj +[840/1743] Building C object esp-idf/mbedtls/mbedtls/3rdparty/p256-m/CMakeFiles/p256m.dir/p256-m/p256-m.c.obj +[841/1743] Generating ../../ota_data_initial.bin +[842/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/sha/dma/esp_sha256.c.obj +[843/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/D_/software/Espressif/frameworks/esp-idf-v5.4.3/components/mbedtls/port/sha/dma/esp_sha512.c.obj +[844/1743] Building C object esp-idf/mbedtls/mbedtls/3rdparty/everest/CMakeFiles/everest.dir/library/everest.c.obj +[845/1743] Building C object esp-idf/mbedtls/mbedtls/3rdparty/p256-m/CMakeFiles/p256m.dir/p256-m_driver_entrypoints.c.obj +[846/1743] Building C object esp-idf/mbedtls/mbedtls/3rdparty/everest/CMakeFiles/everest.dir/library/x25519.c.obj +[847/1743] Building C object esp-idf/mbedtls/mbedtls/library/CMakeFiles/mbedcrypto.dir/psa_crypto.c.obj +[848/1743] Validating and packing local Ogg/Opus prompts +generated D:\4_Program\firmware2_9\build\esp-idf\main\generated\audio_prompts_data.h: assets=45 packed=533670 bytes max_frame=180 +[849/1743] Building C object esp-idf/mbedtls/mbedtls/3rdparty/everest/CMakeFiles/everest.dir/library/Hacl_Curve25519_joined.c.obj +[850/1743] Generating ../../partition_table/partition-table.bin +Partition table binary generated. Contents: +******************************************************************************* +# ESP-IDF Partition Table +# Name, Type, SubType, Offset, Size, Flags +nvs,data,nvs,0x9000,24K, +otadata,data,ota,0xf000,8K, +phy_init,data,phy,0x11000,4K, +ota_0,app,ota_0,0x20000,4M, +ota_1,app,ota_1,0x420000,4M, +model,data,spiffs,0x820000,1M, +claude_mem,data,spiffs,0x920000,7040K, +******************************************************************************* +[851/1743] Linking CXX static library esp-idf\mbedtls\mbedtls\library\libmbedcrypto.a +[852/1743] Linking CXX static library esp-idf\mbedtls\mbedtls\3rdparty\p256-m\libp256m.a +[853/1743] Linking CXX static library esp-idf\mbedtls\mbedtls\3rdparty\everest\libeverest.a +[854/1743] Generating x509_crt_bundle +[855/1743] Generating ../../x509_crt_bundle.S +[856/1743] Building ASM object esp-idf/mbedtls/CMakeFiles/__idf_mbedtls.dir/__/__/x509_crt_bundle.S.obj +[857/1743] Building C object esp-idf/esp_driver_gpio/CMakeFiles/__idf_esp_driver_gpio.dir/src/gpio_glitch_filter_ops.c.obj +[858/1743] Building ASM object esp-idf/xtensa/CMakeFiles/__idf_xtensa.dir/xtensa_intr_asm.S.obj +[859/1743] Building C object esp-idf/xtensa/CMakeFiles/__idf_xtensa.dir/eri.c.obj +[860/1743] Building C object esp-idf/esp_pm/CMakeFiles/__idf_esp_pm.dir/pm_trace.c.obj +[861/1743] Building C object esp-idf/esp_pm/CMakeFiles/__idf_esp_pm.dir/pm_locks.c.obj +[862/1743] Building C object esp-idf/xtensa/CMakeFiles/__idf_xtensa.dir/xt_trax.c.obj +[863/1743] Building ASM object esp-idf/xtensa/CMakeFiles/__idf_xtensa.dir/xtensa_vectors.S.obj +[864/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/dl_fft_f32.c.obj +[865/1743] Building ASM object esp-idf/xtensa/CMakeFiles/__idf_xtensa.dir/xtensa_context.S.obj +[866/1743] Building C object esp-idf/mbedtls/CMakeFiles/__idf_mbedtls.dir/esp_crt_bundle/esp_crt_bundle.c.obj +[867/1743] Building C object esp-idf/esp_driver_gpio/CMakeFiles/__idf_esp_driver_gpio.dir/src/gpio_pin_glitch_filter.c.obj +[868/1743] Building C object esp-idf/xtensa/CMakeFiles/__idf_xtensa.dir/xtensa_intr.c.obj +[869/1743] Building C object esp-idf/esp_pm/CMakeFiles/__idf_esp_pm.dir/pm_impl.c.obj +[870/1743] Building C object esp-idf/esp_driver_gpio/CMakeFiles/__idf_esp_driver_gpio.dir/src/dedic_gpio.c.obj +[871/1743] Building C object esp-idf/esp_driver_gpio/CMakeFiles/__idf_esp_driver_gpio.dir/src/rtc_io.c.obj +[872/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/dl_rfft_s16.c.obj +[873/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/dl_rfft_f32.c.obj +[874/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/dl_fft_s16.c.obj +[875/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/dl_fft2r_fc32_ansi.c.obj +[876/1743] Building C object esp-idf/esp_driver_gpio/CMakeFiles/__idf_esp_driver_gpio.dir/src/gpio.c.obj +[877/1743] Building ASM object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/isa/esp32s3/dl_fft4r_fc32_aes3.S.obj +[878/1743] Linking C static library esp-idf\mbedtls\libmbedtls.a +[879/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/dl_fft2r_sc16_ansi.c.obj +[880/1743] Building ASM object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/isa/esp32s3/dl_fft2r_sc16_aes3.S.obj +[881/1743] Building ASM object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/isa/esp32s3/dl_fft2r_fc32_aes3.S.obj +[882/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/dl_fft4r_fc32_ansi.c.obj +[883/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/dl_fft2r_sc16_dif_ansi.c.obj +[884/1743] Linking C static library esp-idf\esp_pm\libesp_pm.a +[885/1743] Building C object esp-idf/espressif__dl_fft/CMakeFiles/__idf_espressif__dl_fft.dir/base/dl_fft_base.c.obj +[886/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/allocator.c.obj +[887/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/btc/core/btc_alarm.c.obj +[888/1743] Linking C static library esp-idf\esp_driver_gpio\libesp_driver_gpio.a +[889/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/hci_log/bt_hci_log.c.obj +[890/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/buffer.c.obj +[891/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/btc/core/btc_manage.c.obj +[892/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/btc/profile/esp/blufi/blufi_protocol.c.obj +[893/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/btc/core/btc_task.c.obj +[894/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/controller/esp32c3/bt.c.obj +[895/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/api/esp_blufi_api.c.obj +[896/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/btc/profile/esp/blufi/blufi_prf.c.obj +[897/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/alarm.c.obj +[898/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/pkt_queue.c.obj +[899/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/future.c.obj +[900/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/fixed_queue.c.obj +[901/1743] Linking C static library esp-idf\xtensa\libxtensa.a +[902/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/fixed_pkt_queue.c.obj +[903/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/config.c.obj +[904/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/hash_functions.c.obj +[905/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/hash_map.c.obj +[906/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/list.c.obj +[907/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/porting/mem/bt_osi_mem.c.obj +[908/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/mutex.c.obj +[909/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/semaphore.c.obj +[910/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/thread.c.obj +[911/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/osi/osi.c.obj +[912/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/transport/src/transport.c.obj +[913/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/ble_log/ble_log_spi_out.c.obj +[914/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/gatt/src/ble_svc_gatt.c.obj +[915/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/ble_log/ble_log_uhci_out.c.obj +[916/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/tps/src/ble_svc_tps.c.obj +[917/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/util/src/addr.c.obj +[918/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/ipss/src/ble_svc_ipss.c.obj +[919/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/hr/src/ble_svc_hr.c.obj +[920/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/ias/src/ble_svc_ias.c.obj +[921/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/htp/src/ble_svc_htp.c.obj +[922/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/ans/src/ble_svc_ans.c.obj +[923/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/bas/src/ble_svc_bas.c.obj +[924/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/gap/src/ble_svc_gap.c.obj +[925/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/hid/src/ble_svc_hid.c.obj +[926/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/dis/src/ble_svc_dis.c.obj +[927/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/prox/src/ble_svc_prox.c.obj +[928/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/lls/src/ble_svc_lls.c.obj +[929/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/cts/src/ble_svc_cts.c.obj +[930/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_shutdown.c.obj +[931/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/sps/src/ble_svc_sps.c.obj +[932/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/services/cte/src/ble_svc_cte.c.obj +[933/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_l2cap_sig_cmd.c.obj +[934/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_store_util.c.obj +[935/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_id.c.obj +[936/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_gatts_lcl.c.obj +[937/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_hci_cmd.c.obj +[938/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_ibeacon.c.obj +[939/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_conn.c.obj +[940/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_atomic.c.obj +[941/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_sm_alg.c.obj +[942/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_stop.c.obj +[943/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_periodic_sync.c.obj +[944/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_hci_evt.c.obj +[945/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_sm.c.obj +[946/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_att.c.obj +[947/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_att_svr.c.obj +[948/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_mqueue.c.obj +[949/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_gattc.c.obj +[950/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_ead.c.obj +[951/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs.c.obj +[952/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_aes_ccm.c.obj +[953/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_att_clt.c.obj +[954/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_cfg.c.obj +[955/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_sm_lgcy.c.obj +[956/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_mbuf.c.obj +[957/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_l2cap_coc.c.obj +[958/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_store.c.obj +[959/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_l2cap_sig.c.obj +[960/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_startup.c.obj +[961/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_att_cmd.c.obj +[962/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_log.c.obj +[963/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_eddystone.c.obj +[964/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_sm_cmd.c.obj +[965/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_resolv.c.obj +[966/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_flow.c.obj +[967/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_pvcy.c.obj +[968/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_uuid.c.obj +[969/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_misc.c.obj +[970/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_sm_sc.c.obj +[971/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/store/config/src/ble_store_nvs.c.obj +[972/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_hci_util.c.obj +[973/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_l2cap.c.obj +[974/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_hci.c.obj +[975/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_gatts.c.obj +[976/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_eatt.c.obj +[977/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_gap.c.obj +[978/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_hs_adv.c.obj +[979/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/store/ram/src/ble_store_ram.c.obj +[980/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/npl/freertos/src/nimble_port_freertos.c.obj +[981/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/port/src/nvs_port.c.obj +[982/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_gattc_cache.c.obj +[983/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/store/config/src/ble_store_config.c.obj +[984/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/host/src/ble_gattc_cache_conn.c.obj +[985/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/nimble/src/endian.c.obj +[986/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/nimble/src/nimble_port.c.obj +[987/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/nimble/src/mem.c.obj +[988/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/nimble/src/os_mempool.c.obj +[989/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/nimble/src/os_msys_init.c.obj +[990/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/commands.c.obj +[991/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/common/btc/profile/esp/blufi/nimble_host/esp_blufi.c.obj +[992/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/nimble/transport/esp_ipc_legacy/src/hci_esp_ipc_legacy.c.obj +[993/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/esp_console_common.c.obj +[994/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/split_argv.c.obj +[995/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_cmd.c.obj +[996/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/esp-hci/src/esp_nimble_hci.c.obj +[997/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/nimble/src/os_mbuf.c.obj +[998/1743] Building C object esp-idf/bt/CMakeFiles/__idf_bt.dir/host/nimble/nimble/porting/npl/freertos/src/npl_os_freertos.c.obj +[999/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_dbl.c.obj +[1000/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_dstr.c.obj +[1001/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/esp_console_repl_chip.c.obj +[1002/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_end.c.obj +[1003/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_date.c.obj +[1004/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_rem.c.obj +[1005/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_hashtable.c.obj +[1006/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_lit.c.obj +[1007/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_file.c.obj +[1008/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_int.c.obj +[1009/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/linenoise/linenoise.c.obj +[1010/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_utils.c.obj +[1011/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_str.c.obj +[1012/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprod_f32_m_ae32.S.obj +[1013/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprod_f32_ae32.S.obj +[1014/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/arg_rex.c.obj +[1015/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/spiffs_api.c.obj +[1016/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprode_f32_m_ae32.S.obj +[1017/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprode_f32_ae32.S.obj +[1018/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/spiffs/src/spiffs_cache.c.obj +[1019/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/common/misc/aes3_tie_log.c.obj +[1020/1743] Building C object esp-idf/console/CMakeFiles/__idf_console.dir/argtable3/argtable3.c.obj +[1021/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/spiffs/src/spiffs_gc.c.obj +[1022/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/common/misc/dsps_pwroftwo.cpp.obj +[1023/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/spiffs/src/spiffs_check.c.obj +[1024/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprod_f32_arp4.S.obj +[1025/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprode_f32_arp4.S.obj +[1026/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprod_f32_aes3.S.obj +[1027/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprode_f32_ansi.c.obj +[1028/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dsps_dotprod_f32_ansi.c.obj +[1029/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dsps_dotprod_s16_ae32.S.obj +[1030/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/spiffs/src/spiffs_hydrogen.c.obj +[1031/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/esp_spiffs.c.obj +[1032/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dsps_dotprod_s16_m_ae32.S.obj +[1033/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dsps_dotprod_s16_arp4.S.obj +[1034/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dspi_dotprod_off_f32_ansi.c.obj +[1035/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_u16_ansi.c.obj +[1036/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_s16_aes3.S.obj +[1037/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/float/dspi_dotprod_f32_ansi.c.obj +[1038/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_u8_aes3.S.obj +[1039/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dsps_dotprod_s16_ansi.c.obj +[1040/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_s8_ansi.c.obj +[1041/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_u8_ansi.c.obj +[1042/1743] Building C object esp-idf/spiffs/CMakeFiles/__idf_spiffs.dir/spiffs/src/spiffs_nucleus.c.obj +[1043/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_s8_aes3.S.obj +[1044/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_u16_aes3.S.obj +[1045/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_u16_ansi.c.obj +[1046/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_u16_aes3.S.obj +[1047/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_s16_ansi.c.obj +[1048/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_u8_ansi.c.obj +[1049/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_s8_ansi.c.obj +[1050/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_s16_aes3.S.obj +[1051/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_s16_arp4.S.obj +[1052/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_s8_arp4.S.obj +[1053/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_u8_arp4.S.obj +[1054/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_s8_arp4.S.obj +[1055/1743] Building C object esp-idf/protobuf-c/CMakeFiles/__idf_protobuf-c.dir/protobuf-c/protobuf-c/protobuf-c.c.obj +[1056/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_s16_ansi.c.obj +[1057/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_3x3x1_f32_ae32.S.obj +[1058/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_u16_arp4.S.obj +[1059/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_3x3x3_f32_ae32.S.obj +[1060/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_f32_ae32.S.obj +[1061/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_u8_arp4.S.obj +[1062/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_s8_aes3.S.obj +[1063/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_f32_arp4.S.obj +[1064/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_u8_aes3.S.obj +[1065/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_s16_arp4.S.obj +[1066/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_4x4x1_f32_ae32.S.obj +[1067/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dotprod/fixed/dspi_dotprod_off_u16_arp4.S.obj +[1068/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_ex_f32_aes3.S.obj +[1069/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_f32_aes3.S.obj +[1070/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_4x4x4_f32_ae32.S.obj +[1071/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_ex_f32_ae32.S.obj +[1072/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_ex_f32_arp4.S.obj +[1073/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/fixed/dspm_mult_s16_m_ae32_vector.S.obj +[1074/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/add/float/dspm_add_f32_ae32.S.obj +[1075/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/fixed/dspm_mult_s16_arp4.S.obj +[1076/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/fixed/dspm_mult_s16_ae32.S.obj +[1077/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/fixed/dspm_mult_s16_m_ae32.S.obj +[1078/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/addc/float/dspm_addc_f32_ae32.S.obj +[1079/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mulc/float/dspm_mulc_f32_ae32.S.obj +[1080/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_f32_ansi.c.obj +[1081/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/fixed/dspm_mult_s16_aes3.S.obj +[1082/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/float/dspm_mult_ex_f32_ansi.c.obj +[1083/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/sub/float/dspm_sub_f32_ae32.S.obj +[1084/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/add/float/dspm_add_f32_ansi.c.obj +[1085/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/addc/float/dspm_addc_f32_ansi.c.obj +[1086/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mul/fixed/dspm_mult_s16_ansi.c.obj +[1087/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/fixed/dsps_add_s16_ae32.S.obj +[1088/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/fixed/dsps_add_s8_ansi.c.obj +[1089/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/fixed/dsps_add_s16_ansi.c.obj +[1090/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mulc/fixed/dsps_mulc_s16_ae32.S.obj +[1091/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/fixed/dsps_sub_s16_ae32.S.obj +[1092/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mulc/fixed/dsps_mulc_s16_ansi.c.obj +[1093/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mulc/float/dsps_mulc_f32_ansi.c.obj +[1094/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/addc/float/dsps_addc_f32_ansi.c.obj +[1095/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/fixed/dsps_add_s8_aes3.S.obj +[1096/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/sub/float/dspm_sub_f32_ansi.c.obj +[1097/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/fixed/dsps_mul_s16_ae32.S.obj +[1098/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/float/dsps_sub_f32_ansi.c.obj +[1099/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/fixed/dsps_add_s16_aes3.S.obj +[1100/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/float/dsps_add_f32_ansi.c.obj +[1101/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/fixed/dsps_mul_s16_aes3.S.obj +[1102/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/fixed/dsps_sub_s8_ansi.c.obj +[1103/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/fixed/dsps_sub_s8_aes3.S.obj +[1104/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/fixed/dsps_sub_s16_ansi.c.obj +[1105/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/addc/float/dsps_addc_f32_ae32.S.obj +[1106/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mulc/float/dspm_mulc_f32_ansi.c.obj +[1107/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/float/dsps_mul_f32_ansi.c.obj +[1108/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/fixed/dsps_mul_s16_ansi.c.obj +[1109/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/add/float/dsps_add_f32_ae32.S.obj +[1110/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/fixed/dsps_mul_s8_ansi.c.obj +[1111/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mulc/float/dsps_mulc_f32_ae32.S.obj +[1112/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/float/dsps_sub_f32_ae32.S.obj +[1113/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft2r_fc32_arp4.S.obj +[1114/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sub/fixed/dsps_sub_s16_aes3.S.obj +[1115/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft2r_fc32_ae32_.S.obj +[1116/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft4r_fc32_aes3_.S.obj +[1117/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/float/dsps_mul_f32_ae32.S.obj +[1118/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/mul/fixed/dsps_mul_s8_aes3.S.obj +[1119/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_bit_rev_lookup_fc32_aes3.S.obj +[1120/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft4r_fc32_arp4.S.obj +[1121/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft2r_bitrev_tables_fc32.c.obj +[1122/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/math/sqrt/float/dsps_sqrt_f32_ansi.c.obj +[1123/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft4r_fc32_ae32_.S.obj +[1124/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft2r_fc32_aes3_.S.obj +[1125/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/fixed/dsps_fft2r_sc16_arp4.S.obj +[1126/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/fixed/dsps_fft2r_sc16_ae32.S.obj +[1127/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft4r_fc32_ansi.c.obj +[1128/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft2r_fc32_ae32.c.obj +[1129/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft4r_bitrev_tables_fc32.c.obj +[1130/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft2r_fc32_ansi.c.obj +[1131/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/float/dsps_fft4r_fc32_ae32.c.obj +[1132/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/fixed/dsps_fft2r_sc16_aes3.S.obj +[1133/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/misc/dsps_d_gen.c.obj +[1134/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fft/fixed/dsps_fft2r_sc16_ansi.c.obj +[1135/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/mem/esp32s3/dsps_memset_aes3.S.obj +[1136/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/misc/dsps_tone_gen.c.obj +[1137/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/misc/dsps_h_gen.c.obj +[1138/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dct/float/dsps_dct_f32.c.obj +[1139/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/cplx_gen/dsps_cplx_gen.c.obj +[1140/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dct/float/dsps_dctiv_f32.c.obj +[1141/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/mem/esp32s3/dsps_memcpy_aes3.S.obj +[1142/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/dct/float/dsps_dstiv_f32.c.obj +[1143/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/cplx_gen/dsps_cplx_gen.S.obj +[1144/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/windows/hann/float/dsps_wind_hann_f32.c.obj +[1145/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/cplx_gen/dsps_cplx_gen_init.c.obj +[1146/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dsps_corr_f32_ae32.S.obj +[1147/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/windows/blackman/float/dsps_wind_blackman_f32.c.obj +[1148/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/snr/float/dsps_snr_f32.cpp.obj +[1149/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/windows/blackman_harris/float/dsps_wind_blackman_harris_f32.c.obj +[1150/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dsps_conv_f32_ae32.S.obj +[1151/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/windows/nuttall/float/dsps_wind_nuttall_f32.c.obj +[1152/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_f32_ae32.S.obj +[1153/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/windows/blackman_nuttall/float/dsps_wind_blackman_nuttall_f32.c.obj +[1154/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dsps_ccorr_f32_ae32.S.obj +[1155/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dsps_corr_f32_ansi.c.obj +[1156/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_f32_arp4.S.obj +[1157/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_f32_aes3.S.obj +[1158/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_sf32_arp4.S.obj +[1159/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dspi_conv_f32_ansi.c.obj +[1160/1743] Performing configure step for 'bootloader' +-- Building ESP-IDF components for target esp32s3 +-- Project sdkconfig file D:/4_Program/firmware2_9/sdkconfig +-- Compiler supported targets: xtensa-esp-elf +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/soc/esp32s3/ld/esp32s3.peripherals.ld +-- Bootloader project name: "bootloader" version: 1 +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.api.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.bt_funcs.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.libgcc.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.wdt.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.version.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom/esp32s3/ld/esp32s3.rom.newlib.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader/subproject/main/ld/esp32s3/bootloader.ld +-- Adding linker script D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader/subproject/main/ld/esp32s3/bootloader.rom.ld +-- Components: bootloader bootloader_support efuse esp_app_format esp_bootloader_format esp_common esp_hw_support esp_rom esp_security esp_system esptool_py freertos hal log main micro-ecc newlib partition_table soc spi_flash xtensa +-- Component paths: D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader_support D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/efuse D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_app_format D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_bootloader_format D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_common D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_hw_support D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_rom D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_security D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esp_system D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/esptool_py D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/freertos D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/hal D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/log D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader/subproject/main D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/bootloader/subproject/components/micro-ecc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/newlib D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/partition_table D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/soc D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/spi_flash D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/xtensa +-- Configuring done (14.4s) +-- Generating done (0.8s) +-- Build files have been written to: D:/4_Program/firmware2_9/build/bootloader +[1161/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/sfdr/float/dsps_sfdr_f32.cpp.obj +[1162/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fird_f32_ae32.S.obj +[1163/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fird_f32_aes3.S.obj +[1164/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dsps_conv_f32_ansi.c.obj +[1165/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_sf32_ae32.S.obj +[1166/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/windows/flat_top/float/dsps_wind_flat_top_f32.c.obj +[1167/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/support/view/dsps_view.cpp.obj +[1168/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/conv/float/dsps_ccorr_f32_ansi.c.obj +[1169/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fir_f32_aes3.S.obj +[1170/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fir_f32_ae32.S.obj +[1171/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_fird_s16_ae32.S.obj +[1172/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_fird_s16_arp4.S.obj +[1173/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fird_f32_arp4.S.obj +[1174/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_f32_ansi.c.obj +[1175/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_fird_s16_aes3.S.obj +[1176/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fird_f32_ansi.c.obj +[1177/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_gen_f32.c.obj +[1178/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/iir/biquad/dsps_biquad_sf32_ansi.c.obj +[1179/1743] Building ASM object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_fir_s16_m_ae32.S.obj +[1180/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_fird_s16_ansi.c.obj +[1181/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fir_f32_ansi.c.obj +[1182/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_firmr_f32_ansi.c.obj +[1183/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fird_init_f32.c.obj +[1184/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_fird_init_s16.c.obj +[1185/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_fir_init_f32.c.obj +[1186/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_firmr_init_s16.c.obj +[1187/1743] Linking C static library esp-idf\espressif__dl_fft\libespressif__dl_fft.a +[1188/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/resampler/dsps_resampler_mr.c.obj +[1189/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/resampler/dsps_resampler_ph.c.obj +[1190/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/float/dsps_firmr_init_f32.c.obj +[1191/1743] Building C object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/fir/fixed/dsps_firmr_s16_ansi.c.obj +[1192/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tool/src/dl_tool_cache.cpp.obj +[1193/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/matrix/mat/mat.cpp.obj +[1194/1743] Building C object esp-idf/espressif__cjson/CMakeFiles/__idf_espressif__cjson.dir/cJSON/cJSON_Utils.c.obj +[1195/1743] Building C object esp-idf/espressif__cjson/CMakeFiles/__idf_espressif__cjson.dir/cJSON/cJSON.c.obj +[1196/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_add2d.cpp.obj +[1197/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tool/src/dl_tool.cpp.obj +[1198/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_add.cpp.obj +[1199/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_and.cpp.obj +[1200/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/kalman/ekf_imu13states/ekf_imu13states.cpp.obj +[1201/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_avg_pool2d.cpp.obj +[1202/1743] Building CXX object esp-idf/espressif__esp-dsp/CMakeFiles/__idf_espressif__esp-dsp.dir/modules/kalman/ekf/common/ekf.cpp.obj +[1203/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_dotprod.cpp.obj +[1204/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_equal.cpp.obj +[1205/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_div.cpp.obj +[1206/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_greaterorequal.cpp.obj +[1207/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_depthwise_conv2d.cpp.obj +[1208/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_greater.cpp.obj +[1209/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_leakyrelu.cpp.obj +[1210/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_less.cpp.obj +[1211/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_conv2d.cpp.obj +[1212/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_lut.cpp.obj +[1213/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_matmul.cpp.obj +[1214/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_lessorequal.cpp.obj +[1215/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_elemwise.cpp.obj +[1216/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_max2d.cpp.obj +[1217/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_max.cpp.obj +[1218/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_min.cpp.obj +[1219/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_max_pool2d.cpp.obj +[1220/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_min2d.cpp.obj +[1221/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_mul2d.cpp.obj +[1222/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_mod.cpp.obj +[1223/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_norm.cpp.obj +[1224/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_mul.cpp.obj +[1225/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_or.cpp.obj +[1226/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_pow.cpp.obj +[1227/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_prelu.cpp.obj +[1228/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_relu.cpp.obj +[1229/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_requantize_linear.cpp.obj +[1230/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_pad.cpp.obj +[1231/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_reduce.cpp.obj +[1232/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_shape.cpp.obj +[1233/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_resize.cpp.obj +[1234/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tensor/src/dl_tensor_base.cpp.obj +[1235/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_sub.cpp.obj +[1236/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_sub2d.cpp.obj +[1237/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/math/src/dl_math.cpp.obj +[1238/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/dl_base_xor.cpp.obj +[1239/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/model/src/dl_model_context.cpp.obj +[1240/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/math/src/dl_math_matrix.cpp.obj +[1241/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/model/src/dl_memory_manager.cpp.obj +[1242/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/fbs_loader/src/fbs_loader.cpp.obj +[1243/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/image/dl_image_draw.cpp.obj +[1244/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/image/dl_image_ppa.cpp.obj +[1245/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/module/src/dl_module_base.cpp.obj +[1246/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_base.cpp.obj +[1247/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/image/dl_image_bmp.cpp.obj +[1248/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/model/src/dl_memory_manager_greedy.cpp.obj +[1249/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_mnp_postprocessor.cpp.obj +[1250/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_espdet_postprocessor.cpp.obj +[1251/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_postprocessor.cpp.obj +[1252/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/image/dl_image_jpeg.cpp.obj +[1253/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_msr_postprocessor.cpp.obj +[1254/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_pico_postprocessor.cpp.obj +[1255/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_detect_yolo11_postprocessor.cpp.obj +[1256/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_pose_yolo11_postprocessor.cpp.obj +[1257/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/detect/dl_seg_yolo11_postprocessor.cpp.obj +[1258/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/image/dl_image_preprocessor.cpp.obj +[1259/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tool/isa/xtensa/dl_xtensa_bzero.S.obj +[1260/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/recognition/dl_feat_base.cpp.obj +[1261/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/image/dl_image_process.cpp.obj +[1262/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/recognition/dl_feat_postprocessor.cpp.obj +[1263/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/recognition/dl_feat_image_preprocessor.cpp.obj +[1264/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/recognition/dl_recognition_database.cpp.obj +[1265/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/audio/common/dl_audio_common.cpp.obj +[1266/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/audio/common/dl_audio_wav.cpp.obj +[1267/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/audio/speech_features/dl_fbank.cpp.obj +[1268/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tool/isa/tie728/dl_tie728_bzero.S.obj +[1269/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tool/isa/tie728/dl_tie728_memcpy.S.obj +[1270/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/tool/isa/tie728/dl_tie728_memset.S.obj +[1271/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/xtensa/dl_xtensa_s16_block.S.obj +[1272/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_dotprod.S.obj +[1273/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_add2d.S.obj +[1274/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16.S.obj +[1275/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_rms_normalization.S.obj +[1276/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_reduce.S.obj +[1277/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_lut.S.obj +[1278/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_conv2d.S.obj +[1279/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_add.S.obj +[1280/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_depthwise_conv2d_block.S.obj +[1281/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_avg_pool2d.S.obj +[1282/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_equal.S.obj +[1283/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_greaterorequal.S.obj +[1284/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_greater.S.obj +[1285/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_max2d.S.obj +[1286/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_lessorequal.S.obj +[1287/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_matmul.S.obj +[1288/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_max_pool2d.S.obj +[1289/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_min2d.S.obj +[1290/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_prelu.S.obj +[1291/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/classification/dl_cls_base.cpp.obj +[1292/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/audio/speech_features/dl_spectrogram.cpp.obj +[1293/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/audio/speech_features/dl_mfcc.cpp.obj +[1294/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_relu.S.obj +[1295/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_mul2d.S.obj +[1296/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_less.S.obj +[1297/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_sub.S.obj +[1298/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_mul.S.obj +[1299/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8.S.obj +[1300/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_requantize_linear.S.obj +[1301/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/classification/imagenet_cls_postprocessor.cpp.obj +[1302/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_unaligned_matmul.S.obj +[1303/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_transpose.S.obj +[1304/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/classification/hand_gesture_cls_postprocessor.cpp.obj +[1305/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_sub2d.S.obj +[1306/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_unaligned.S.obj +[1307/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_add2d.S.obj +[1308/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_avg_pool2d.S.obj +[1309/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_add.S.obj +[1310/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_lessorequal.S.obj +[1311/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_greaterorequal.S.obj +[1312/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/audio/speech_features/dl_speech_features.cpp.obj +[1313/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/vision/classification/dl_cls_postprocessor.cpp.obj +[1314/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_unaligned_depthwise_conv2d.S.obj +[1315/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_equal.S.obj +[1316/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_less.S.obj +[1317/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_max2d.S.obj +[1318/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_mul.S.obj +[1319/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_greater.S.obj +[1320/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_matmul.S.obj +[1321/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_resize.S.obj +[1322/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_conv2d.S.obj +[1323/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s16_unaligned_conv2d.S.obj +[1324/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_prelu.S.obj +[1325/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_sub.S.obj +[1326/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_unaligned_matmul.S.obj +[1327/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_min2d.S.obj +[1328/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_depthwise_conv2d.S.obj +[1329/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_requantize_linear.S.obj +[1330/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_max_pool2d.S.obj +[1331/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_relu.S.obj +[1332/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_sub2d.S.obj +[1333/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_transpose.S.obj +[1334/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_s8_mul2d.S.obj +[1335/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity_compat.c.obj +[1336/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_w8a16_conv2d.S.obj +[1337/1743] Linking C static library esp-idf\console\libconsole.a +[1338/1743] Linking C static library esp-idf\protobuf-c\libprotobuf-c.a +[1339/1743] Building ASM object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/base/isa/tie728/dl_tie728_w8a16_unaligned_conv2d.S.obj +[1340/1743] Linking C static library esp-idf\bt\libbt.a +[1341/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity_utils_cache.c.obj +[1342/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity_runner.c.obj +[1343/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity_port_esp32.c.obj +[1344/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity_utils_memory.c.obj +[1345/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity_utils_freertos.c.obj +[1346/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/port/esp/unity_utils_memory_esp.c.obj +[1347/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/proto-c/constants.pb-c.c.obj +[1348/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/proto-c/sec0.pb-c.c.obj +[1349/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/transports/protocomm_console.c.obj +[1350/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/proto-c/sec1.pb-c.c.obj +[1351/1743] Building C object esp-idf/unity/CMakeFiles/__idf_unity.dir/unity/src/unity.c.obj +[1352/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/common/protocomm.c.obj +[1353/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/proto-c/sec2.pb-c.c.obj +[1354/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/proto-c/session.pb-c.c.obj +[1355/1743] Building C object esp-idf/esp_https_server/CMakeFiles/__idf_esp_https_server.dir/src/https_server.c.obj +[1356/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/Partition.cpp.obj +[1357/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/transports/protocomm_httpd.c.obj +[1358/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/security/security0.c.obj +[1359/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/SPI_Flash.cpp.obj +[1360/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/crypto/srp6a/esp_srp.c.obj +[1361/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/crypto/srp6a/esp_srp_mpi.c.obj +[1362/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/WL_Ext_Safe.cpp.obj +[1363/1743] Linking C static library esp-idf\spiffs\libspiffs.a +[1364/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/security/security2.c.obj +[1365/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/WL_Ext_Perf.cpp.obj +[1366/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/crc32.cpp.obj +[1367/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/security/security1.c.obj +[1368/1743] Building C object esp-idf/protocomm/CMakeFiles/__idf_protocomm.dir/src/transports/protocomm_nimble.c.obj +[1369/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/wear_levelling.cpp.obj +[1370/1743] Building C object esp-idf/espressif__button/CMakeFiles/__idf_espressif__button.dir/button_adc.c.obj +[1371/1743] Building CXX object esp-idf/wear_levelling/CMakeFiles/__idf_wear_levelling.dir/WL_Flash.cpp.obj +[1372/1743] Building C object esp-idf/espressif__button/CMakeFiles/__idf_espressif__button.dir/button_gpio.c.obj +[1373/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/entcode.c.obj +[1374/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/cwrs.c.obj +[1375/1743] Building C object esp-idf/espressif__button/CMakeFiles/__idf_espressif__button.dir/button_matrix.c.obj +[1376/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/celt.c.obj +[1377/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/entdec.c.obj +[1378/1743] Building C object esp-idf/json/CMakeFiles/__idf_json.dir/cJSON/cJSON_Utils.c.obj +[1379/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/entenc.c.obj +[1380/1743] Building C object esp-idf/espressif__button/CMakeFiles/__idf_espressif__button.dir/iot_button.c.obj +[1381/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/laplace.c.obj +[1382/1743] Building C object esp-idf/json/CMakeFiles/__idf_json.dir/cJSON/cJSON.c.obj +[1383/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/modes.c.obj +[1384/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/mathops.c.obj +[1385/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/mdct.c.obj +[1386/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/pitch.c.obj +[1387/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/bands.c.obj +[1388/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/celt_decoder.c.obj +[1389/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus.c.obj +[1390/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/rate.c.obj +[1391/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/vq.c.obj +[1392/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/kiss_fft.c.obj +[1393/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_multistream.c.obj +[1394/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/celt_lpc.c.obj +[1395/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/quant_bands.c.obj +[1396/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_multistream_decoder.c.obj +[1397/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_decoder.c.obj +[1398/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/repacketizer.c.obj +[1399/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/extensions.c.obj +[1400/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/mapping_matrix.c.obj +[1401/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/celt/celt_encoder.c.obj +[1402/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/CNG.c.obj +[1403/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/code_signs.c.obj +[1404/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_projection_encoder.c.obj +[1405/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/init_decoder.c.obj +[1406/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decode_frame.c.obj +[1407/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decoder_set_fs.c.obj +[1408/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_projection_decoder.c.obj +[1409/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_multistream_encoder.c.obj +[1410/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decode_indices.c.obj +[1411/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decode_pulses.c.obj +[1412/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decode_core.c.obj +[1413/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decode_parameters.c.obj +[1414/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/dec_API.c.obj +[1415/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/src/opus_encoder.c.obj +[1416/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/encode_pulses.c.obj +[1417/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/gain_quant.c.obj +[1418/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/interpolate.c.obj +[1419/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/LP_variable_cutoff.c.obj +[1420/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/encode_indices.c.obj +[1421/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_decode.c.obj +[1422/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_gain.c.obj +[1423/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/enc_API.c.obj +[1424/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_LTP.c.obj +[1425/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/shell_coder.c.obj +[1426/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_NLSF_CB_NB_MB.c.obj +[1427/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_other.c.obj +[1428/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_NLSF_CB_WB.c.obj +[1429/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_pitch_lag.c.obj +[1430/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NSQ.c.obj +[1431/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/tables_pulses_per_block.c.obj +[1432/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/PLC.c.obj +[1433/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/VAD.c.obj +[1434/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/VQ_WMat_EC.c.obj +[1435/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NSQ_del_dec.c.obj +[1436/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_encode.c.obj +[1437/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/control_audio_bandwidth.c.obj +[1438/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_VQ.c.obj +[1439/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/HP_variable_cutoff.c.obj +[1440/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_unpack.c.obj +[1441/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_del_dec_quant.c.obj +[1442/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/quant_LTP_gains.c.obj +[1443/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/stereo_MS_to_LR.c.obj +[1444/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/control_SNR.c.obj +[1445/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/init_encoder.c.obj +[1446/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/ana_filt_bank_1.c.obj +[1447/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/check_control_input.c.obj +[1448/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/biquad_alt.c.obj +[1449/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/debug.c.obj +[1450/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/bwexpander_32.c.obj +[1451/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/decode_pitch.c.obj +[1452/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/bwexpander.c.obj +[1453/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/inner_prod_aligned.c.obj +[1454/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/stereo_LR_to_MS.c.obj +[1455/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/lin2log.c.obj +[1456/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/A2NLSF.c.obj +[1457/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_VQ_weights_laroia.c.obj +[1458/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/control_codec.c.obj +[1459/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/table_LSF_cos.c.obj +[1460/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/process_NLSFs.c.obj +[1461/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF_stabilize.c.obj +[1462/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/pitch_est_tables.c.obj +[1463/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/log2lin.c.obj +[1464/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/LPC_inv_pred_gain.c.obj +[1465/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/LPC_analysis_filter.c.obj +[1466/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_down2.c.obj +[1467/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/NLSF2A.c.obj +[1468/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_private_AR2.c.obj +[1469/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_rom.c.obj +[1470/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_down2_3.c.obj +[1471/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_private_IIR_FIR.c.obj +[1472/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler.c.obj +[1473/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/sigm_Q15.c.obj +[1474/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/sum_sqr_shift.c.obj +[1475/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_private_up2_HQ.c.obj +[1476/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/sort.c.obj +[1477/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/resampler_private_down_FIR.c.obj +[1478/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/stereo_find_predictor.c.obj +[1479/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/LTP_scale_ctrl_FIX.c.obj +[1480/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/stereo_decode_pred.c.obj +[1481/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/stereo_quant_pred.c.obj +[1482/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/stereo_encode_pred.c.obj +[1483/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/find_LPC_FIX.c.obj +[1484/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/LTP_analysis_filter_FIX.c.obj +[1485/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/LPC_fit.c.obj +[1486/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/find_LTP_FIX.c.obj +[1487/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/corrMatrix_FIX.c.obj +[1488/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/regularize_correlations_FIX.c.obj +[1489/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/encode_frame_FIX.c.obj +[1490/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/find_pitch_lags_FIX.c.obj +[1491/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/residual_energy16_FIX.c.obj +[1492/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/autocorr_FIX.c.obj +[1493/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/find_pred_coefs_FIX.c.obj +[1494/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/k2a_FIX.c.obj +[1495/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/k2a_Q16_FIX.c.obj +[1496/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/residual_energy_FIX.c.obj +[1497/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/warped_autocorrelation_FIX.c.obj +[1498/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/apply_sine_window_FIX.c.obj +[1499/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/process_gains_FIX.c.obj +[1500/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/burg_modified_FIX.c.obj +[1501/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/arm/arm_silk_map.c.obj +[1502/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/vector_ops_FIX.c.obj +[1503/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/noise_shape_analysis_FIX.c.obj +[1504/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/schur64_FIX.c.obj +[1505/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/pitch_analysis_core_FIX.c.obj +[1506/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/esp_codec_dev_vol.c.obj +[1507/1743] Building C object esp-idf/78__esp-opus/CMakeFiles/__idf_78__esp-opus.dir/silk/fixed/schur_FIX.c.obj +[1508/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/esp_codec_dev_if.c.obj +[1509/1743] Linking C static library esp-idf\espressif__esp-dsp\libespressif__esp-dsp.a +[1510/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/audio_codec_sw_vol.c.obj +[1511/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/platform/audio_codec_gpio.c.obj +[1512/1743] Linking C static library esp-idf\espressif__cjson\libespressif__cjson.a +[1513/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/platform/esp_codec_dev_os.c.obj +[1514/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es8156/es8156.c.obj +[1515/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/platform/audio_codec_ctrl_spi.c.obj +[1516/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/platform/audio_codec_ctrl_i2c.c.obj +[1517/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/esp_codec_dev.c.obj +[1518/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/platform/audio_codec_data_i2s.c.obj +[1519/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es7243e/es7243e.c.obj +[1520/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/tas5805m/tas5805m.c.obj +[1521/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es8311/es8311.c.obj +[1522/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es8388/es8388.c.obj +[1523/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es7243/es7243.c.obj +[1524/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es8374/es8374.c.obj +[1525/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/aw88298/aw88298.c.obj +[1526/1743] Building C object esp-idf/espressif__esp-sr/CMakeFiles/__idf_espressif__esp-sr.dir/src/esp_sr_debug.c.obj +[1527/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es7210/es7210.c.obj +[1528/1743] Building C object esp-idf/espressif__led_strip/CMakeFiles/__idf_espressif__led_strip.dir/src/led_strip_rmt_encoder.c.obj +[1529/1743] Linking C static library esp-idf\unity\libunity.a +[1530/1743] Building C object esp-idf/espressif__esp_codec_dev/CMakeFiles/__idf_espressif__esp_codec_dev.dir/device/es8389/es8389.c.obj +[1531/1743] Building C object esp-idf/espressif__esp-sr/CMakeFiles/__idf_espressif__esp-sr.dir/src/esp_mn_speech_commands.c.obj +[1532/1743] Building C object esp-idf/espressif__esp-sr/CMakeFiles/__idf_espressif__esp-sr.dir/src/model_path.c.obj +[1533/1743] Building C object esp-idf/espressif__led_strip/CMakeFiles/__idf_espressif__led_strip.dir/src/led_strip_api.c.obj +[1534/1743] Building C object esp-idf/app_trace/CMakeFiles/__idf_app_trace.dir/app_trace_util.c.obj +[1535/1743] Building C object esp-idf/espressif__led_strip/CMakeFiles/__idf_espressif__led_strip.dir/src/led_strip_spi_dev.c.obj +[1536/1743] Building C object esp-idf/app_trace/CMakeFiles/__idf_app_trace.dir/host_file_io.c.obj +[1537/1743] Building C object esp-idf/espressif__esp-sr/CMakeFiles/__idf_espressif__esp-sr.dir/src/esp_process_sdkconfig.c.obj +[1538/1743] Building C object esp-idf/cmock/CMakeFiles/__idf_cmock.dir/CMock/src/cmock.c.obj +[1539/1743] Building C object esp-idf/app_trace/CMakeFiles/__idf_app_trace.dir/port/port_uart.c.obj +[1540/1743] Building C object esp-idf/esp_driver_cam/CMakeFiles/__idf_esp_driver_cam.dir/dvp_share_ctrl.c.obj +[1541/1743] Building C object esp-idf/espressif__led_strip/CMakeFiles/__idf_espressif__led_strip.dir/src/led_strip_rmt_dev.c.obj +[1542/1743] Building C object esp-idf/app_trace/CMakeFiles/__idf_app_trace.dir/app_trace.c.obj +[1543/1743] Building C object esp-idf/esp_driver_cam/CMakeFiles/__idf_esp_driver_cam.dir/dvp/src/esp_cam_ctlr_dvp_gdma.c.obj +[1544/1743] Linking C static library esp-idf\esp_https_server\libesp_https_server.a +[1545/1743] Building C object esp-idf/esp_driver_cam/CMakeFiles/__idf_esp_driver_cam.dir/esp_cam_ctlr.c.obj +[1546/1743] Building C object esp-idf/esp_eth/CMakeFiles/__idf_esp_eth.dir/src/esp_eth_netif_glue.c.obj +[1547/1743] Building C object esp-idf/esp_eth/CMakeFiles/__idf_esp_eth.dir/src/esp_eth.c.obj +[1548/1743] Building C object esp-idf/esp_hid/CMakeFiles/__idf_esp_hid.dir/src/nimble_hidd.c.obj +[1549/1743] Building C object esp-idf/esp_hid/CMakeFiles/__idf_esp_hid.dir/src/esp_hid_common.c.obj +[1550/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/src/esp_lcd_common.c.obj +[1551/1743] Building C object esp-idf/esp_driver_cam/CMakeFiles/__idf_esp_driver_cam.dir/dvp/src/esp_cam_ctlr_dvp_cam.c.obj +[1552/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/src/esp_lcd_panel_ssd1306.c.obj +[1553/1743] Building C object esp-idf/esp_eth/CMakeFiles/__idf_esp_eth.dir/src/phy/esp_eth_phy_802_3.c.obj +[1554/1743] Building C object esp-idf/esp_hid/CMakeFiles/__idf_esp_hid.dir/src/nimble_hidh.c.obj +[1555/1743] Building C object esp-idf/esp_hid/CMakeFiles/__idf_esp_hid.dir/src/esp_hidd.c.obj +[1556/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/src/esp_lcd_panel_nt35510.c.obj +[1557/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/src/esp_lcd_panel_ops.c.obj +[1558/1743] Building C object esp-idf/esp_hid/CMakeFiles/__idf_esp_hid.dir/src/esp_hidh.c.obj +[1559/1743] Linking C static library esp-idf\protocomm\libprotocomm.a +[1560/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/src/esp_lcd_panel_st7789.c.obj +[1561/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/src/esp_lcd_panel_io.c.obj +[1562/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/i2c/esp_lcd_panel_io_i2c_v2.c.obj +[1563/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/i2c/esp_lcd_panel_io_i2c_v1.c.obj +[1564/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/spi/esp_lcd_panel_io_spi.c.obj +[1565/1743] Building C object esp-idf/esp_local_ctrl/CMakeFiles/__idf_esp_local_ctrl.dir/src/esp_local_ctrl_handler.c.obj +[1566/1743] Building C object esp-idf/esp_local_ctrl/CMakeFiles/__idf_esp_local_ctrl.dir/proto-c/esp_local_ctrl.pb-c.c.obj +[1567/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_init.c.obj +[1568/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_sha.c.obj +[1569/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_crc.c.obj +[1570/1743] Linking C static library esp-idf\wear_levelling\libwear_levelling.a +[1571/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_binary.c.obj +[1572/1743] Building C object esp-idf/esp_local_ctrl/CMakeFiles/__idf_esp_local_ctrl.dir/src/esp_local_ctrl_transport_httpd.c.obj +[1573/1743] Building C object esp-idf/esp_local_ctrl/CMakeFiles/__idf_esp_local_ctrl.dir/src/esp_local_ctrl.c.obj +[1574/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_uart.c.obj +[1575/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/i80/esp_lcd_panel_io_i80.c.obj +[1576/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_common.c.obj +[1577/1743] Building C object esp-idf/esp_local_ctrl/CMakeFiles/__idf_esp_local_ctrl.dir/src/esp_local_ctrl_transport_ble.c.obj +[1578/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_elf.c.obj +[1579/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/port/xtensa/core_dump_port.c.obj +[1580/1743] Linking C static library esp-idf\json\libjson.a +[1581/1743] Building C object esp-idf/espcoredump/CMakeFiles/__idf_espcoredump.dir/src/core_dump_flash.c.obj +[1582/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/diskio/diskio.c.obj +[1583/1743] Building C object esp-idf/esp_lcd/CMakeFiles/__idf_esp_lcd.dir/rgb/esp_lcd_panel_rgb.c.obj +[1584/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/diskio/diskio_rawflash.c.obj +[1585/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/diskio/diskio_wl.c.obj +[1586/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/diskio/diskio_sdmmc.c.obj +[1587/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/port/freertos/ffsystem.c.obj +[1588/1743] Building C object esp-idf/mqtt/CMakeFiles/__idf_mqtt.dir/esp-mqtt/lib/mqtt_outbox.c.obj +[1589/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/src/ffunicode.c.obj +[1590/1743] Building C object esp-idf/nvs_sec_provider/CMakeFiles/__idf_nvs_sec_provider.dir/nvs_sec_provider.c.obj +[1591/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/vfs/vfs_fat_spiflash.c.obj +[1592/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/vfs/vfs_fat_sdmmc.c.obj +[1593/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/vfs/vfs_fat.c.obj +[1594/1743] Building C object esp-idf/perfmon/CMakeFiles/__idf_perfmon.dir/xtensa_perfmon_apis.c.obj +[1595/1743] Building C object esp-idf/perfmon/CMakeFiles/__idf_perfmon.dir/xtensa_perfmon_access.c.obj +[1596/1743] Building C object esp-idf/mqtt/CMakeFiles/__idf_mqtt.dir/esp-mqtt/lib/mqtt_msg.c.obj +[1597/1743] Building C object esp-idf/mqtt/CMakeFiles/__idf_mqtt.dir/esp-mqtt/lib/platform_esp32_idf.c.obj +[1598/1743] Building C object esp-idf/perfmon/CMakeFiles/__idf_perfmon.dir/xtensa_perfmon_masks.c.obj +[1599/1743] Building C object esp-idf/rt/CMakeFiles/__idf_rt.dir/FreeRTOS_POSIX_utils.c.obj +[1600/1743] Building C object esp-idf/rt/CMakeFiles/__idf_rt.dir/FreeRTOS_POSIX_mqueue.c.obj +[1601/1743] Building C object esp-idf/touch_element/CMakeFiles/__idf_touch_element.dir/touch_button.c.obj +[1602/1743] Building C object esp-idf/fatfs/CMakeFiles/__idf_fatfs.dir/src/ff.c.obj +[1603/1743] Building C object esp-idf/touch_element/CMakeFiles/__idf_touch_element.dir/touch_matrix.c.obj +[1604/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/usb_private.c.obj +[1605/1743] Building C object esp-idf/touch_element/CMakeFiles/__idf_touch_element.dir/touch_element.c.obj +[1606/1743] Building C object esp-idf/touch_element/CMakeFiles/__idf_touch_element.dir/touch_slider.c.obj +[1607/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/hub.c.obj +[1608/1743] Building C object esp-idf/mqtt/CMakeFiles/__idf_mqtt.dir/esp-mqtt/mqtt_client.c.obj +[1609/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/enum.c.obj +[1610/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/wifi_config.c.obj +[1611/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/wifi_ctrl.c.obj +[1612/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/usb_helpers.c.obj +[1613/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/wifi_scan.c.obj +[1614/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/usbh.c.obj +[1615/1743] Linking C static library esp-idf\espressif__button\libespressif__button.a +[1616/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/usb_phy.c.obj +[1617/1743] Linking C static library esp-idf\espressif__led_strip\libespressif__led_strip.a +[1618/1743] Linking C static library esp-idf\espressif__esp_codec_dev\libespressif__esp_codec_dev.a +[1619/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/handlers.c.obj +[1620/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/hcd_dwc.c.obj +[1621/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/scheme_console.c.obj +[1622/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/proto-c/wifi_scan.pb-c.c.obj +[1623/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/proto-c/wifi_config.pb-c.c.obj +[1624/1743] Building C object esp-idf/usb/CMakeFiles/__idf_usb.dir/usb_host.c.obj +[1625/1743] Linking C static library esp-idf\78__esp-opus\lib78__esp-opus.a +[1626/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/proto-c/wifi_constants.pb-c.c.obj +[1627/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/proto-c/wifi_ctrl.pb-c.c.obj +[1628/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/packed_opus_reader.cc.obj +[1629/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/scheme_softap.c.obj +[1630/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/manager.c.obj +[1631/1743] Building C object esp-idf/wifi_provisioning/CMakeFiles/__idf_wifi_provisioning.dir/src/scheme_ble.c.obj +[1632/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/app/application.cc.obj +[1633/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/pcm_rate_converter.cc.obj +[1634/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/activation/activation_replay_service.cc.obj +[1635/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/playback_controller.cc.obj +[1636/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/voice_activity_detector.cc.obj +[1637/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/opus_frame_decoder.cc.obj +[1638/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/opus_frame_encoder.cc.obj +[1639/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/embedded_prompt_catalog.cc.obj +[1640/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/connectivity_policy.cc.obj +[1641/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/wake_word_detector.cc.obj +[1642/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/capture_pipeline.cc.obj +[1643/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/connectivity_manager.cc.obj +[1644/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/local_prompt_player.cc.obj +[1645/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/voice_dsp.cc.obj +[1646/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/playback_pipeline.cc.obj +[1647/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/ml307_at_parser.cc.obj +[1648/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/dual_network_policy.cc.obj +[1649/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/reconnect_backoff.cc.obj +[1650/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/core/app_event.cc.obj +[1651/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/main.cc.obj +[1652/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/wifi_credential_store.cc.obj +[1653/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/diagnostics/trace_context.cc.obj +[1654/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/configuration/remote_behavior_config.cc.obj +[1655/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/diagnostics/device_log_formatter.cc.obj +[1656/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/core/app_effect.cc.obj +[1657/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/app/composition_root.cc.obj +D:/4_Program/firmware2_9/main/app/composition_root.cc: In member function 'bool borla::CompositionRoot::Initialize()': +D:/4_Program/firmware2_9/main/app/composition_root.cc:177:23: warning: unused variable 'ret' [-Wunused-variable] + 177 | esp_err_t ret = tca9555_.read_p1_input(&val); + | ^~~ +[1658/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/core/playback_types.cc.obj +[1659/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/connectivity/dual_network_transport.cc.obj +[1660/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/core/remote_behavior.cc.obj +[1661/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/diagnostics/runtime_diagnostics_service.cc.obj +[1662/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/core/runtime_state.cc.obj +[1663/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/audio/voice_frontend.cc.obj +[1664/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/core/state_reducer.cc.obj +[1665/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/diagnostics/audio_tap.cc.obj +[1666/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/memory/memory_types.cc.obj +[1667/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/friend/friend_types.cc.obj +[1668/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/adapters/effect_router.cc.obj +[1669/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/capacitive_touch_input.cc.obj +[1670/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/friend/friend_service.cc.obj +[1671/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/button_input.cc.obj +[1672/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/battery_monitor.cc.obj +[1673/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/bmi270_sensor.cc.obj +[1674/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/friend/friend_store.cc.obj +[1675/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/ble_friend_exchange.cc.obj +[1676/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/i2c_bus.cc.obj +[1677/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/borla_s3_platform.cc.obj +[1678/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/memory/memory_cache.cc.obj +[1679/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/ble_provisioning_gatt.cc.obj +[1680/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/ota/ota_types.cc.obj +[1681/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/protocol/binary_audio_protocol.cc.obj +[1682/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/adapters/esp_audio_engine.cc.obj +[1683/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/ota/ota_endpoint.cc.obj +[1684/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/es8311_audio_output.cc.obj +[1685/1743] Building CXX object esp-idf/espressif__esp-dl/CMakeFiles/__idf_espressif__esp-dl.dir/dl/model/src/dl_model_base.cpp.obj +[1686/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/esp_wifi_transport.cc.obj +[1687/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/ota/ota_response_parser.cc.obj +[1688/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/protocol/protocol_message_builder.cc.obj +[1689/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/ml307_transport.cc.obj +[1690/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/protocol/websocket_uri.cc.obj +[1691/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/esp_websocket_transport.cc.obj +[1692/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/ws2812_led.cc.obj +[1693/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/protocol/realtime_config.cc.obj +[1694/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/provisioning/ble_provisioning_codec.cc.obj +[1695/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/protocol/server_message_dispatcher.cc.obj +[1696/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/alarm_schedule.cc.obj +[1697/1743] Linking C static library esp-idf\espressif__esp-dl\libespressif__esp-dl.a +[1698/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/provisioning/ble_provisioning_service.cc.obj +[1699/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/ota/ota_service.cc.obj +[1700/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/reminder_schedule.cc.obj +[1701/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/power/idle_service.cc.obj +[1702/1743] Linking C static library esp-idf\espressif__esp-sr\libespressif__esp-sr.a +[1703/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/sensor/battery_estimator.cc.obj +[1704/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/alert_ringer.cc.obj +[1705/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/schedule_coordinator.cc.obj +[1706/1743] Linking C static library esp-idf\app_trace\libapp_trace.a +[1707/1743] Linking C static library esp-idf\cmock\libcmock.a +[1708/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/reminder_service.cc.obj +[1709/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/sensor/sensor_message_codec.cc.obj +[1710/1743] Linking C static library esp-idf\esp_eth\libesp_eth.a +[1711/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/sensor/imu_processor.cc.obj +[1712/1743] Linking C static library esp-idf\esp_driver_cam\libesp_driver_cam.a +[1713/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/power/power_service.cc.obj +[1714/1743] Building C object esp-idf/main/CMakeFiles/__idf_main.dir/__/managed_components/espressif__esp-dsp/applications/m5stack_core_s3/apps/kalman_filter/main/bmi270_context.c.obj +[1715/1743] Linking C static library esp-idf\esp_hid\libesp_hid.a +[1716/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/sensor/sensor_types.cc.obj +[1717/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/protocol/realtime_protocol.cc.obj +[1718/1743] Linking C static library esp-idf\esp_lcd\libesp_lcd.a +[1719/1743] Linking C static library esp-idf\esp_local_ctrl\libesp_local_ctrl.a +[1720/1743] Linking C static library esp-idf\fatfs\libfatfs.a +[1721/1743] Linking C static library esp-idf\espcoredump\libespcoredump.a +[1722/1743] Linking C static library esp-idf\mqtt\libmqtt.a +[1723/1743] Linking C static library esp-idf\perfmon\libperfmon.a +[1724/1743] Linking C static library esp-idf\rt\librt.a +[1725/1743] Linking C static library esp-idf\nvs_sec_provider\libnvs_sec_provider.a +[1726/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/alarm_store.cc.obj +[1727/1743] Linking C static library esp-idf\usb\libusb.a +[1728/1743] Linking C static library esp-idf\touch_element\libtouch_element.a +[1729/1743] Linking C static library esp-idf\wifi_provisioning\libwifi_provisioning.a +[1730/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/platform/borla_s3/tca9555.cc.obj +[1731/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/schedule/alarm_service.cc.obj +[1732/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/sensor/sensor_service.cc.obj +[1733/1743] Building CXX object esp-idf/main/CMakeFiles/__idf_main.dir/sensor/touch_channel.cc.obj +[1734/1743] Performing build step for 'bootloader' +[1/2] Generating binary image from built executable +esptool.py v4.10.0 +Creating esp32s3 image... +Merged 2 ELF sections +Successfully created esp32s3 image. +Generated D:/4_Program/firmware2_9/build/bootloader/bootloader.bin +[2/2] C:\WINDOWS\system32\cmd.exe /C "cd /D D:\4_Program\firmware2_9\build\bootloader\esp-idf\esptool_py && D:\software\Espressif\python_env\idf5.4_py3.11_env\Scripts\python.exe D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/partition_table/check_sizes.py --offset 0x8000 bootloader 0x0 D:/4_Program/firmware2_9/build/bootloader/bootloader.bin" +Bootloader binary size 0x5180 bytes. 0x2e80 bytes (36%) free. +[1735/1743] No install step for 'bootloader' +[1736/1743] Completed 'bootloader' +[1737/1743] Linking C static library esp-idf\main\libmain.a +[1738/1743] Generating ld/sections.ld +[1739/1743] Building C object CMakeFiles/borla-firmware2.elf.dir/project_elf_src_esp32s3.c.obj +[1740/1743] Linking CXX executable borla-firmware2.elf +[1741/1743] Generating binary image from built executable +esptool.py v4.10.0 +Creating esp32s3 image... +Merged 4 ELF sections +Successfully created esp32s3 image. +Generated D:/4_Program/firmware2_9/build/borla-firmware2.bin +[1742/1743] C:\WINDOWS\system32\cmd.exe /C "cd /D D:\4_Program\firmware2_9\build\esp-idf\esptool_py && D:\software\Espressif\python_env\idf5.4_py3.11_env\Scripts\python.exe D:/software/Espressif/frameworks/esp-idf-v5.4.3/components/partition_table/check_sizes.py --offset 0x8000 partition --type app D:/4_Program/firmware2_9/build/partition_table/partition-table.bin D:/4_Program/firmware2_9/build/borla-firmware2.bin" +borla-firmware2.bin binary size 0x32ec20 bytes. Smallest app partition is 0x400000 bytes. 0xd13e0 bytes (20%) free. + +Project build complete. To flash, run: + idf.py flash +or + idf.py -p PORT flash +or + python -m esptool --chip esp32s3 -b 460800 --before default_reset --after hard_reset write_flash --flash_mode dio --flash_size 16MB --flash_freq 80m 0x0 build\bootloader\bootloader.bin 0x8000 build\partition_table\partition-table.bin 0xf000 build\ota_data_initial.bin 0x20000 build\borla-firmware2.bin 0x820000 build\srmodels\srmodels.bin +or from the "D:\4_Program\firmware2_9\build" directory + python -m esptool --chip esp32s3 -b 460800 --before default_reset --after hard_reset write_flash "@flash_args" diff --git a/docs/activation-and-memory.md b/docs/activation-and-memory.md new file mode 100644 index 0000000..09c0b0e --- /dev/null +++ b/docs/activation-and-memory.md @@ -0,0 +1,65 @@ +# Firmware 2 激活码播放与记忆缓存 + +> 实现阶段:重构路线图阶段 13 +> 当前状态:代码、协议测试和 ESP-IDF 构建完成,等待 server/真机验收 + +## 1. 协议先行 + +协议定义位于 `protocols/websocket_protocol.md`: + +- ClientHello `features.play_local_sequence=true`。 +- Server 可下发 `play_local_sequence`。 +- ClientHello 可携带 `memory_cache`。 +- Server 可下发 `memory_sync`。 + +所有字符串都使用固定上限:儿童昵称最多 63 字节,记忆摘要最多 2047 字节, +互动次数为非负 32 位整数。非法类型、超长字符串、负数和超过 16 项的序列在 +dispatcher 边界拒绝。 + +## 2. 激活码顺序播放 + +`play_local_sequence` 最多包含 16 个本地提示项。播放器先解析并固定本次所有 +资源,再创建一个 PlaybackSession,整个序列不会与 TTS 或其他提示音混播。 + +包含 `activation_device`/`activation_prompt` 时使用激活码节奏: + +- 激活引导音后静音 1000ms。 +- 数字之间静音 150ms。 +- 整个序列扬声器排空后等待 6 秒,再重复同一序列。 +- TTS、本地提示、播放抢占、来电、好友模式、闹钟、Idle 或生命周期变化会 + 停止重播并取消旧 session。 + +generation 和 session ID 同时防止旧 timer、旧 producer 或迟到 drained 事件 +重新启动已经取消的序列。 + +## 3. 记忆缓存 + +`NvsMemoryCache` 使用 namespace `memory2`、key `snapshot`,记录包含 magic、 +版本、固定大小快照和 FNV 校验。写入顺序为 `nvs_set_blob` + `nvs_commit`, +只有成功后才替换内存快照。 + +连接时若存在有效数据,Realtime 将快照放入 ClientHello;若完整 hello 超过控制 +消息上限,会安全回退为不带缓存的 hello,连接本身仍可继续。收到合法 +`memory_sync` 后同步写入 NVS,失败只产生协议诊断,不关闭当前会话。 + +## 4. 旧固件迁移 + +分区表保留 `claude_mem` 数据分区。首次未找到新 NVS 快照时: + +1. 校验旧分区 `BORL` magic、长度和 64KB 上限。 +2. 从 PSRAM 分配临时 JSON 缓冲并读取。 +3. 迁移旧字段 `name`、`brain`、`count`。 +4. 对字符串按 UTF-8 边界截断到新容量。 +5. 校验后写入 `memory2/snapshot`。 + +旧分区不擦除,回滚到旧固件时仍保留原数据。 + +## 5. 待联调 + +- server 只在 feature 存在时下发顺序播放。 +- 六位激活码顺序、停顿和 6 秒循环的实际听感。 +- TTS/按键/来电/闹钟打断后不再复播。 +- `memory_sync` 写入后重启,ClientHello 能回传一致快照。 +- 从带真实旧 `claude_mem` 数据的设备升级并迁移。 +- NVS 空间不足、旧分区损坏、超长 UTF-8 和 hello 容量回退。 + diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..9d87440 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,155 @@ +# Firmware 2 基础架构 + +> 实施进度和逐步验收清单见 +> [Firmware 2 重构路线图](refactoring-roadmap.md)。 +> 旧固件逐项功能的迁移状态见 +> [迁移清单](migration-from-firmware.md)。 + +## 当前状态 + +阶段 0~13 的计划代码均已在 `firmware2` 独立实现:控制面、播放与采集、WiFi/ +ML307 双网络、Realtime、Voice Frontend、BLE 配网、传感器、日程、电源、OTA、 +通话、好友、激活码序列、记忆缓存和运行诊断。host tests 17/17 以及 ESP-IDF +5.4.3 全量构建通过。2026-07-21 真机日志累计运行到 45 分 53 秒:TLS/hello 和 +多轮对话正常,无 panic、watchdog、命令池耗尽、断线或重连风暴。栈尾 watchpoint +将最后一次随机调度器崩溃定位到 `friend_service2` 的 NVS 保存栈溢出;好友、闹钟 +和记忆的大型持久化工作对象已迁入 PSRAM,相关任务预算也已加固。TLS 内存、提示 +音 worker 和无效电池误关机修复均已得到真机验证。硬件声学、小程序、SIM、双设备、 +OTA/低功耗和 24h/72h 长期稳定性仍等待验收。长日志暴露的 TTS 首帧竞态与关机 +WebSocket/WiFi 收敛竞态已完成代码修复和构建,等待复刷确认;具体状态以路线图和 +验证矩阵为准。应用期普通 `ESP_LOG` 现统一携带设备 MAC 与校时后的本地日历 +毫秒时间;Realtime 已解析并打印完整 STT 输入与 TTS 分句输出。两项均已通过 +host/ESP 构建。新增文本缓冲曾使按值解析产生 4736-byte 栈帧并导致 ServerHello +阶段重复重启;现已改为 PSRAM 原位解析,机器码栈帧降至 64 bytes并加入编译门禁。 +串口格式、中文完整性和连续启动 10 次仍等待复刷确认。TTS 打断保留本地 WakeNet +硬打断;自然插话已改成 server 唯一裁决的 `candidate → rejected/confirmed` 两阶段 +协议。candidate 只暂停并保留播放队列,ASR 与 TTS 文本校验后才恢复或取消。 +旧的本地能量 detector、跨帧相关性和固定 60ms reference 延迟均已删除;捕获原始/ +处理缓冲已拆分,TTS 插话使用单帧低延迟上行。`tts:stop` 到物理播放排空之间继续 +保持 AEC/tail 上行,避免丢失尾部新问题;WakeNet 冷却使用单调时钟且 reference +miss 不再跳过检测。firmware2 Host 17/17、server 打断相关定向回归 85/85 和 ESP +构建通过,等待真机验证时延、恢复连续性和误取消率。 + +## 1. 控制面 + +所有异步输入转换为小型 `AppEvent`: + +```text +ISR / timer / audio / network / protocol / sensor + │ + ▼ + AppEventQueue + │ + ▼ + Application + │ + ReduceState(state,event) + │ + ┌──────────┴──────────┐ + ▼ ▼ + RuntimeState AppEffect[] + │ + ▼ + Effect adapters +``` + +`ReduceState` 是纯函数,不调用 ESP-IDF,不持有设备句柄。所有状态变更先经过 +`ValidateRuntimeState`。 + +## 2. 数据面 + +音频帧、Opus 包、IMU 批量数据不会经过控制面事件队列: + +```text +Mic → Capture → Voice Frontend → Opus Encoder → Realtime transport +Speaker ← Playback ← Opus Decoder ← Realtime transport +``` + +数据面只在生命周期边界发布事件,例如: + +- TTS 开始 +- TTS 输入流结束 +- 扬声器队列排空 +- 播放失败 +- 唤醒词命中 + +## 3. 状态所有权 + +`RuntimeState` 拆分为六个正交维度: + +- Lifecycle:启动、运行、配网、升级、关机 +- Connectivity:离线、连接中、在线 +- Realtime:实时通道关闭、打开中、已打开 +- Conversation:空闲、监听、播报 +- Call:未通话、响铃、通话 +- Playback:空闲、流入中、排空中 + +任何 adapter 都不能直接写 `RuntimeState`。 + +## 4. Effect + +归约器不执行硬件或网络操作,而是输出 effect,例如: + +- 启动网络 +- 打开实时通道 +- 应用音频策略 +- 设置 LED +- 进入配网 +- 开始 OTA + +`CompositionRoot` 已经装配真实 `EffectRouter`。当前板级 Effect 进入 +`BorlaS3Platform`,音频 Effect 进入 `EspAudioEngine`,网络 Effect 进入 +`ConnectivityManager`,实时协议 Effect 进入 `RealtimeProtocol`,配网进入 +`BleProvisioningService`,OTA 进入 `OtaService`。日程和电源能力由 observer/service +边界接收控制事件,不允许 timer 或网络回调直接写状态。 + +## 5. 当前装配关系 + +```text +app_main + └── CompositionRoot + ├── Application + │ └── AppEventQueue + ├── EffectRouter + │ ├── BorlaS3Platform + │ ├── EspAudioEngine + │ │ └── PlaybackPipeline ──> ES8311 / I2S + │ ├── ConnectivityManager + │ │ ├── ConnectivityPolicy / ReconnectBackoff + │ │ ├── NvsWifiCredentialStore + │ │ └── DualNetworkTransport + │ │ ├── EspWifiTransport + │ │ ├── DualNetworkPolicy + │ │ └── Ml307Transport ──> UART / PPP + │ ├── RealtimeProtocol + │ │ └── EspWebsocketTransport ──> TCP / TLS + │ ├── BleProvisioningService + │ │ └── BleProvisioningGattServer / EspWifiTransport + │ ├── FriendService ──> BleFriendExchange / NVS + │ └── OtaService ──> HTTPS / A-B partition / SHA256 + ├── ActivationReplayService / NvsMemoryCache + ├── RuntimeDiagnosticsService + ├── SensorService + │ ├── TouchChannel / CapacitiveTouchInput + │ ├── ImuProcessor / Bmi270Sensor + │ └── BatteryEstimator / BatteryMonitor + ├── ScheduleCoordinator + │ ├── ReminderService + │ └── AlarmService / AlarmStore + ├── IdleService / PowerService + └── ButtonInput ──publish──> Application +``` + +`main.cc` 不持有业务判断。GPIO12 回调也不执行对话、配网或关机动作,只将原始 +按键事件送入控制面;产品含义由 `ReduceState` 决定。 + +## 6. 后续门禁 + +不再新增迁移阶段。后续只按 +[真机验证清单](hardware-validation-checklist.md) 逐项联调和修复: + +1. 板级、音频、WiFi 和基础 Realtime。 +2. Voice Frontend、BLE 配网、传感器、日程与低功耗。 +3. ML307/PPP、双网切换、通话与好友双设备。 +4. 激活码、记忆迁移、OTA A/B 回滚。 +5. 24h/72h 稳定性、heap/任务栈门禁和正式切换评审。 diff --git a/docs/audio-data-plane.md b/docs/audio-data-plane.md new file mode 100644 index 0000000..0b6f077 --- /dev/null +++ b/docs/audio-data-plane.md @@ -0,0 +1,102 @@ +# Firmware 2 音频数据面 + +> 实现阶段:重构路线图阶段 5 +> 当前状态:基础 16kHz 上行/24kHz 下行多轮对话真机链路已打通;声学质量、打断、 +> TTS 首帧 pre-roll 已实现并通过自动验证,等待复刷听感;长稳仍待验收 + +## 1. 固定音频契约 + +| 方向 | PCM | 编码 | 帧长 | +|---|---|---|---| +| 上行 | 16kHz、16bit、单声道 | Opus | 60ms / 960 samples | +| 下行 | 24kHz、16bit、单声道 | Opus | 60ms / 1440 samples | + +硬件 codec 统一工作在 24kHz。麦克风帧由 `Pcm24kTo16kConverter` 转成协议要求的 +16kHz 后再编码;下行保持 24kHz,解码后直接进入唯一播放管线。 + +## 2. 数据流和所有权 + +```text +ES8311 ADC / I2S RX + → CapturePipeline + → 24k→16k + → VoiceFrontend + → OpusFrameEncoder + → RealtimeProtocol + → WebSocket v3 binary + +WebSocket v3 binary + → RealtimeProtocol + → 整包验证后逐帧投递 + → PlaybackPipeline + → OpusFrameDecoder + → ES8311 DAC / I2S TX +``` + +音频帧不进入 `AppEventQueue`。Application 只接收监听、TTS、播放排空和失败等 +生命周期事件。 + +## 3. WebSocket v3 二进制格式 + +实现严格遵循 `protocols/websocket_protocol.md`: + +```text +[type:1][flags:1][payload_length:2 big-endian][payload] +``` + +- `type=0`:Opus。 +- `flags=0`:单帧;`flags=1`:批量。 +- 批量 payload 重复 `[frame_length:2][frame]`,上行最多聚合 5 帧。 +- 上行单帧最大 512 bytes,下行单帧最大 1536 bytes。 +- 长度、flags、空帧、帧数和边界全部校验。 +- 批量包先完整校验再投递,坏尾包不会造成前半包被播放。 + +## 4. 背压和生命周期 + +- `CapturePipeline` 使用固定 60ms 缓冲区;任务为 Core 0、priority 5,32KB + 栈通过 ESP-IDF capabilities API 分配在 PSRAM。 +- `RealtimeProtocol` 只在 start-listening 与 stop-listening 之间接受上行帧。 +- start-listening effect 先于采集策略执行,避免首个 Opus 帧落在协议门外。 +- 批量缓冲在 stop-listening 前强制 flush。 +- 发送队列和播放帧池均为固定容量;满队列丢弃并计数,不阻塞 Application。 +- WebSocket 二进制流最多占 10 槽命令池中的 8 槽,保留 2 槽给控制消息;传感器 + 文本使用独立 latest-wins 双槽,不会以 10Hz 频率挤满音频/控制池。 +- transport 每轮最多发送 2 条队列命令后优先读取下行,并在成功读取后让出一个 + tick,避免 Application 长时间收不到 `tts_started` 生命周期事件。 +- 协议任务在 `tts:start` 后收到、但 Application 尚未执行 + `BeginRemotePlayback` 的最多 8 个下行 Opus 帧进入 PSRAM 固定 pre-roll;开始 + session 后按原顺序提交。pre-roll 不逐帧分配内存,session 切换、取消和停止会 + 清空旧数据,超过 8 帧才按有界策略拒绝。 +- 下行帧必须属于当前远程播放 session,过期 session 无法进入扬声器。 +- `CapturePipeline` 为原始 16k PCM 和 Voice Frontend 处理后 PCM 使用独立缓冲, + 避免 AEC 输入/输出别名;Opus 编码只读取处理后数据。 +- TTS 全双工期间,reference 按实际软件播放音量缩放后交给保温的高性能 AEC; + 固件把处理后的音频按单个 60ms Opus 帧发送,绕过普通监听的 5 帧聚合。 +- server VAD 命中后下发 `barge_in:candidate`。播放任务在当前帧边界暂停,保留已经 + 取出的帧、队列和 session;server 同时停止产生新下行帧。ASR/文本回声校验判为 + `rejected` 时原位续播,判为 `confirmed` 时才取消旧 session。 +- server 的 `tts:stop` 是 producer EOF,不是扬声器 drain。两阶段连接继续通过 + 独立 tail uplink gate 逐帧发送 AEC 后音频;设备真正 `PlaybackDrained` 并发送 + `listen:start` 后才切回普通监听和 5 帧批量。这样不会在最后一段 TTS 仍在播放时 + 丢掉孩子新问题的主体。 +- 自然插话不再由设备本地能量、相关性或固定 reference 延迟硬取消;“你好播乐” + 仍通过 WakeNet 走独立的本地硬打断路径。 + +## 5. 自动验证与待验 + +宿主机测试覆盖精确 24k→16k 转换、批量往返、单帧、长度不符、空帧、坏尾包、 +容量上限和坏批次零部分投递。ESP-IDF 5.4.3 完整构建通过。 + +2026-07-21 长日志覆盖设备累计运行到 45 分 53 秒,共看到 48 次 TTS 开始;无 +命令池耗尽、断线或重连风暴。旧镜像中 22 个 session 共 71 个下行 Opus 帧早于 +Application 的 `tts_started` effect 被拒绝,最多单 session 6 帧;这证明问题是 +控制面异步时序,而非网络随机丢包。8 帧 PSRAM pre-roll 与两阶段播放暂停已实现, +firmware2 host tests 17/17、server 打断相关定向回归 85/85 及 ESP-IDF 构建通过。 +本轮另修复了 producer stop 到物理 drain 间的采集空窗,以及无活动人声时尾音 +pre-roll 进入普通 ASR 导致“你觉得呢?”伪输入的问题。仍需复刷 +确认日志不再出现 `downlink Opus dropped`、首字完整,并验证 candidate/rejected +恢复、confirmed 新问题、网络抖动和长时间对话。 + +播放/采集任务栈预算集中在 `core/task_stack_budget.h`。音频任务只在启动时分配 +PSRAM 栈,停止时通过 `vTaskDeleteWithCaps` 成对释放;真机应以运行时栈高水位 +决定是否继续收紧预算。 diff --git a/docs/ble-provisioning.md b/docs/ble-provisioning.md new file mode 100644 index 0000000..8ab3c60 --- /dev/null +++ b/docs/ble-provisioning.md @@ -0,0 +1,68 @@ +# Firmware 2 BLE 配网 + +> 实现阶段:重构路线图阶段 7 +> 协议:`protocols/ble_provisioning.md` v1.0.0 +> 当前状态:代码、编解码测试和 ESP-IDF 构建完成,等待小程序/真机验收 + +## 1. 模块边界 + +```text +Application + └── EnterProvisioning effect + └── BleProvisioningService(唯一配网工作任务) + ├── EspWifiTransport(预扫描/候选连接) + ├── NvsWifiCredentialStore + ├── BleProvisioningGattServer(NimBLE/GATT) + └── BorlaS3Platform(显式 FF06 重启命令) +``` + +GATT callback 只校验短命令、组装分包并向静态工作队列投递请求。Wi‑Fi 扫描、 +连接、NVS 和 JSON 通知不在 NimBLE Host task 中执行。 + +## 2. GATT 契约 + +| 特征 | 属性 | 实现 | +|---|---|---| +| FF02 DeviceInfo | READ | mac/version/board | +| FF03 WifiScan | WRITE/NOTIFY | `0x01` 返回预扫描缓存 | +| FF04 WifiConfig | WRITE | 严格 seq/flag 分包和 JSON 凭据 | +| FF05 WifiResult | NOTIFY | success 或标准错误码 | +| FF06 Command | WRITE | `0x01` 显式重启 | +| FF07 SavedWifi | WRITE/NOTIFY | 列表和按 index 删除 | + +设备名为 `Borla-XXXX`,XXXX 是 MAC 后四位。最大 MTU 为 517,默认 MTU 23 时 +自动回退为 18-byte JSON chunk。 + +## 3. Wi‑Fi/BLE 共存顺序 + +1. Application 同步停止正常 ConnectivityManager。 +2. 配网服务临时接管同一个 Wi‑Fi transport。 +3. 在 NimBLE 启动前主动扫描、按 RSSI 排序并去重,最多缓存 20 项。 +4. 停止 Wi‑Fi,启动 BLE;FF03 只返回缓存,不在 BLE 连接期间重新扫描。 +5. 收到候选凭据后启动 Wi‑Fi,等待 DHCP 或断开,最长 10 秒。 +6. 仅 DHCP 成功后 `SaveAndPromote`;失败凭据不落盘。 +7. 先停止 Wi‑Fi,再通过 FF05 通知结果,给 BLE 独占射频时间。 + +## 4. 凭据与资源安全 + +- 密码不进入日志;FF07 只返回 index 和 SSID,绝不回传密码。 +- 已保存 SSID 发送空 password 时,设备仅在内部从 NVS 恢复密码。 +- JSON 长度/NUL/字段类型、SSID/password 上限、seq 和 flag 全部校验。 +- worker、队列、事件组和 NimBLE Host task 均为静态存储。 +- 只允许一个 BLE 连接、两个 controller activity。 + +## 5. 自动验证与待验 + +宿主机测试覆盖分包顺序、越序拒绝、默认 MTU round-trip、凭据解析、所有 JSON +契约,以及 SavedWifi 不泄露密码。ESP-IDF 5.4.3 全量构建通过: + +```text +Binary size: 0x20e820 +App partition: 0x400000 +Free: 0x1f17e0(约 49%) +``` + +真机仍需验证手机发现/FF01 过滤、FF02、MTU 517 与 23、预扫描、正确/错误密码、 +SSID 不存在、DHCP 超时、NVS 优先级、FF07、FF06、BLE 断线重连,以及反复配网时 +的 BLE/Wi‑Fi 共存、内部 SRAM、Host task 栈和稳定性。 + diff --git a/docs/calls-and-friends.md b/docs/calls-and-friends.md new file mode 100644 index 0000000..e977570 --- /dev/null +++ b/docs/calls-and-friends.md @@ -0,0 +1,99 @@ +# Firmware 2 通话与好友碰一碰 + +> 实现阶段:重构路线图阶段 12 +> 当前状态:代码、host 测试和 ESP-IDF 构建完成,等待双设备真机验收 + +## 1. 通话状态与信令 + +`ServerMessageDispatcher` 把 `call` JSON 转成强类型命令,Realtime 只接受当前 +`call_id` 的后续状态: + +| server state | 控制面事件 | 设备行为 | +|---|---|---| +| `ring` | `OutgoingCall` | 主叫等待、播放等待音 | +| `invite` | `IncomingCall` | 来电响铃、单击可接听 | +| `connected` | `CallConnected` | 建立专用 call playback session | +| `ended` / `missed` | `CallEnded` | 取消音频、恢复待机策略 | + +设备单击来电时上发 `accept`;Calling/Active 单击上发 `hangup`。通话消息格式以 +仓库根目录的 `protocols/websocket_protocol.md` 为准。 + +通话与 Conversation 通过 `RuntimeState` 不变量互斥。进入通话会取消当前 TTS +和普通本地播放;通话 session 使用 `PlaybackPriority::kCall`,优先级高于闹钟。 +`connected` 后启用 `kCallDuplex`,Realtime 允许麦克风 Opus 上行,并把对端 +二进制 Opus 送入同一个 call session。挂断、断网、协议关闭都会关闭上行 gate、 +清空批次并取消旧 session。 + +专用通话提示音资源尚未提供时,catalog 使用已有提示音做明确的兼容回退;替换 +同名资源不改变状态和协议代码。 + +## 2. 好友模式 + +GPIO12 三击进入独占好友模式: + +1. 停止 listen/abort,取消播放,关闭音频策略。 +2. 关闭 Realtime,避免 BLE 启停与 socket/音频竞争。 +3. 启动 NimBLE observer + advertiser。 +4. 每 2 秒轮换扫描和广播,总时限 30 秒。 +5. 匹配成功后保留 4 秒 grace 广播,让另一台设备也能观察到本机。 +6. NimBLE 完全停止后发布 `FriendModeEnded`。 +7. 根据当前网络重新打开 Realtime,或重新启动 Connectivity。 + +好友广播名为 `BorlaF-XXXX`。候选最多 8 个,选择规则: + +- RSSI ≥ -60 dBm:一次观察即可。 +- -85 dBm ≤ RSSI < -60 dBm:至少观察两次。 +- 超过 6 秒未再观察的候选失效。 +- 选择满足条件且 RSSI 最强的候选。 + +BLE 地址归一为设备 base MAC 后存储,避免 controller 派生地址与业务设备 ID +不一致。 + +## 3. 离线优先存储 + +NVS namespace `friend_v2` 保存: + +- 设备昵称。 +- 最多 20 个好友。 +- 最近一个尚未成功上报的 `friend_add`。 +- magic、版本和 FNV 校验。 + +BLE 成功后先更新 NVS,再尝试上报。Realtime 离线时 pending 记录保留;下一次 +`RealtimeConnected` 自动补传,成功后清除 pending。重复 MAC 更新原记录, +不会重复占用列表。 + +首次启动新版存储时,如果 `friend_v2` 尚无有效快照,会只读旧 namespace +`device` 的 `name` 与 `friends` 的 `count`/`f_N` JSON,并保存成校验过的 +`friend_v2` 快照。已有新版快照但缺昵称时只补旧昵称。迁移不删除旧 key,确保 +回滚旧固件仍可读取原数据。好友快照约 1.8KB,加载、迁移和保存使用 PSRAM 工作 +对象,禁止把完整快照放入 service 小栈。 + +## 4. 资源与互斥 + +- BLE worker task:2048 bytes。 +- NimBLE host task:4096 bytes。 +- 好友 service task:4096 bytes,内部 RAM,集中预算并由 host 门禁约束。 +- NimBLE 同步超时:5 秒。 +- 好友工作流通过固定队列通信,GAP callback 不写 RuntimeState。 +- 再次三击只请求停止;必须等 BLE stop callback 后才恢复 Realtime,消除 + controller shutdown 与重连竞争。 +- 来电、闹钟、配网、OTA 和好友模式均由状态机决定互斥关系。 + +## 5. 自动验证与真机待验证 + +自动验证已覆盖通话 JSON、call 状态转换、接听/挂断 Effect、普通对话互斥、 +候选筛选、陈旧候选、MAC 归一、好友新增/更新/容量和消息构造。 + +2026-07-21 栈尾 watchpoint 在真机准确捕获旧 2KB `friend_service2` 栈于 +`NvsFriendStore::Save` 越界。快照迁入 PSRAM并提升为 4KB 栈后,设备完成超过 +110 秒多轮对话,不再发生 watchpoint 或随机调度器 panic;旧数据迁移本身仍需 +构造旧 NVS 做专项验收。 + +真机仍需: + +- 两台设备主叫、被叫、接听、挂断、未接和重复邀请。 +- 双向 16kHz 上行/24kHz 下行的实际通话音质、AEC 和回声。 +- 通话中 WiFi/4G 丢线及恢复。 +- 两台设备同时三击的发现成功率、距离/RSSI 边界和 30 秒超时。 +- Friend mode 退出后的 BLE 内存完全释放以及 WiFi/音频恢复。 +- 离线配对、重启、联网后的 `friend_add` 补传。 diff --git a/docs/connectivity-system.md b/docs/connectivity-system.md new file mode 100644 index 0000000..3e3ef4c --- /dev/null +++ b/docs/connectivity-system.md @@ -0,0 +1,146 @@ +# Firmware 2 连接管理与 WiFi 基础 + +> 实现阶段:重构路线图阶段 3 +> 当前状态:当前 NVS 凭据、STA/DHCP 与基础稳定运行已通过;断网恢复、旧格式 +> 凭据和多 AP 仍待真机验收 + +## 1. 设计目标 + +WiFi 连接层只负责“如何连接和恢复 WiFi”,不负责实时协议、提示音、4G 策略、 +重启或产品状态切换。业务状态仍由 `Application` 单写者事件循环维护。 + +阶段 11 已在本层外增加 `DualNetworkTransport`,将 `EspWifiTransport` 与 +`Ml307Transport` 组合成统一上游接口;WiFi adapter 本身仍保持单一职责。双网 +设计见 [dual-network.md](dual-network.md)。 + +## 2. 模块边界 + +```text +Application + │ AppEffect::kStartConnectivity / kStopConnectivity + ▼ +ConnectivityManager + ├── ConnectivityPolicy 纯 C++ 连接/恢复状态机 + ├── ReconnectBackoff 指数退避和抖动 + ├── NvsWifiCredentialStore 已保存网络 + └── DualNetworkTransport + ├── EspWifiTransport ESP-NETIF / ESP WiFi driver + └── Ml307Transport UART / LTE / PPP + │ + └── driver callback ──> manager internal queue + +ConnectivityManager + └── AppEvent::kNetworkConnected + AppEvent::kNetworkDisconnected + AppEvent::kProvisioningRequested + │ + ▼ + Application +``` + +ESP WiFi 回调不调用 `ReduceState`,也不直接执行重连。回调只把固定大小的内部 +事件写入 `ConnectivityManager` 静态队列。连接、定时器和应用事件发布都由唯一 +manager 任务串行执行。 + +## 3. 连接流程 + +1. `Start()` 向 manager 队列投递启动请求,调用方不等待网络。 +2. manager 从 NVS 加载最多 10 组凭据。 +3. 无凭据时发布 `ProvisioningRequested`,由控制面进入配网生命周期。 +4. 有凭据时启动双网 wrapper,默认 bearer 为 `EspWifiTransport`。 +5. 收到 `WIFI_EVENT_STA_START` 后连接优先级最高的已保存网络。 +6. 只有收到 `IP_EVENT_STA_GOT_IP` 才发布 `NetworkConnected`。 +7. 在线连接断开时只发布一次 `NetworkDisconnected`,随后在 manager 内部恢复。 +8. 每次失败轮换到下一组凭据,并按指数退避等待。 +9. DHCP 恢复后取消未触发的重试定时器并重新发布 `NetworkConnected`。 + +重复 `Start`、重复 `GotIp`、等待退避期间的重复 `Disconnected` 和停止后的迟到 +回调均为幂等操作,不产生重复应用事件。 + +## 4. 重试策略 + +参数集中在 `platform/borla_s3/board_config.h`: + +| 参数 | 当前值 | +|---|---:| +| 初始延迟 | 1000 ms | +| 最大延迟 | 60000 ms | +| 倍数 | 2 | +| 随机抖动 | ±20% | + +基础延迟序列为 1、2、4、8、16、32、60、60… 秒,每次再施加抖动。DHCP 成功 +后重试次数和延迟归零。该策略避免无 AP、密码错误或路由器重启时产生高频连接风暴。 + +## 5. 凭据存储 + +`NvsWifiCredentialStore` 使用原固件已经使用的 `wifi` namespace 和以下键: + +```text +ssid / password +ssid1 / password1 +... +ssid9 / password9 +``` + +因此从旧固件升级到 `firmware2` 时可以继续读取已有凭据。新保存或更新的网络会 +提升到第一优先级,最多保存 10 组。SSID 最长 32 字节,密码最长 64 字节。 + +日志只允许输出 SSID、索引和错误码,任何路径都不输出密码。 + +## 6. 诊断 + +`IConnectivityManager::GetDiagnostics()` 返回固定大小快照: + +- 当前连接阶段 +- 在线状态 +- SSID 和 IPv4 +- RSSI 和信道 +- 当前凭据索引和凭据总数 +- 当前退避次数 +- 最近一次 WiFi disconnect reason + +诊断快照不暴露密码。RSSI 当前在 DHCP 成功时采样;后续设备状态上报可读取该快照, +无需直接依赖 ESP WiFi driver。 + +## 7. 资源和并发 + +| 资源 | 配置 | +|---|---| +| manager 任务 | 动态任务,优先级 4 | +| manager 栈 | 8192 bytes,内部 RAM | +| 双网任务栈 | 8192 bytes,内部 RAM | +| 内部事件队列 | 静态队列,24 项 | +| 重试定时器 | 单次 `esp_timer` | +| 凭据缓存 | 固定 10 项 | + +两个任务只在系统初始化时创建,稳态连接和回调路径不创建任务、不创建队列, +也不按事件分配堆内存。网络栈保持在内部 RAM,确保 ESP-NETIF/WiFi 驱动启动及 +flash cache 暂停期间可访问;其预算与音频栈统一定义在 +`core/task_stack_budget.h`。 + +## 8. 已验证与待验证 + +自动验证已经覆盖: + +- 无凭据请求配网 +- 启动和成功事件幂等 +- 驱动启动失败退避 +- DHCP 成功 +- 在线掉线只通知一次 +- 等待期间抑制重复掉线 +- 多凭据轮换 +- 退避上限和成功后复位 +- Stop 后忽略迟到事件 +- ESP-IDF 5.4.3 完整编译 + +2026-07-21 真机已从当前 NVS 读取凭据、完成 STA/DHCP,并在 TLS 与多轮对话期间 +保持在线超过 110 秒;未出现由 WebSocket 发送池背压导致的重连风暴。 + +真机仍需验证: + +- 读取旧固件保存的真实 NVS 凭据 +- 错误密码、AP 不存在及弱信号行为 +- 路由器断电后无重连风暴 +- 路由器恢复后自动回到 Online +- 多个已保存 AP 的轮换 +- 长时间运行的任务栈、堆和 watchdog diff --git a/docs/dual-network.md b/docs/dual-network.md new file mode 100644 index 0000000..e65966b --- /dev/null +++ b/docs/dual-network.md @@ -0,0 +1,103 @@ +# Firmware 2 WiFi/4G 双网络 + +> 实现阶段:重构路线图阶段 11 +> 当前状态:代码、host 测试和 ESP-IDF 构建完成,等待 ML307/SIM 真机验收 + +## 1. 目标与边界 + +双网络实现分成三层,避免把产品决策塞进 UART 或 WiFi driver: + +```text +ConnectivityManager + │ IWifiTransport(统一上游边界) + ▼ +DualNetworkTransport ────────> DualNetworkPolicy(纯 C++) + ├── EspWifiTransport + └── Ml307Transport ──> UART1 / AT / LTE / PPP / ESP-NETIF +``` + +- `Ml307Transport` 只负责模组探测、注册、拨号和 PPP。 +- `DualNetworkPolicy` 只决定启动/停止哪个 bearer,以及何时通知上层。 +- `DualNetworkTransport` 串行执行策略动作并把 WiFi/4G 统一成原有 + `IWifiTransport` 事件。 +- `ConnectivityManager` 继续负责凭据、退避、Application 事件和提示音请求。 +- transport 不写 NVS、不播放提示音、不重启设备。 + +## 2. 自动与手动切换 + +默认启动 WiFi。以下任一条件触发自动转 4G: + +- WiFi 持续离线达到 30 秒,并且 ML307 存在。 +- WiFi RSSI 每 5 秒采样一次,连续 6 次低于 -80 dBm,并且 ML307 存在。 + +4G 掉线时自动停止 PPP 并回到 WiFi。GPIO12 四击发出手动切网请求: + +- 当前为 WiFi 且模组存在:切到 4G,并请求上层播放 `net4g_on`。 +- 当前为 WiFi 且模组不存在:保持 WiFi,并请求播放 `net4g_no_wifi`。 +- 当前为 4G:切回 WiFi,并请求播放 `net4g_off`。 + +切换时先向上层发布断网,再停止旧 bearer、启动新 bearer,并让 +Connectivity/Realtime 重新建立连接,避免沿用旧 socket。 + +## 3. ML307 生命周期 + +当前硬件配置: + +| 项目 | 配置 | +|---|---| +| UART | UART1 | +| MCU TX / RX | GPIO43 / GPIO44 | +| 波特率 | 115200 | +| APN | `CONFIG_BORLA_ML307_APN` | +| PPP 拨号命令 | `CONFIG_BORLA_ML307_DIAL_COMMAND`,默认 `ATD*99#` | +| 工作任务 | 静态任务 `ml307_ppp2`,stack 4096 bytes | + +启动顺序: + +1. 安装 UART driver,发送 `AT` 探测模组。 +2. 发送 `ATE0`、`AT+CMEE=2`、`AT+CFUN=1`、`AT+CEREG=2`。 +3. 最多等待约 60 秒,轮询 SIM 和 LTE 注册状态。 +4. 配置 PDP context/APN,发送拨号命令等待 `CONNECT`。 +5. 创建 ESP-NETIF PPP 接口,将 UART 收发接到 lwIP。 +6. 只有收到 `IP_EVENT_PPP_GOT_IP` 才向上层报告在线。 +7. Stop、PPP lost 或失败都按序销毁 netif、事件 handler 和 UART。 + +音频仍通过 WebSocket/lwIP 发送,不在 Application 控制面中搬运。协议层按 +5 个 60ms Opus 帧组成一个上行批次,降低蜂窝链路发送调用频率。 + +## 4. 并发与恢复 + +- 双网事件使用 20 项静态队列,由唯一 `dual_network2` 任务处理。 +- 5 秒周期 monitor 只投递固定大小事件。 +- ML307 AT/PPP 在独立任务中阻塞读取,不占用 Application。 +- bearer 重复启动、停止和迟到回调均有幂等保护。 +- 只有 WiFi 离线、RSSI 达到弱网门限或用户手动切网时才探测模组;强 WiFi 稳态 + 不再每 30 秒安装/卸载 UART。自动探测间隔仍不短于 30 秒。 +- AT presence 探测使用 512-byte RX、无 TX 软件队列;进入 PPP 前才使用 + 4096-byte RX/2048-byte TX 配置,避免 WiFi/音频活跃时因内部 heap 最大连续块 + 不足导致 UART driver malloc error。 +- PPP IP lost 即使没有 event payload 也会被记录并进入回退。 + +## 5. 已验证 + +- WiFi 正常时保持 WiFi。 +- 持续断网和连续弱 RSSI 达到门限后切换。 +- 弱 RSSI 恢复会清零计数。 +- 模组缺失时自动策略不切换。 +- 模组缺失时手动请求只产生不可用提示。 +- 4G 失败回到 WiFi。 +- 重复启动/停止和手动来回切换。 +- ML307 AT 注册、CSQ 和运营商响应解析。 +- ESP-IDF 5.4.3 全量编译。 +- 强 WiFi 稳态超过原 36 秒故障点,不再周期安装 UART,也未出现 driver malloc + error;退化 WiFi 下的轻量探测和真实 PPP 仍归入 SIM 专项。 + +## 6. 真机待验证 + +- GPIO43/44 方向、电平、波特率和供电时序。 +- SIM PIN、LTE 注册、运营商 APN 和真实 PPP 获取地址。 +- 4G 下 DNS、TLS、WebSocket hello、上下行音频和批量帧。 +- 拔 AP 后 30 秒切 4G;恢复 WiFi 后手动切回。 +- -80 dBm 边界和连续采样行为。 +- 模组缺失、无 SIM、拒绝注册、拨号失败、PPP 丢线。 +- 切网过程无重连风暴、任务泄漏、heap 持续下降或 watchdog。 diff --git a/docs/firmware-parity-audit.md b/docs/firmware-parity-audit.md new file mode 100644 index 0000000..5b43fc7 --- /dev/null +++ b/docs/firmware-parity-audit.md @@ -0,0 +1,1070 @@ +# firmware → firmware2 逐功能点对比台账 + +按功能域逐块通读旧固件 `borla/firmware`,与 `firmware2` 对照,记录**缺失 / 未完善 / 错误**的实现。 + +原则:不照搬。每条先判断旧代码本身有没有问题——没问题则集成,有问题则改进后集成。旧固件与 +server 均不修改。 + +状态含义: +- `已修复` — 已改入 firmware2 并通过编译 + host 测试 +- `新方案更好` — firmware2 现有实现优于旧固件,不移植,记录结论避免日后重复评估 +- `待实测` — 需要设备日志才能定夺,不做猜测性改动 + +--- + +## A. 音频服务任务 / 缓冲 / 时序 + +对照 `firmware/main/audio/audio_service.{h,cc}` (1428 行) ↔ `firmware2` 的 +`capture_pipeline` / `playback_pipeline` / `playback_controller` / `esp_audio_engine`。 + +### A-1 播放完成判定的竞态 — 新方案更好 + +旧固件靠补丁式的 `playback_pending_start_` 标志:`BeginNewPlayback()` 置位,第一帧进解码队列时 +清除,`WaitForPlaybackComplete()` 在置位期间不把"队列空"当成"播完"。加这个标志的原因写在注释里 +——现场 2026-07-14,`idle_check` 提前 5 秒报完成,麦克风在喇叭还在说"你还在吗小朋友"时就打开, +回声被当成用户语音送进了 ASR。 + +firmware2 的 `PlaybackController` 把同一件事编码进了会话状态机:`kPending` 状态 + +`producer_started` / `input_ended` 字段 + `producer_start_timeout`。`Active()` 返回的是会话是否 +持有喇叭,与队列空满无关。竞态在结构上不成立。 + +**结论:不移植。** 旧固件的标志是新方案状态机的一个退化子集。 + +### A-2 双工上行在参考环为空时整帧丢弃 — 已修复(严重) + +`voice_frontend.cc` 原本在 `!has_reference` 时置 `uplink_suppressed`,`Process()` 返回 false, +`CapturePipeline` 直接跳过编码与上行。 + +问题在于**参考环为空压倒性地意味着"没有在播放",而不是"漏了一帧参考"**: + +- `kCallDuplex` 通话中对端静默时根本不产生播放帧,参考环恒空 → 每一帧麦克风数据都被丢弃 → + 上行全程哑掉 +- `kWakeWordDuplex` 同理 +- `kBargeInDuplex` 在 TTS 结束到策略切回之间同样命中 + +这就是现场反馈的"声音录不进去了,说话没反应",以及 ASR 收到的内容断续错乱。 + +修复:改用 firmware2 自己已有的权威判据 `speaker_active`(由播放任务每帧回调打的时间戳, +120 ms 窗口),条件收紧为 `!has_reference && speaker_active`。喇叭没响就不可能有回声,那些帧 +必须上行——那段安静正是孩子在说话。 + +旧固件在这里的做法是完全不做参考门控,改用 **AEC 后 RMS ≥ 800** 的能量门控 +(`audio_service.cc:805-821`)。见 A-5。 + +### A-3 AEC 分块循环没有让出点 — 已修复 + +旧固件 `voice_processor.cc:191` 在每个 AEC 分块后 `vTaskDelay(1)`,注释写明是防 Task Watchdog。 + +firmware2 的 `VoiceDsp::ProcessAec` 循环每 60 ms 帧跑 3-4 次 `aec_process()`,全程不阻塞,跑在 +优先级 8 的采集任务上 → 该核 idle 任务在双工期间拿不到任何运行时间 → 看门狗触发。 + +`taskYIELD()` 在这里无效:idle 任务优先级为 0,只有阻塞式延时才能让它运行。已按旧固件同位置加 +`vTaskDelay(1)`。1000 Hz 下一个 tick = 1 ms,每帧代价约 4 ms。 + +### A-4 esp-sr 状态被分配到 PSRAM — 已修复(待实测确认收益) + +两边 esp-sr 版本相同(2.4.6),AEC 配置也相同(VOIP_HIGH_PERF / filter 4 / 16 kHz)。差异在 +**malloc 路由**: + +| | 旧固件 | firmware2(修复前) | +|---|---|---| +| `CONFIG_SPIRAM_USE_MALLOC` | 未设置 | `=y` | +| `SPIRAM_MALLOC_ALWAYSINTERNAL` | — | 16384 | +| esp-sr AEC/NS 状态落点 | 内部 SRAM | PSRAM(>16 KB 的分配全部外置) | + +NS 状态已被证实在 PSRAM(开机日志 `WebRtcNs_Create: self=0x3c285b14`,`0x3C..` 段为 PSRAM), +大小 23632 字节。自适应回声消除器每个分块都要读写整个滤波器状态,跑在八线 PSRAM 总线上而不是内部 +SRAM,是"同样的 AEC 配置旧固件塞得进 60 ms、firmware2 要 68 ms"的首要嫌疑。 + +修复:`ScopedInternalAllocationPreference` 在 `aec_create` / `ns_pro_create` 前后临时把 +`heap_caps_malloc_extmem_enable()` 阈值抬高,让 esp-sr 优先拿内部 RAM,之后恢复工程默认值。 + +**失败安全**:`heap_caps_malloc_default()` 在内部 RAM 不足时会自动回退到任意堆 +(`heap_caps.c:122` "try again while being less picky"),所以抬高阈值不可能让创建失败,最坏也只是 +回到今天的落点。 + +创建时会打印 `AEC state allocated internal=X psram=Y` 与 `NS state internal=X bytes`,用实测数字 +确认理论是否成立。前置依赖:`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP=y`(已于 e43f0098 补上)必须 +真的把内部堆余量从 1511 字节拉回几十 KB,否则内部 RAM 装不下这几十 KB 状态。 + +### A-5 双工上行缺少 AEC 后能量门控 — 待评估 + +旧固件 barge-in 上行前有一道 RMS ≥ 800 的门控。在 ERL 13 dB 下,TTS 麦克风 RMS 3000 的残留约 +670,正好被滤掉——这道门控实际在兼任残留回声抑制。 + +firmware2 没有这道门控。是否补:取决于 A-4 修复后实测的 ERL。ERL 回到 20 dB 以上则不需要;仍在 +4-14 dB 则需要,但不应照搬固定阈值(对音量和 AGC 增益敏感,且会削掉语音起音的头一两帧),应改为 +相对参考帧能量的自适应门限。 + +--- + +## B. 语音前端 AEC / VAD / 唤醒词 + +对照 `firmware/main/audio/voice_processor.{h,cc}`、`wake_word.{h,cc}` ↔ `firmware2` 的 +`voice_frontend` / `voice_dsp` / `voice_activity_detector` / `wake_word_detector`。 + +### B-1 DSP 参数对齐情况 — 已核对,基本一致 + +| 参数 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| AEC 引擎 | `VOIP_HIGH_PERF` | 同 | 一致 | +| AEC filter_length | 4 | 4 | 一致 | +| barge-in 时 NS | 关闭(注释:NS FFT 在 S3 上有看门狗压力) | 关闭 | 一致 | +| AGC 目标峰值 | 0.42 | 0.42 | 一致 | +| AGC 最小增益 | 0.8 | 0.8 | 一致 | +| AGC 最大增益(通话) | 6.0 | 4.0 | firmware2 更保守,可接受 | +| AGC 最大增益(barge-in) | 1.8 | 1.8 | 一致 | +| 噪声门衰减(通话) | 0.20 | 0.1 | firmware2 更激进,可接受 | +| 噪声门衰减(barge-in) | 0.05 | 0.05 | 一致 | + +### B-2 TTS 播放期间是否运行 WakeNet — 待实测 + +**旧固件 Speaking 状态明确关闭 WakeNet**(`application.cc:2352-2356`): + +```cpp +audio_service_.EnableWakeWordDetection(false); // 防止唤醒词打断播放 +audio_service_.EnableVoiceProcessing(true); +audio_service_.EnableBargeInMode(true); +audio_service_.EnableEnergyVad(true); // 启用能量 VAD 用于打断播放 +``` + +即旧固件双工期间的 CPU 开销**只有 AEC**——没有 NS,没有 WakeNet。 + +firmware2 的 `WakeRequired()` 对 `kBargeInDuplex` 返回 true,barge-in 期间 AEC + WakeNet 全跑。 + +需要澄清的一点:现场反馈"以前'你好播乐'能打断 TTS",但旧固件此时 WakeNet 是关的——实际机制是 +**能量 VAD**(RMS ≥ 2500 连续 3 帧 → `on_voice_detected` → 中止播放)。说任何话都能打断,用户 +感受上等同于唤醒词生效。 + +是否关闭 firmware2 双工期间的 WakeNet,取决于 A-4 修复后 AEC 与 WakeNet 的实测耗时占比。若 AEC +才是大头,关掉 WakeNet 就是白丢功能。**不在拿到实测数字前动。** + +### B-3 缺少本地能量 VAD 打断路径 — 待补 + +firmware2 的 `kBargeInCandidate` / `kBargeInRejected` / `kBargeInConfirmed` 三个事件目前**只有 +服务端一个来源**(`realtime_protocol.cc:938-953`)。本地没有任何快速打断路径。 + +叠加 A-2 的上行丢帧缺陷后,服务端根本收不到语音 → 自然打断完全失效,这与现场反馈一致。 + +补法:在 `VoiceFrontend` 的 AEC 分支对 AEC 输出做能量检测,发 `kBargeInCandidate`。reducer 不用 +改一行——两阶段设计里 candidate 只是可逆暂停,服务端随后 confirm 或 reject 仲裁,比旧固件的 +"能量 VAD 直接中止"更稳健。 + +先观察 A-2 修复后服务端路径是否已经够用,避免引入过早暂停的体感问题。 + +--- + +## C. 编解码器 / 音量 / I2S + +对照 `firmware/main/audio/audio_codec.{h,cc}`、`codecs/es8311_audio_codec.{h,cc}` ↔ +`firmware2/main/platform/borla_s3/es8311_audio_output.cc`。 + +### C-0 已核对一致的项 + +| 项 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| 硬件 DAC 音量 | 恒定 `set_out_vol(100)` | 同 | 一致 | +| 软件音量曲线 | `gain = vol/100`,定点 ×256 >>8,钳制 int16 | 同 | 一致 | +| 输入增益 | `set_in_gain(30)` | `set_in_gain(30.0f)` | 一致 | +| 音量上下限 | 0 – 100 | 0 – 100 | 一致 | +| 音量 NVS | namespace `audio` / key `output_volume` | 同 | 一致 | +| I2S 声道 | 单声道 / LEFT slot / 16 bit | 同 | 一致 | + +硬件 DAC 恒定 100%、音量只做软件缩放,这一点旧固件有注释说明理由:若把 NVS 音量写进硬件 DAC, +之后设成 100 会同时顶到软件增益上限和硬件天花板,听感与 70 无异。firmware2 保持了同样做法。 + +采样率差异是 firmware2 的有意选择,不改:旧固件硬件收发都是 16k,下行 24k 要降采样到 16k 播放; +firmware2 硬件跑 24k,下行原生播放不损失,上行再降到 16k 送协议。 + +### C-1 I2S DMA 时间深度被砍掉三分之一 — 待实测后修(与参考帧提前量耦合) + +DMA 参数数值两边相同(`dma_desc_num=6`、`dma_frame_num=240`),但**采样率改了、时间深度没跟着换算**: + +| | 采样率 | DMA 深度 | 采集循环耗时 | +|---|---|---|---| +| 旧固件 | 16 kHz | 6×240/16000 = **90 ms** | 远小于 90 ms | +| firmware2 | 24 kHz | 6×240/24000 = **60 ms** | 双工 68 ms | + +这是重写时照抄原始数字、未按采样率换算的转写错误:缓冲被砍掉三分之一,而处理反而更重,双工下每帧 +必然溢出 → 丢麦克风帧 → AEC 的 mic/reference 锁步漂移。 + +**不在本轮改。** IDF 的 `i2s_new_channel()` 对 TX/RX 共用一份 `chan_cfg`,加深 RX 必然同时加深 TX, +而 TX 深度直接决定"参考帧入队"到"声音离开喇叭"的提前量,会让 `kReferenceMaxLeadFrames` 需要重新 +整定。在 A-4 实测结果出来前改动对齐,会把两个变量混在一起。若 A-4 修复后循环耗时回到 60 ms 以内, +这一项可能自然不再是瓶颈。 + +### C-2 PA 常开 — 记录,暂不改 + +- 旧固件:`gpio_set_level(pa_pin_, output_enabled_ ? 1 : 0)`,PA 随输出使能开关 +- firmware2:Initialize 置 1、Shutdown 置 0,**运行期间常开** + +影响:功放静态电流常在(电池设备);放大器底噪持续进入麦克风,抬高本底、削弱唤醒词信噪比与能量 +VAD 的判别余量。 + +反面代价:按输出使能切换 PA 会产生开关爆音,且有建立时间,可能削掉提示音开头。旧固件承担了这个 +代价。属功耗/噪声优化而非功能缺陷,等主线问题收敛后再评估。 + +--- + +## D. 协议 / WebSocket + +对照 `firmware/main/protocols/{protocol,websocket_protocol,utf8_util}.*` ↔ +`firmware2/main/protocol/*`。 + +### D-0 消息类型覆盖 — 完整 + +旧固件处理的 30 种消息 type(`alarm_config` `barge_in` `call` `cancel_timer` `connected` +`control` `delete_alarm` `ended` `hello` `invite` `light_sleep` `llm` `memory_sync` `missed` +`play_local` `play_local_sequence` `pong` `recent` `ring` `sentence_start` `set_alarm` `set_timer` +`start` `stop` `stt` `sync_alarms` `tts` `volume` `wake_word` `wifi_config`)在 firmware2 的 +`server_message_dispatcher` 中**全部覆盖**,且 firmware2 是超集。 + +### D-1 abort 消息缺少 playback_text — 已修复 + +旧固件 `SendAbortSpeaking` 会带上当前正在播放的 TTS 文本(前 100 字节),作用是让服务端知道孩子 +打断时已经听到了多少,下一轮从那里接续而不是从完整回复接续。firmware2 的 abort 只有 +`session_id` / `type` / `reason`,这段上下文丢失了。 + +已补:`RealtimeProtocol` 在 `tts sentence_start` 时留存该句,abort 时随消息发出,并在 TTS 正常结束 / +barge-in 确认 / 来电抢占 / 连接关闭四处清空,避免把已结束的句子当成"仍在播放"上报。 + +### D-2 UTF-8 边界安全截断 — 已补齐 + +旧固件 `utf8_util.h` 的注释记录了现场根因(2026-06-25):`substr(0, 100)` 按字节切断,跨第 100 +字节的中文字符(3 字节)被劈成非法 UTF-8 序列,服务端 websockets 库校验文本帧失败后以 1007 +(invalid frame payload data) 强制断连,线上表现为"讲故事讲一半就停"。 + +算法本身正确(从字节上限向左走到非续字节),已按 firmware2 协议层的定长缓冲风格重写为 +`protocol/utf8_text.h`。 + +旧固件的手写 `EscapeJsonString` **不移植**:firmware2 全部用 cJSON 构造消息,转义由 cJSON 负责, +而且 cJSON 的实现更完整。cJSON 不校验编码,所以边界截断这一半仍然必须自己做。 + +host 测试已覆盖:无文本时字段缺省、正常中文原样带上、超长句截断后字节数为 3 的整数倍(即从未劈开 +字符)。 + +### D-3 其他已核对项 + +- 心跳/超时:旧固件 `IsTimeout()` 为 120 秒无入站;firmware2 `heartbeat_timeout_ms = 90000`。 + 更激进但合理,不改。 + +--- + +## F. OTA + +对照 `firmware/main/ota.{h,cc}` ↔ `firmware2/main/ota/*`。 + +### F-0 已核对一致或更好的项 + +| 项 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| 请求体 | mac_address / board_type / app_version / chip_model / free_heap | 同 + idf_version | firmware2 更全 | +| 固件包校验 | 无 sha256 字段 | 解析并校验 `firmware.sha256` | **firmware2 更好** | +| 陈旧端点自愈 | `IsKnownSavedEndpoint` | `IsRolloverEndpoint`(同逻辑,定长缓冲重写) | 一致 | +| `0.0.0.0` 主机替换 | 字符串 replace | `SubstituteWildcardHost`(带边界校验) | firmware2 更严谨 | +| auto_update / force_upgrade | 解析 | 解析 | 一致 | +| A/B 回滚确认 | `esp_ota_mark_app_valid_cancel_rollback` | 同 | 一致 | +| 升级前通知 | `ota_notify` 文本 + 等 4 秒 | `SendOtaNotify` + `AnnounceUpgrade` | 一致 | + +OTA 检查地址:旧固件存 NVS(`wifi/ota_url`)再靠 `IsKnownSavedEndpoint` 每次开机纠偏;firmware2 直接用 +编译期常量 `CONFIG_BORLA_OTA_URL`,**结构上不存在陈旧地址问题**,不移植 NVS 那套。 + +### F-1 缺少客户端时间戳请求头 — 已修复 + +服务端 `http_server.py:98` 读 `X-Borla-Client-Send-Ms` / `X-Borla-Client-Epoch-Ms`,用 +`trace.py:client_delta_ms` 算设备与服务端的时钟偏差。firmware2 的 OTA 请求只有 +Trace-Id / Session-Id / Request-Id 三个,两个时间戳缺失。已补。 + +wall clock 未同步(NTP 未落地,开机首次 OTA 检查就是这种情况)时**整个 epoch 头省略**而不是发 0: +1970 的时间戳会被服务端算成 56 年偏差,不如明确表示"未知"。 + +--- + +## 跨域:端到端链路追踪 + +这一组不属于单一功能域,是重写时整体遗漏的一套能力。服务端基础设施完整存在 +(`server/core/trace.py`、`websocket_server.py`、`http_server.py`、`connection.py`),设备端没接上。 + +### T-1 WebSocket 握手缺 trace 头 — 已修复(影响最大) + +`server/core/websocket_server.py:66-73` 从握手头读取: + +```python +trace_id = get_header(headers, "X-Borla-Trace-Id") or new_trace_id("ws") +session_id = get_header(headers, "X-Borla-Session-Id") or new_session_id() +client_send_ms = get_header(headers, "X-Borla-Client-Send-Ms") +client_epoch_ms = get_header(headers, "X-Borla-Client-Epoch-Ms") +``` + +firmware2 的握手只发 `Device-Id` / `Protocol-Version` / `Firmware-Version`,五个 trace 头一个没有。 +**后果是服务端每次都自己新生成 trace/session id,设备侧日志与服务端日志无法关联**——端到端追踪 +能力实际处于失效状态。旧固件 `websocket_protocol.cc:368-378` 五个头齐全。 + +已补全五个头(Trace-Id / Session-Id / Request-Id / Client-Send-Ms / Client-Epoch-Ms)。 + +### T-2 上行音频批次 trace 标记 — 已修复 + +旧固件在每个上行音频批次发出时按采样策略发一条 +`{"type":"trace","stage":"ws.audio_batch.send","seq","frames","bytes","client_send_ms","client_epoch_ms"}`。 +服务端 `connection.py:538-556` 有完整接收处理(`_update_trace_from_payload` + +`_trace_last_client_audio`)。firmware2 一处都没有。 + +采样策略照搬旧固件(首批 / 帧数变化 / 字节数变化≥160 且相对变化≥20% / 5 秒心跳)——每 300ms 一个 +批次,逐批发标记纯属噪音,这套策略是合理的,直接集成。 + +实现上有两点与旧固件不同:标记在音频**之后**发送,确保它永远不会延迟它所描述的那批音频;构造走 +cJSON 而不是 `snprintf` 拼字符串,省掉旧固件那句手写的防溢出检查。 + +### T-3 session id 从不由设备生成 — 已修复(T-1 的必要配套) + +补上 T-1 的握手头之后暴露出来的问题:firmware2 的 `g_session_id` **只由服务端 ServerHello 经 +`SetSession()` 写入**,设备自己从不生成,而 `TraceContext` 头文件里写着"session 为连接作用域·每次 +实时会话刷新"。旧固件有 `RefreshSession()`,firmware2 漏了。 + +两个后果: + +- 开机首连时 session id 是 `"-"`。发出去后服务端那句 + `get_header(headers, "X-Borla-Session-Id") or new_session_id()` —— Python 里 `"-"` 是真值, + 服务端会把字面量 `"-"` 当成 session id 采纳 +- 重连时发的是**上一条连接**的 id,两条无关会话被并到同一个 id 下 + +已补 `TraceContext::RefreshSession()`(前缀 `s-`,与旧固件一致),在每次连接尝试构造握手头时调用。 +设备提议、服务端 ServerHello 仍可覆盖,语义是"提议"而非"决定"。host 测试已覆盖。 + +--- + +## H. 设置 / 系统信息 / 缓存 / trace + +对照 `firmware/main/{settings,system_info,memory_cache,trace_ctx}.*` ↔ firmware2 对应实现。 + +| 项 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| NVS 封装 | `Settings` 类,析构时按 dirty 提交 | 各模块直接用 `nvs_*`,就近提交 | 等价,不改 | +| MAC 取值 | `esp_read_mac(ESP_MAC_BASE)` | `esp_read_mac(ESP_MAC_WIFI_STA)` | ESP32-S3 上两者相同(旧固件注释亦如此说明),无差异 | +| MAC 格式 | 小写带冒号 | 同(已于 e43f0098 修正) | 一致 | +| BLE MAC → BASE MAC | `BleMacToBaseMac`(BLE = BASE + 2) | `NormalizeBleMacToBaseMac` | 一致 | +| 芯片型号 / 版本 / 堆 | `SystemInfo::*` | `DeviceIdentity` + 诊断服务 | 一致 | +| 记忆缓存 | `Load/Save/UpdateFromServerSync` | `Load/CopySnapshot/Update` + `LoadLegacyPartitionLocked` | **firmware2 更好**(带旧分区格式迁移) | +| trace 作用域 | trace / session / request 三层 | 同 | 一致,`RefreshSession` 见 T-3 | + +--- + +## G. 板级 / 配网 / 按键 / LED + +| 项 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| 按键长按 / 短按阈值 | 2000 / 50 ms | 2000 / 50 ms | 一致 | +| 按键有效电平 | active_high | `active_level = 1` | 一致 | +| 多击识别归属 | 固件只报边沿,业务识别在 server(ADR-006) | 同 | 一致 | +| 触摸阈值系数 | `THRESHOLD_K=5.0` `MIN_TOUCH_DELTA=300` `MIN_NOISE_DEV=50` `OUTLIER_K=4.0` | 5.0 / 300 / 50 / 4.0 | 一致 | +| 触摸消抖 | 按下 4 采样 / 释放 1 采样 | 4 / 1 | 一致 | +| 基线跟随 | 漂移带门控(`DRIFT_K=3.0`) | 按下期间完全冻结 + 离群拒绝 | **firmware2 更严** | +| 释放短路 EMA | 有 | 有 | 一致 | + +### G-1 缺少关机 LED 图案 — 记录,未实现 + +旧固件 `LedState` 有 `kShuttingDown`,firmware2 的 `LedPattern` 没有(另有 `kStarting` / +`kFriendMode` 是新增的)。长按关机时 firmware2 在提示音播放期间保持原图案,`CompleteShutdownPrompt` +排空后才置 `kOff`,中间没有关机中的视觉反馈。 + +属视觉反馈层面,改动要动枚举 + ws2812 渲染 + effect_router 映射 + host 测试四处,收益与成本不成 +比例,先记录。 + +--- + +## I. BLE 好友交换 + +| 常量 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| 好友模式总超时 | 30 s | `kModeTimeoutMs = 30000` | 一致 | +| 广播 / 扫描各阶段时长 | 各 2000 ms | `kPhaseDurationMs = 2000` | 一致 | +| 配对宽限 | 4000 ms | `kGraceDurationMs = 4000` | 一致 | +| NimBLE sync 超时 | 5000 ms | `kNimbleSyncTimeoutMs = 5000` | 一致 | +| 强 / 弱 RSSI 门限 | −60 / −85 dBm | `kStrongRssiDbm` / `kWeakRssiDbm` 同值 | 一致 | + +### I-1 GAP 停止后立即释放 NimBLE — 已修复 + +`ble_gap_disc_cancel()` / `ble_gap_adv_stop()` 只是把停止命令排给控制器。firmware2 紧接着就 +`nimble_port_stop()` + `nimble_port_deinit()`,可能在控制器还在收尾广播/扫描上下文时就把 port 拆了, +BT 内存回收会延迟甚至不回收——而调用方随后立刻重新挂 WiFi,这两个栈的内部 RAM 加起来放不下。 + +已按旧固件同位置补 200 ms 间隔(旧固件注释:「GAP stop 稍等 200ms 后释放 BLE,再恢复 WS」)。 + +--- + +## E. 应用状态机 + +对照 `firmware/main/application.{h,cc}`(4024 行)↔ `firmware2` 的 `core/state_reducer` + +`app/application` + `adapters/effect_router` + `power/idle_service`。 + +以定时器与阈值常量作为行为规格的切面比对(逐行读 4000 行的收益低于按规格点核对)。 + +### E-0 已核对覆盖的项 + +| 项 | 旧固件 | firmware2 | 判定 | +|---|---|---|---| +| TTS 无 stop 看门狗 | `kTtsTimeoutMs = 60000`,每个 sentence_start 重置 | `kStalledTimeoutMs = 10000`(帧级停滞) | firmware2 更严更直接,覆盖同一失效模式 | +| TTS 流空闲超时 | `kTtsStreamIdleTimeoutMs = 10000` | 同上 | 一致 | +| 生产者启动超时 | `playback_pending_start_` 宽限 1500 ms | `kProducerStartTimeoutMs = 2000` | 等价 | +| 应答窗口 | 15 s | `response_window_ms = 15000` | 一致 | +| 闹钟上限 | 16 | 16 | 一致 | + +`kTtsTimeoutMs` 不是 TTS 绝对时长上限(每个 `sentence_start` 都重置),讲故事不受影响,不必移植。 + +### E-1 空闲策略时长差异显著 — 需产品确认,未擅改 + +| | 旧固件 | firmware2 | +|---|---|---| +| `idle_check`("你还在吗?小朋友") | T+**30 秒** | T+**3 分钟** | +| `idle_goodbye` / 进入休眠 | T+**60 秒** | T+**10 分钟** | +| 每次提示后的应答窗口 | 15 秒 | 15 秒 | + +旧固件在最后一次交互 30 秒后就问"你还在吗",firmware2 放宽到 3 分钟。这是**产品行为决策**而非缺陷, +两种都能自洽,改哪边都会被用户直接感知到。**保持 firmware2 现值,等确认。** + +### E-2 最短监听时长守卫未移植 — 已评估,判定为不移植 + +旧固件 `kMinListeningDurationMs = 5000`:`Listening → Speaking` 的切换若距监听开始不足 5 秒就延后, +注释写着「解决人声识别不完全就开始应答」——本质是给服务端 ASR 断句过早打的客户端补丁。 + +不移植的理由: + +- **固定 5 秒地板代价很大**。孩子答一个"好",回复要被硬压 5 秒才出来,每一轮短回答都卡顿 +- 它掩盖的是服务端断句问题,而当前约束是不改 server——但也不该在设备侧用一个会劣化正常路径的 + 补丁去盖 +- 旧固件为这套延迟切换的定时器机制打过至少两个后续补丁(2026-06-30 的定时器复用、以及防止 + TTS STOP 已取消定时器但 lambda 仍在队列里导致误切) +- firmware2 的设计是服务端持有回合边界权(`listen mode="auto"`) + +现场反馈过的"唤醒后极短时间必须提问",根因已定位为设备自身提示音触发了 VAD(A-2 / 自采集 +hangover 已修)。若该修复上机后症状仍在,再把这条守卫作为兜底重新评估。 + +--- + +## 待办 + +无剩余未覆盖功能域。待实测项见 A-5 / B-2 / B-3,待产品确认项见 E-1。 + +--- + +# 第二轮:firmware2 全量自检(不对照旧固件,查自身缺陷) + +通读范围:realtime_protocol / esp_websocket_transport / capture_pipeline / playback_pipeline / +local_prompt_player / voice_frontend / esp_audio_engine / state_reducer / runtime_state 验证器 / +application / app_event_queue / composition_root / effect_router / ble_friend_exchange / +friend_service / friend_types / ota_service 下载校验段 / server_message_dispatcher 解析入口 / +protocol_message_builder::Print。外设薄层(es8311 Read、ws2812、sensor_service、各定时器回调)抽查。 +纯逻辑模块依赖既有 19 项 host 测试。 + +## 修复的缺陷 + +### S-1 Opus 编码器跨任务 Reset 与 Encode 并发(严重) + +`CapturePipeline::ApplyPolicy`(application 任务)在离开采集策略时直接调 `encoder_.Reset()`, +而 `RunEncoder`(core 1 编码任务)可能正在 `encoder_.Encode()` 里。libopus 状态非重入,并发 +Reset 会把状态撕裂在半帧上——编出垃圾帧或崩溃。**每一轮对话结束都会离开采集策略**,竞态常年上膛。 + +修复:`encoder_reset_pending_` 原子标志,Reset 由编码任务自己在下一圈执行。 + +### S-2 Opus 解码器跨任务 Reset 与 Decode 并发(严重,与 S-1 成对) + +`PlaybackPipeline::Run()` 的 `decoder_.Decode()` 在 **mutex_ 之外**执行(有意为之,避免锁跨慢速 +解码),但 `Cancel()` 与 `StartSession()`(application 任务,锁内)直接调 `decoder_.Reset()`。 +每次打断 / 新会话抢占都在与解码撞状态。 + +修复:`decoder_reset_pending_` 原子标志,播放任务在下一次 Decode 前执行。`CheckTimeout` 与 +`Stop` 里的 Reset 保留——前者在播放任务自身,后者在任务已删除之后,均无并发。 + +### S-3 好友 MAC 大写送服务端(功能性) + +`NormalizeBleMacToBaseMac` 输出 `%02X` 大写。归一化结果是对端设备的 device_id,经 +`SendFriendAdd` 原样送服务端,服务端按大小写敏感匹配——与激活提示死循环(platform MAC 大写) +同一类契约违背,加好友必然失败。旧固件 `BleMacToBaseMac` 输出小写。 + +修复:输出改 `%02x`;`ble_friend_exchange` 的发现路径同步改小写(本地去重键,顺带统一); +host 测试断言改为小写输出、保留大写输入验证解析不区分大小写。 + +### S-4 WS 握手 trace id 首连为 "-"(T-1 的遗留) + +设备从不在连接前生成 trace id:开机首连时 `TraceId()` 仍是 `"-"`,服务端 +`get_header(...) or new_trace_id()` 对 `"-"` 判真原样采纳——与 T-3 的 session id 同病。 + +修复:`DoOpen()` 构造握手头前 `RefreshTrace("ws")`——每次连接尝试都是一次新交换,语义本就该刷新; +ServerHello 之后的再次刷新对应首个回合,两者各司其职。 + +### S-5 编码任务创建失败泄漏采集任务(边缘路径) + +`CapturePipeline::Start()` 里 encoder 任务创建失败直接返回,已创建的 capture 任务永远停在 +`vTaskSuspend`,16 KB 内部 RAM 栈滞留——恰好是整个工程在拼命保护的池子。补了与 `Stop()` 相同的 +收尾。 + +### S-6 死代码清理 + +`VoiceFrontend::ReferenceActive()` 已被播放时间戳方案取代且无调用者,连同头文件声明一并删除。 + +## 核对过、确认无问题的点(避免日后重查) + +- **realtime_protocol 全文**:`SendBuiltMessage` 先发送后拿锁(trace 标记在锁外调它是必须的); + 所有 `Publish` 都在锁外;`OnTimer` 在 esp_timer 任务里只投递(transport 全异步);TTS/通话 + 会话 id 分配的回绕处理;`SyncClock` 的 1970 下限与时区钳制 +- **esp_websocket_transport 全文**:Open/Send 全部经命令队列由专用任务执行,esp_timer 任务不会 + 被 TLS 连接卡住;帧重组对控制帧 payload 的消耗处理正确(否则会把控制字节拼进应用消息); + 收包走 `cJSON_ParseWithLength`,不依赖 NUL 终结 +- **audio_packet_ 共享缓冲**:批次消费在锁内原子完成,两个任务不可能同时持有待发内容 +- **state_reducer 全读**:长按关机无 lifecycle 守卫是"物理关机任何状态可用",升级中长按 OTA + 失败事件会被 kShuttingDown 正确忽略;kPlaybackDrained → Listening 的通用回归是 idle_check + 应答窗口的实现基础 +- **Print / dispatcher / NVS**:cJSON 全路径释放;nvs_open/close 配对完整 +- **全部 esp_timer 回调**(realtime/friend/dual_net/wifi_retry/ws2812/led_alert/activation): + 只投递或平凡工作,无阻塞 +- **无 strcpy/strcat/sprintf**;临界区内无日志/延时/IO(sensor_service:272 的日志在 + portEXIT 之后,grep 上下文误报) +- **Es8311 Shutdown 时序**:仅在 capture/playback 任务确认退出后调用,无悬空句柄窗口 +- **ble_friend_exchange**:`HandleStop` 跑在专用 worker 任务,其中的 200ms 控制器释放延时 + 不阻塞任何共享任务 + +--- + +# 第三轮:双工回声修复 + +现场日志(2026-07-29)钉死证据链:三句 ">>> 用户" 转写全部与同时段 TTS 原文逐句吻合 +("改成收听兔"→"改成偷听兔"、"你这是在跟人工服务说话呢"→"你是在跟李光头说话呢"), +是残留回声被 ASR 硬解,不是任何人说的话。ERL 只有 6-13dB 的三个实测原因: +`period_avg=77.8ms`(超预算 → RX DMA 溢出 → mic/ref 失步,`ref_drops` 17%)、 +`process=68ms`(AEC+WakeNet 同跑)、`encode=82ms`(playback 与 capture_enc2 挤 core 1, +三次看门狗回溯全部停在 silk_encode)。 + +方案约束:双工必须成立——TTS 播报时用户说话,设备要听清并回答新问题。因此上行全程 +不关、门控只允许"相对残留"不允许绝对能量阈值。完整方案见对话记录,分五步实施。 + +## 步骤 ①(本次):纯减负三件套 + +**R2 编码 complexity 4→3**:对齐旧固件(`audio_service.cc:14` "ESP32 上用最低复杂度保证 +实时性",组件默认甚至是 0)。complexity 4 实测独占核 33ms/帧、与播放争核时 82ms。 + +**R3 编码任务帧间让出**:单次 `opus_encode` 内部无法让出,积压时 `xQueueReceive` 立即返回, +循环独占 core 1 直到积压清空——看门狗的直接成因。每帧末尾 `vTaskDelay(1)`,代价 1ms/60ms。 + +**R1 kBargeInDuplex 不再喂 WakeNet**:AEC+WakeNet=68ms 永远塞不进 60ms。旧固件 Speaking +同款决策("防止唤醒词打断播放")。打断由上行+服务端仲裁承担,本地能量候选在步骤 ③ 补。 +kWakeWordDuplex 保留 WakeNet:该策略无上行,超支不会外泄回声,只损失本地唤醒精度。 + +验收指标(对照 2026-07-29 基线):process 68→<45ms、encode 82→<20ms、 +period_avg 77.8→≤62ms、看门狗零出现。达标后看 erl 是否 ≥18dB、ref_drops 是否 <2%。 + +## 步骤 ① 实测结果(2026-07-29 13:57 日志) + +| 指标 | 基线 | ① 后 | 判定 | +|---|---|---|---| +| 看门狗 | 3 次/40s | 0 | ✓ | +| period_avg | 77.8ms | 62-65ms | 大幅改善,未到 60 | +| process | 68ms | 54ms | R1 生效(-14ms=WakeNet) | +| encode(独占核) | 33ms | 22ms | ✓ R2 生效 | +| ref_drops | 17% | 3.4% | ✓ | +| ERL | 6-13dB | 起始 8-10 → 尾部 17-19.6dB | 收敛但每会话重爬 4-6s | + +三个结论: + +**AEC 单独 ~50ms 是天花板**:WakeNet 只占 14ms。且本次 esp-sr 状态已被搬进内部 RAM,AEC +依旧 50ms——**PSRAM 位置理论被实测证伪**(内外差 ≤4ms,噪声级)。 + +**prefer-internal 是一次回归(已回滚)**:状态搬内部吃掉 ~50KB,`heap internal free=4415 +min=531`,lwIP 分不出包缓冲,`transport_poll_write` 失败 → 会话中途断线重连、服务端从头 +再答——"错乱"的一半是它。回滚后状态回 PSRAM(探针保留),内部堆归还 lwIP。 + +**残留注入口确认**:每次 TTS 前 2-4 秒 ERL 只有 8-10dB,残留 out_rms 均值 800-2800、峰值 +15295,再被 AGC ×1.8 连续上传数秒——ASR 转写成"一出三局"" 《小王子》"("小白"的残留)。 +CPU 压缩已到边际,转入 ③+④。 + +## 步骤 ③+④(本次实现):残留门 + 本地候选闭环 + +实现于 `VoiceFrontend::UpdateBargeInGate`(仅 kBargeInDuplex,采集任务内,无新任务): + +- **相对残留门**:跟踪 `leak = out_rms/ref_rms` 的 EMA(只在被判定为残留的帧上训练,防止 + 被语音带偏;首帧直接播种,首个会话即受门保护;跨会话保留,回声路径不随会话漂移)。 + 帧能量 ≤ `leak×ref×1.5`(下限 200)判为残留 → 不上传。能量跳出 leak 线 → 判为孩子在 + TTS 中说话 → 正常上传(语音头帧不丢) +- **本地候选**:连续 3 帧(180ms)超线 → 发 `kBargeInCandidate` → 复用 reducer 现有可逆 + 暂停,一行 reducer 不改 +- **暂停即探针**:暂停后回声源消失。能量持续 → 真人,此刻上行是无回声干净语音,交服务端 + STT 确认;连续 5 帧(300ms)静默 → 误触发,本地发 `kBargeInRejected` 恢复播放,并把 + leak 线抬 ×1.5 防同级残留复触发 +- **1.5s 悬空超时**:服务端与探针都不裁决时本地 rejected 恢复——补上两阶段设计里 + "candidate 永久暂停"的真实缺口。reducer 的状态守卫使迟到/重复裁决天然为 no-op +- 已知局限(v1 接受):TTS 响段且用户音量恰好等于残留水平时,候选要等到 TTS 句间停顿才 + 触发(中文 TTS 停顿密集,延迟 <300ms 量级);kCallDuplex 不启用门(通话双讲不赌能量) + +新观测指标:`gated=`(拦下的残留帧)、`cand=`、`cand_local_rej=`、`cand_timeout=`。 + +验收(下一次上机):静播全程零 ">>> 用户" 幻听;`gated` 在 TTS 期间持续增长;D1 TTS 中 +正常音量提问 → 暂停 ≤300ms → 回答新问题;D3 误触发 ≤1s 自愈整句播完;内部堆恢复几十 KB、 +无 transport_poll_write 断线。 + +## 步骤 ⑤(因"偶发播报卡顿"提前执行)+ 候选门加固 + +现场反馈:TTS 播报偶发卡顿,旧固件从无此问题。三个成因、三处修复,全部对应旧固件性质: + +**播出余量 60ms vs 旧固件 ~570ms**:旧固件解码在 prio 2 codec 任务,产出 PCM 进 8 帧队列 +(480ms),audio_out 只做 I2S 写,外加 16k 下 6×240=90ms DMA。firmware2 解码+写合并在 +playback 任务,唯一余量是被 C-1 换算错误砍成 60ms 的 DMA。修复:`dma_frame_num` 240→360 +(24k 下恢复 90ms/方向;RX 同步加深,吸收采集抖动);`kReferenceMaxLeadFrames` 2→3 +(TX 变深,参考提前量从 ~1 帧变 ~1.5 帧)。 + +**playback prio 4 被无绑核的 4/5 任务群轮转**:websocket2(4, TLS)、imu_sensor2(5, I2C)、 +touch/battery/alarm/reminder(4) 都可漂到 core 1 与解码同权时间片轮转,10-15ms 的解码偶尔 +被轮到 60ms+。旧固件 audio_out 每次唤醒只是一次 memcpy,同权轮转伤不到它;firmware2 的 +融合任务必须站在服务群之上。修复:`kPlaybackLoop` 4→6(capture 8 之下、服务群之上; +共享互斥锁经 ESP-IDF pthread→FreeRTOS PI mutex,有优先级继承)。 + +**候选门误触发口子(③ v1 的缺陷)**:barge-in 档 NS 关闭、AGC ×1.8,房间底噪被放大到 +~250-300;句间空隙 ref≈0 时绝对下限 200 挡不住 → 误发 candidate → 可逆暂停 ~0.5s,听感 +与卡顿无异。且空隙帧 ratio 退化为 out/1,训练会把 leak 线拖到钳位。修复:下限 200/250 → +500/400(童声实测 ≥2000,两侧均保数量级余量);leak 训练与播种仅在 ref_rms≥300 的帧上 +进行,空隙帧只按绝对下限裁决。 + +验收补充:连续播放长文本无卡顿;`cand_local_rej`/`cand_timeout` 静播时应为 0。 + +## 候选门 v2(2026-07-30 日志复盘:卡顿=误触发暂停,两个根因) + +日志把误触发拍在了脸上:两次 `candidate raised ... leak=0.05` → 暂停 400-580ms → "probe +heard silence, resuming"——首句"我是小白狗"的轻微卡顿正是第一次暂停(02.35-02.75s)。 + +**根因一:播种帧取早了。** 参考帧比声音离开喇叭早 ~1.5 帧(TX DMA 90ms)入队,"第一个 +参考活跃帧"到来时回声还没到麦克风:out≈底噪、ref=1450 → ratio≈0 → 钳到 0.05。 + +**根因二:训练单向向下。** EMA 只在被抑制的帧上训练;leak=0.05 时残留帧全都越线(被当 +语音,不训练)→ 线永远升不上去,只能靠每次误触发 ×1.5 爬,每爬一步 = 一次可闻暂停。 +**低起点是死局,高起点会自愈衰减到真值**——这是本修复的核心不变式。 + +**根因三(幅度抖动)**:回声滞后参考 1-2 帧,逐帧 ratio 在 0.1-1.0 间摆(实测 +out=1437/ref=1450 与 out=787/ref=7325 并存),单帧参考值撑不起一条线。 + +v2 修复: +- **参考峰值**:门限与 ratio 改用最近 3 帧参考的最大值(覆盖 DMA 滞后),幅度抖动收敛 +- **预热播种**:前 8 个响参考帧(~0.5s)无条件不上传,期间记录最坏 ratio 作种子, + 完成后种子下限 0.5(`kLeakSeedMinimum`);预热只在开机后第一次 TTS 发生一次 +- **EMA 下限 0.05→0.15**(≈16dB ERL 的 leak,线没有理由更低) +- 离开 barge-in 时清参考峰值历史,防跨会话残值 + +代价(接受):开机后第一句 TTS 的前 0.5 秒内插话不被上传、候选延后到预热结束; +之后所有会话无此限制。 + +## 剩余步骤 + +⑥ 二期选项 R7:WakeNet 迁 core 1 找回"TTS 中喊你好播乐",产品要求时再做 + +## 已解答的探针 + +`AEC state allocated internal=8876 psram=124028`——esp-sr 的 AEC 状态 132KB,主体在 +PSRAM。配合"内部放置实测无提速"(第三轮),位置问题就此关闭:状态留 PSRAM,内部堆 +留给 lwIP。 + +## 第四轮:唤醒应答与监听窗口(2026-07-30) + +用户症状:① 唤醒后有时不回"我在";② 刚进监听态就立即切走,输入窗口过短。 + +**根因 ②(主):本地 VAD 抢跑关会话。** WakeNet 在唤醒词说到一半就触发, +"你好播乐"的尾音(≥2 个响帧 = 120ms)被 kConversationCapture 的本地 VAD 判为 +speech_started;孩子还没开口,13 个静帧(780ms)后 VAD speech_ended → +kConversationStopRequested → 状态机 kSendStopListening + 回 idle。整个监听窗口 +只活了 ~0.9 秒。协议是 listen mode="auto"(server 端 FunASR/VAD 自主断句 + 补尾), +本地这刀是冗余的,还会在 server 补尾前掐断上行。老固件从不本地断句,无此问题。 + +修复:VoiceFrontend 不再发布 kConversationStopRequested;VAD 保留( +speech_started/ended 日志 + vad_stops 指标,纯观测)。回合结束权完全归 server: +TTS start / 服务端指令 / 按键 / idle 流程(3 分钟 idle_check)才会离开监听态。 + +**根因 ①:欢迎语一次性抑制。** suppress_wake_response 在开机欢迎语后吞掉第一次 +"我在"。产品决策改为无条件应答:每次唤醒必回"我在"。字段与两处逻辑删除, +宿主测试改为断言欢迎语后第一次唤醒也有 kPlayDetachedPrompt。 + +监听时序(修复后):唤醒 → 同帧进入监听(kSendStartListening + LED)+ 播"我在" +(detached,self_capture_hangover 抑制其上行)→ 一直监听直到 server 断句回复。 + +## 配网 BLE 启动失败(2026-07-30) + +症状:双击进配网模式后小程序蓝牙搜不到设备,红灯高频闪(platform error 7001)。 +日志:控制器阶段成功(打印 MAC),`BLE_INIT: hci inits failed` → +nimble_port_init ESP_FAIL。当时内部堆 free=63019 largest=24576(本次开机 +min=539,WiFi 预扫描后释放 +36640 仍高度碎片化)。 + +根因:NimBLE **主机栈**内存池(os_msys mbuf、HCI evt/cmd/ACL 池)配置为 +MEM_ALLOC_MODE_INTERNAL。控制器 enable 吃掉最大连续块后,主机池在碎片化的 +内部堆里分配失败。主机栈纯软件、不碰 DMA,无须内部内存。 + +修复:`CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL=y`(sdkconfig.defaults)—— +主机池全部走 PSRAM(bt_osi_mem_calloc → MALLOC_CAP_SPIRAM),控制器内部 +DMA 分配走独立的 bt_osi_mem_*_internal 不受影响,顺带为控制器腾出 ~20KB+ +内部堆。依赖 SPIRAM_USE_MALLOC=y(已有)。 + +**注意:sdkconfig 在 .gitignore 里,此修复必须重生成 sdkconfig 才会到设备:** +`mv sdkconfig sdkconfig.bak && idf.py build`。好友 BLE 交换同栈同收益。 + +## AudioTap 开机循环崩溃(2026-07-30,热修) + +`CONFIG_BORLA_AUDIO_TAP=y` 在重生成 sdkconfig 后首次生效即触发:tap 任务启动 +就调 lwip_socket(),但 lwIP 的 TCP/IP 线程要等 WiFi 传输层调 esp_netif_init() +才创建 —— lwIP 对此不是返回错误而是断言 `Invalid mbox`,开机循环重启。 + +修复:Run() 先等 `esp_netif_get_nr_of_ifs() > 0`(netif 存在即证明 +esp_netif_init 已完成)再建 socket。等待期间 PSRAM 环形缓冲照常收录, +开机提示音不丢。 + +## 双击失效(2026-07-30) + +症状:配网模式内双击无反应;日志里两次相隔 130-290ms 的点击各报 +`button clicked count=1`,从无 count=2。 + +根因:iot_button 的 `short_press_time` 不是"短按判定时长",而是**松开后 +等待下一次按下的连击合并窗口**(PRESS_REPEAT_DOWN_CHECK:超窗即按当前 +repeat 数定格为单击/双击)。firmware2 写 50ms —— 人手双击间隔 130ms+, +第一次点击 50ms 后就定格成单击,第二次再成一个单击。老固件传 0 → 组件 +默认 180ms,故正常。K 轮对比时误读了该参数语义。 + +修复:kButtonShortPressMs 50 → 180。副作用:单击回调延迟从 50ms 变 +180ms(等窗口关闭才能确定不是双击),与老固件一致。 + +附带确认:reducer 对 value==2 无条件 EnterProvisioning —— 双击修复后, +配网模式内再双击即重走配网入口(BLE 失败时 active_=false,HandleStart +会完整重试)。15:37 那次进配网是 server 的未绑定引导指令,非按键。 + +## BLE 仍失败的复盘(2026-07-30 第二次) + +15:50 日志仍 `hci inits failed`。两项决定性验证: +1. 读通 IDF 5.4.3 全路径:controller init/enable 均成功(无对应错误日志)、 + npl 池是普通 malloc 且返回值不被检查 —— 能走到该错误的**唯一**分支是 + bt_osi_mem_calloc 按 INTERNAL 模式分配失败。即该固件编译的还是 INTERNAL。 +2. 本机删 sdkconfig 全新 reconfigure:EXTERNAL=y 正确出现在生成的 sdkconfig + 与 build/config/sdkconfig.h —— defaults 传播无问题。 + +结论:该次烧录未执行 sdkconfig 重生成(命令历史仅 git pull && build)。 + +加固:BLE 启动前日志追加 host_pools= 编译期字符串(PSRAM / internal +(STALE sdkconfig — regenerate!) / default),设备日志自证构建新旧, +不再靠猜。刷前自检:`grep BT_NIMBLE_MEM_ALLOC_MODE sdkconfig`。 + +## 重生成后 WiFi 连不上(2026-07-30 第三次,根因闭环) + +BLE 修复生效后(配网成功、凭据已存),设备反而连不上 WiFi:每次 +init->auth 后 1 秒超时回 init(0x200),伴随 `wifi:m f auth` / `m f probe +req l=0`(m f = malloc fail —— 认证帧都分配不出来)。诊断行: +`heap internal free=5111 min=5091 largest=4608`。 + +根因:TRY_ALLOCATE_WIFI_LWIP=y 会把 WiFi 缓冲的 Kconfig 默认值悄悄抬高 +(static rx 10→16、rx_ba_win 6→16),而 static RX/TX 是 DMA 缓冲永远占 +内部 RAM。老固件把该开关与显式压制成对使用(rx=6/dyn=8/ba=8,defaults +可查),firmware2 的 defaults 只抄了开关没抄压制 —— 旧的手工 sdkconfig +里恰好有旧值兜着,一重生成就爆雷。这也是"sdkconfig 被 gitignore"陷阱的 +第三次变体:**调优必须完整落在 defaults,否则 regen 即回归**。 + +修复(sdkconfig.defaults): +- CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=6 / DYNAMIC_RX=8 / RX_BA_WIN=8 + (老固件同款配对;static tx 保持默认 16,与老固件运行值一致) +- 顺带移植老固件的 CONFIG_MBEDTLS_SSL_RENEGOTIATION=n(teardown 期 + ssl->session 空指针 LoadProhibited 崩溃防护,我们服务器不用重协商) + +验证:全新 regen 后七项关键值全部正确落盘,全量编译通过。预期开机行: +`Init static rx buffer num: 6` / `rx ba win: 8` / `WiFi/LWIP prefer SPIRAM`, +WiFi 认证一次通过,内部堆恢复到几十 KB。 + +## 唤醒后多播欢迎语(2026-07-30) + +链路:软待机(idle_check 15s 无应答 → 关 WS,唤醒词常开,非 light sleep) +→ "你好播乐" → 播"我在" + 重连 → server 对每个新 WS 会话都推 +play_local welcome → 设备状态机"取消当前播放+播提示"→ 掐断"我在"、 +kSendStopListening、上行关闭 ~4 秒、播"我睡醒了"。 + +修复(设备端,server 不动):kLocalPromptRequested 中 prompt==kWelcome 且 +conversation==kListening 时,回执 started+done(立即释放 server 的 +playing_local 锁)但不播、不撤监听。非监听态(如开机自动连接)欢迎语照播。 +宿主测试 TestServerWelcomeSkippedWhileListening 锁定两个分支。 + +同日志确认:内部堆 free=1299 min=23 largest=1024(空闲态!),4G UART +探测每 30s malloc 失败 —— 仍是"重生成缺失"的膨胀 WiFi 缓冲配置在跑, +b6e794a6 的 6/8/8 未进设备。等待用户按三步重刷后复查。 + +## "服务器开小差"循环:AEC 内存棘轮(2026-07-30,结构性根因闭环) + +新 WiFi 配置确认生效(rx6/ba8/prefer SPIRAM,认证一次通过;BLE 配网全流程 +成功 host_pools=PSRAM)。但首次 TTS 仍断线,且此后永久瘫痪: + +``` +TTS开始 → esp-aes 分配失败 → WS断开 internal_free=4011 + → AEC state allocated internal=12376 ← 趁 WS 释放缓冲瞬间抢走 +之后所有重连: internal_free=75 largest=16(数分钟不恢复)→ 无限 server_error +``` + +三个叠加根因: +1. **aec_create 投机式吞内部堆**:有多少吃多少(实测 2600/7404/8980/12376 + 字节不等),Suspend 保留句柄(保学习滤波器)永不归还 —— 首次 TTS 时机 + 恰逢 WS 断开释放缓冲,AEC 把重连预算整个端走,TLS 从此死锁。 +2. **barge↔call 档位切换 Disable+重建**,而 aec_create 参数两档完全相同 + (mode/filter 均为常量)—— 会话中途无谓的二次抢占。 +3. **esp-aes 每条 TLS 记录都要内部 DMA 反弹缓冲**(mbedtls 缓冲在 PSRAM), + 对内部堆水位最敏感,是第一个倒下的。 + +修复: +- VoiceDsp::PrewarmEchoCancellation():开机时(WiFi 驱动创建前、内部堆 + 富裕无碎片)用 8KB 护栏块占满内部堆(留 8KB 底)逼 aec_create 落 PSRAM, + 建好即挂起。位置对速度无影响是本审计早期的实测结论(~50ms/帧两者相同)。 + VoiceFrontend::Initialize 调用,失败非致命(回退旧懒加载路径)。 +- EnableEchoCancellation 档位切换只改 barge_in_profile_ + Reset(),不再重建。 +- CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=4096(默认 16384):≥4KB 的普通 + malloc 先走 PSRAM,中型缓冲(websocket rx、http、cJSON)不再挤占内部堆, + 给 esp-aes 的 DMA 反弹缓冲留出常备水位。 + +附带确认:配网模式重试路径 capture 任务创建失败(error 2002 自动重启) +同为内部堆枯竭症状,此修复一并覆盖。welcome-skip 逻辑本日志中行为正确 +(kIdle 时欢迎语照播)。 + +## AEC 预热护栏失效 → 开机循环崩溃(2026-07-30,热修) + +预热本身按计划在 WiFi 前运行了,但固定 8KB 护栏块在第一个 <8KB 碎片上 +分配失败即退出(开机堆 = 各内存区尾巴 + 32K DMA 池分块,碎片天然多), +esp-sr 的几十个小块分配把护栏占不住的 24.9KB 碎片全部吃下 +(internal=24892,比懒加载时代还多)。WiFi 驱动随后只剩 ~700B, +phy_track_pll_init 的 esp_timer_create(显式内部分配)NO_MEM → +ESP_ERROR_CHECK abort → 开机循环。 + +修复:护栏改为"按当前最大空闲块递减占位"——每轮查询 +largest_free_block(留 256B 头空间),直到总空闲 ≤8KB 或块 <1KB, +32 个槽位。小碎片一并占住,esp-sr 只能落 PSRAM。新增 +"AEC prewarm guards= held= free= largest=" 日志行自证护栏效果。 + +## R7 落地:TTS 播报中恢复"你好播乐"打断(2026-07-30) + +产品要求确认,二期选项 R7 转正。当年禁用依据是"AEC+WakeNet=68ms/帧超 +预算",但该测量含同任务的 Opus 编码;现编码在核 1、复杂度 3,双工 +process 实测均值 10-15ms(峰值 37ms),WakeNet ~14ms 可入 60ms 预算。 + +改动: +- WakeRequired() 纳入 kBargeInDuplex —— 双工分支本就产出 AEC 净化信号, + 直接喂 WakeNet(回声已衰减 10-20dB,自触发风险低;误触发走普通 + barge-in 状态机路径,可自愈)。自然语音打断仍归 server VAD/ASR 仲裁。 +- 状态机 kSpeaking + 唤醒词源:取消播放 + 进监听 + 补"我在"应答 + (按键打断保持静默)。宿主测试断言两分支。 + +回退观测点:frame stats 的 period_avg 若爬过 ~65ms(播报卡顿回归), +升级为专职核 1 唤醒任务(R7 完整版)。 + +## 音乐中唤醒需要喊(2026-07-31) + +R7 生效(音乐可被唤醒词打断,wake=3 检出、状态机正确切换),但正常音量 +说唤醒词检不出,要喊到 mic_rms≈20000 才行。日志排除法: +- 帧预算正常(period_avg 61-63ms)→ 非算力问题 +- server 有 wake_word_control 但 wake=1 保持 → 非远程禁用 +- 纯音乐区间 AEC 正常(09:41:39 erl=27.4dB);erl 1-3dB 的区间全是 + 双讲(AEC 不该消人声,该指标双讲时无意义)→ 非 AEC 失效 +- 顺带证伪了"参考随软件音量缩放是 bug":老固件同为硬件恒 100 + 软件 + 缩放(es8311_audio_codec.cc:111 注释),参考镜像缩放是正确配对 + +真凶(差分定位):空闲唤醒喂 WakeNet 的是**原始麦克风**,双工唤醒喂的 +是 **AEC+AGC 之后**的信号 —— barge 档 AGC 在音乐+人声双讲下增益在 +0.90↔1.80 间剧烈摆动(日志实测),一句"你好播乐"说到一半被增益台阶 +切割,WakeNet 特征匹配失败;喊叫时 AGC 压到下限不再摆动,反而能检出。 + +修复:VoiceDsp::Process 增加 wake_tap 出口(AEC 之后、NS/AGC 之前拷贝), +双工分支 FeedWakeWord 改喂 wake_tap。上行仍用 AGC 后信号(server ASR +需要),仅唤醒检测回到与训练域一致的干净信号。 + +遗留观察项:音量显示 4%(restored volume=4%)但响度不低 —— 软件缩放 +4% 理论上近静音,疑似 server 音量刻度不匹配(0-10 档被当 0-100%), +另行排查。 + +## TTS 卡顿/不流畅复查:先计量后动刀(2026-07-31) + +链路核查结论: +- server 发帧节奏(audio_send.py,只读):前 PRE_BUFFER_COUNT=6 帧立即 + 猝发,之后 60ms/帧单调时钟限速,段间连续计时。→ 设备端全程抗抖动 + 预算 = 6 帧(360ms) + 90ms I2S DMA ≈ 450ms,且设备侧无自建预缓冲。 +- 设备扬声器任务:帧到即解码即写,唯一节流是阻塞式 DMA 写。候选暂停 + 路径是刻意保留(可逆 barge-in)。 +- 疑点排除:R7 后 period_avg 61-63ms 正常;48 槽就绪队列远大于 6 帧 + 猝发不会满;候选误暂停已被 gate v2 压到 cand=0~3。 + +结论:凭现有日志无法区分"网络抖动>450ms"与"设备内部断口",先补计量。 +新增 playout health(每会话一行,扬声器任务独占无锁): +- 逐帧测量相邻两次 Write 之间的间隙:>60ms 记 gaps>frame(缓冲耗尽)、 + >90ms 记 gaps>dma(DMA 也排空,必然可闻);max_gap 峰值 +- 就绪队列深度 min..max(猝发缓冲的健康水位,正常应 4~6) +- 候选暂停期间跳过间隙采样(刻意保持不算饥饿) + +判读:depth 常态 4~6 + gaps=0 → 播放侧健康,卡顿另有来源(如策略切换 +瞬间);depth 掉 0 + gaps>dma>0 → 网络/WiFi 抖动超预算,方向是 WiFi +省电/信道诊断或设备端加启动预缓冲换时延。 + +## playout health 首批数据判读 + 断流重建(2026-07-31) + +数据(用户实测两次开机、多轮对话): +- 本地提示音会话:max_gap 5-12ms、gaps=0、depth 峰值 46 —— **播放引擎 + 自身零缺陷**,设备内部断口排除。 +- 远程 TTS 会话:depth 常态 0..2~4(6 帧猝发从未站稳),句间频发 + 60-145ms 间隙;最差一个会话 16 次 60-81ms 微间隙(即"不流畅"体感)、 + 两个会话各 1 次 >90ms 可闻断口(其一为候选暂停恢复后 145ms)。 +- AEC 预热护栏实测生效:internal=656/788 字节(此前 24892),本次会话 + TLS 零断线、UART 探测零失败;min=23 为预热护栏挤压瞬间,属预期。 + +根因链(server 只读核实):server 逐句合成 + 60ms/帧限速;句间生成延迟 +超 MAX_AUDIO_SCHEDULE_LAG_MS=180ms 时仅"重新对表"不补发 —— 之后整段 +回复缓冲垫贴零,任何抖动直达喇叭;候选暂停恢复同样零缓冲垫。 + +设备端修复(server 不动):扬声器任务检测"迟到帧"(距上次写完 >60ms += 队列已跑干、DMA 正在排空),持帧最多 150ms 等下一帧到位再开播 —— +一串微间隙合并为一次短暂停顿 + 后续流畅。排空期(input_ended)与候选 +暂停期间不持帧;持帧中每 10ms 复查 input_ended 防尾帧误延。 + +预期新日志形态:gaps>frame 总数大幅下降,偶见单次 max_gap≈150-210ms +(重建暂停),体感由"毛刺"变"顿一下接流畅"。 + +## 录音第三通道:server 之耳(2026-07-31) + +用户疑问:mic.wav 里混着 TTS,是否意味着回声消除失败、server 收到了 +设备自己的声音?答:mic.wav 按设计录的是**硬件边界的原始麦克风** +(AEC 之前),麦克风物理上必然听到喇叭 —— 它是诊断输入,不是上行。 +上行 = 原始 mic → AEC → 残留门控 → Opus。 + +为让"server 到底听到什么"可被亲耳验证,AudioTap 增加第三环(uplink, +16kHz):采集任务在门控判定后推流 —— 通过的帧推处理后 PCM,被抑制/ +非上行策略的帧推等长静音(时间轴与 mic/spk 对齐,可逐秒 A/B 对听)。 +协议 hello 升 v2(16 字节,双采样率),脚本产出第三个文件 +<时间>-uplink.wav。判据:uplink.wav 中应只有用户语音(少量残留可接受), +TTS 段应为静音或极弱残留;若清晰可闻 TTS,才是真的回声泄漏。 + +## uplink 残留复盘:参考环引灌(2026-07-31) + +用户实听 uplink.wav:每 ~0.5s 有 ~0.1s 的 TTS 残留通过门控,节奏与播放 +卡顿一致。结合此前 frame stats 的强相关证据: + + ref_depth≈2 → erl 15.8~19.6dB(消得干净) + ref_depth<1 → erl ≤8.7dB(残留大) + +机制闭环:回声从"参考帧入环"到回达麦克风要过 ~90ms TX DMA;滤波器 +跨度仅 64ms,参考环深度 ≈2 帧时对齐、<1 帧时错位。server 限速造成的 +每个播放断口都会抽干参考环;重新开播后深度从 0 起步且推/放同速**永不 +自愈**,整段猝发错位泄漏,直到抖动碰巧攒出深度 —— 与"每断口后泄一段" +的听感完全吻合。 + +修复:PopReference 增加引灌门槛 —— 环清空后须重新积累 +kReferencePrimeFrames=2 帧才开始供给(头 1-2 帧的回声尚在 DMA 中未到 +麦克风,按"无参考+扬声器活跃"处理,现有防护抑制其上传,无泄漏窗口); +ClearReference/pop-empty 时复位引灌标志。 + +验收:uplink.wav 中 TTS 时段应接近全静音;frame stats 中 ref_depth +均值应稳定 ≥1.5,erl 不再随播放断口跳水。 + +## R7 完整版落地 + 门控二次确认(2026-07-31) + +引灌后用户实听"好多了,还有一点点残留"。新日志定位两个残余源: +1. **采集任务超预算**:capture timing 显示部分窗口 process 均值 59-64ms、 + 峰值 84ms,period_avg 66-70ms —— AEC+WakeNet 最坏情况叠加超 60ms, + 麦克风积压、参考环被顶到修剪上限(ref_trims 4-9/窗口)、对齐晃动。 + 正是 R7 时预设的升级判据(period_avg>65ms),触发即执行: + **WakeNet 迁核 1 专职任务 wake_scan2**(prio=kAudioCodec=2,12KB PSRAM + 栈,6 帧 PSRAM 队列)。采集任务只 memcpy 一帧入队即走;accumulator/ + cooldown 归扫描任务独有,wake_mutex_ 串行化 Detect 与模型加载/释放, + 跨任务复位改用 wake_reset_pending_ 标志。队列满则丢帧(扫描落后 + 360ms 时保麦克风流与 AEC 对齐优先)。 +2. **音节起音尖峰**:孤立单帧过线是残留尖峰的典型形态(自适应滤波器对 + 瞬态欠消除),真人说话天然连续。门控增加二次确认:连续第 2 帧起才 + 放行上行,首帧扣留 —— 真实插话仅损失 60ms 起音(server ASR 可容忍, + 候选判定本就需 3 连续帧,不受影响)。 + +预期:period_avg 回落 ~61ms、ref_trims 归零、uplink.wav 残留尖峰消失; +音乐中唤醒灵敏度亦应受益(扫描任务不再被采集预算挤压)。 + +## "spk 不卡、mic 卡"判读修正 + 起播预缓冲(2026-07-31) + +用户对听三通道:uplink 已干净;spk.wav 听不到卡顿、mic.wav 听得到。 +判读修正:**spk.wav 原本是撒谎的** —— 它只在写入 DAC 时记录,写入迟到 +时前后帧在文件里无缝拼接,断口被时间轴吞掉;mic 录的是房间真声。 +"spk 干净 + mic 卡顿"恰恰证明断口 = DMA 饥饿(数据未及时到达 DAC)。 + +两项修复: +1. **spk.wav 修诚实**:Es8311 Write 记录相邻写入间隙,超过一帧周期的 + 部分补等长静音入 spk 环(单次上限 500ms),三通道时间轴从此对齐, + A/B 对听即真值。 +2. **起播预缓冲 180ms**:远程 TTS 会话首帧前固定持留 —— server 超前量 + 6 帧(360ms) 且失速后只重锚不补发、垫子只减不增;起播延迟直接加到 + 超前量上,全程失速预算 360→540ms,句间生成延迟造成的中途断口被 + 吸收。本地提示音豁免(全量在手、时延敏感)。持留期间会话被取消/ + 抢占则立即放行。 + +验收:mic.wav 中 TTS 段不再断续;playout health 的 gaps>dma 归零; +新 spk.wav 与 mic.wav 逐秒对齐。 + +## 候选暂停循环:最后的"偶尔轻微卡顿"(2026-07-31) + +起播预缓冲后 playout health 全绿(7 会话 gaps 全 0)——写入路径卡顿清零。 +用户仍偶感轻微卡顿,日志锁定新元凶:**候选误暂停循环**。会话 21 六秒内 +四次候选(1 次探测静音判负 + 3 次连续 1.5s 超时),累计暂停 ~4.8s; +暂停期间 server 持续发流,48 槽队列被塞满溢出,"downlink Opus dropped" +×30 ≈ 1.8s 音频被丢 —— 恢复播放时句子中间缺块,即耳中"卡顿"。 +playout health 对此免疫(候选暂停属刻意行为不计饥饿)。 + +根因:候选判负后无再武装门槛,同一股持续能量(双讲)立即重触发。 + +修复: +- ResolveCandidateLocked 记录判负时刻:新候选须同时满足 ①2s 冷却期满 + (kCandidateRearmUs)②期间至少一帧回落到泄漏线下(candidate_needs_ + quiet_)。冷却期间上行照常流动,server 端打断仲裁完全不受影响 —— + 本地暂停只是锦上添花,权威裁决在 server。 +- 超时判负额外抬线 ×1.25(server 都未确认的持续能量多为底噪抬升; + 探测静音判负原有 ×1.5 不变)。 +- 计数器与触发解耦(每流每帧递增、恰好等于阈值时触发一次), + 两帧确认规则(==1 扣留)语义不变。 + +观察项:双讲窗口 encoder 峰值 100-174ms(核 1 与 wake_scan 轮转), +uplink 未受损(submit 正常、转写完整),暂不处理。 + +## 会话起始候选误触:卡顿最后一里(2026-07-31) + +新日志:写入路径七会话全绿(含 257 帧长回复),re-arm 生效无连环循环。 +剩余四次候选暂停**全部落在 TTS 会话开始后 1 秒内**、无一在句中: +- leak=0.00 一例:门控未播种(首次 TTS 预热中),纯凭绝对底线误触; +- ref_active=0 一例:参考未流动,能量无从归因,底线误触后 1.5s 超时; +- 两例在会话开始 ~700ms 处:AEC 每会话开头重新收敛(erl 8-10dB), + 残留高于按收敛态(17-25dB)训练的泄漏线。 + +收紧(三个新前置条件,全部只影响"本地暂停",上传与 server 仲裁不变): +候选须满足 ①门控已播种 ②当前参考活跃(有回声源才有歧义,pause-probe +才有价值)③本双工窗口已积累 ≥15 个参考活跃帧(~0.9s,盖住 AEC 收敛期, +kCandidateHoldoffFrames)。窗口计数在离开 kBargeInDuplex 时复位。 + +代价评估:收敛期内真人插话不再有本地抢跑暂停,但语音照常上传、server +照常可打断(~1-1.5s),唤醒词打断即时可用——产品可接受。 + +## 双讲残留脉冲误候选:强度线 + trim 静默期(2026-07-31) + +7 分钟成语接龙实测:写入路径 35 会话仅 1 次 96ms 断口(session 26,孤例), +但 cand=20 全部误报(唯一真实打断走唤醒词),每次误暂停 0.4-1.5s——这就是 +"偶尔卡一下"。20 次误候选 out_rms 全在 510-1552;真人语音 2000-9000。 + +根链:双工窗口采集环平均周期 63-65ms(预算 60)→ 参考环深度爬到上限触发 +trim(本局 ref_trims 0→15)→ 参考时间轴瞬跳 60ms(> AEC 64ms 滤波跨度)→ +失配残留冲过 500 底线 3 帧 → 误候选。encode= 200-600ms 尖峰为核 1 编码任务 +被解码/唤醒扫描挤压的排队时间,不直接卡采集,维持观察项。 + +修复(均只影响本地暂停,上行门限/训练不动): +1. kCandidateStrongRms=1100:候选需连续 3 帧 ≥1100(独立计数器), + 上行 pass 底线仍 500——轻声照常上传,server 仲裁路径完整; +2. trim 时间戳 kAlignmentSettleUs=2s:trim 后 2 秒禁举候选(排空 re-prime + 是对齐设计,不压制)。 +预期本局 20 次误暂停被清零(16 次被强度线杀、其余落在 trim 静默期内)。 + +## 双工复活:段级放行窗 + 峰值判据(2026-07-31) + +实测决定性证据:TTS 播报中人声在 uplink 完全缺失——逐帧 RMS 门控把双讲 +抑制后的语音(AEC 对近端衰减 10dB+,门控处仅数百 RMS)整体判为残留吞掉。 +这同时解释了 server 两阶段仲裁(server VAD→candidate→ASR+回声相似度→ +confirmed,config 全开)长期虚弱:它收到的只有偶尔冒线的 60ms 碎帧。 + +修复(固件侧,server 未动): +1. 段级放行窗 kUplinkPassWindowUs=800ms:连续 2 帧过线即开窗,窗内全帧 + 放行(含包络低谷,泄漏线不训练窗内帧),过线帧持续续窗;停止过线 + 800ms 后恢复逐帧抑制——稳态 uplink 依旧静音,代价是脉冲后 <1s 残留尾。 +2. 候选判据改"形状":条纹 ≥3 帧过线 且 条纹峰值 ≥kCandidateStrongRms。 + 峰值线按双讲现实定 900(上一版 1100"连续帧全高"对包络语音不可满足, + 本地腿全灭)。残留是无峰平台、语音必有音节峰。 +3. 防抖四闸门全保留:trim 静默 2s、起始 holdoff 15 帧、rearm 2s+必须 + 安静一帧、未播种/参考不活跃不举。上份日志 20 次误触大多与 trim 同窗, + 静默期仍拦截主力误报;漏网者单次 450ms 探测暂停、rearm 限频不成环。 diff --git a/docs/hardware-validation-checklist.md b/docs/hardware-validation-checklist.md new file mode 100644 index 0000000..a3d1a3c --- /dev/null +++ b/docs/hardware-validation-checklist.md @@ -0,0 +1,221 @@ +# Firmware 2 真机验证清单 + +> 本清单记录真机和外部环境验收。按顺序执行;失败时先停止后续破坏性步骤,保存 +> 完整串口日志、固件版本、设备 MAC 和复现条件。 + +## 0. 烧录前 + +- [ ] 确认测试设备可被擦写,旧固件/NVS/`claude_mem` 是否需要先备份。 +- [ ] 确认 UART、I2C、I2S、Touch、BMI270、ADC、ML307 引脚与当前板版本一致。 +- [ ] 确认 `CONFIG_BORLA_ML307_APN` 和 server/OTA 地址适用于测试环境。 +- [x] 保存 `build/borla-firmware2.bin` 对应构建日志;当前待复刷基线大小 + `0x24ace0`,SHA256 为 + `14c7fb88ea2c4ab177e1986fb2efd0d4d91213647ebe6fa15a12f264691270df`。 + +建议命令: + +```bash +cd firmware2 +idf.py -p flash monitor +``` + +macOS 建议使用 `/dev/cu.usbmodem*`,避免 monitor 关于 `/dev/tty.*` 的 GDB 提示。 +若工具目录通过符号链接指向实际 Python venv,先把 IDF 变量归一到当前解释器的 +真实前缀,可消除“interpreter is not from installed venv”环境警告: + +```bash +export IDF_PYTHON_ENV_PATH="$(python -c 'import sys; print(sys.prefix)')" +idf.py -p /dev/cu.usbmodem83301 monitor +``` + +若上一版日志已经进入 `entering final light sleep timer_us=0`,随后烧录报 +`Failed to connect ... No serial data received`,先断开并重新接入 USB 使芯片硬复位, +再单独执行 `flash monitor`,不必重复 `fullclean build`。仍无法握手时,按住 BOOT, +短按 RESET,松开 BOOT 后重试;该错误发生在 ROM 下载握手前,不能算作新镜像的 +启动失败。 + +## 1. 启动与基础硬件 + +- [x] 启动日志分别出现 `playback ... stack_bytes=36864 memory=PSRAM`、 + `capture2 ... stack_bytes=32768 memory=PSRAM`、 + `connectivity2 ... stack_bytes=8192 memory=internal` 和 + `dual_network2 ... stack_bytes=8192 memory=internal`。 +- [x] 启动日志出现 `runtime_diag2 ... stack_bytes=8192 memory=PSRAM` 和 + `EspWebsocket2 ... command_pool=PSRAM telemetry=latest-wins stack_bytes=12288 + memory=internal`。 +- [x] 启动日志出现 `LocalPromptPlayer2: worker started stack_bytes=6144 + memory=PSRAM queue=4`;反复断网重试时不再出现 + `failed to create prompt producer task`,任务数量不随提示次数增长。 +- [x] 持续监视超过 110 秒,不再出现 `stack overflow in task playback`、 + `stack overflow in task connectivity`、`stack overflow in task esp_timer`、 + `Guru Meditation` 或自动重启。 +- [ ] 每个本地提示 session 最多出现一条 `frame pool backpressure`,不再连续 + 刷屏;提示音仍可完成或被更高优先级会话正常抢占。 +- [x] 保存启动后 5 秒和 30 秒两组 `RuntimeDiagnostics2` 日志,应用关键任务 + `stack_free_bytes >= 512`,内部 heap 仍有稳定余量。 +- [x] 串口完整经历 Cold → Starting → Running,无 panic/watchdog。 +- [ ] app_main 后的普通 `ESP_LOG` 行均以设备 MAC 开头;ServerHello 校时前显示 + `TIME-UNSYNCED+...ms`,校时后切换为形如 + `[2026-07-21 14:23:09.962]` 的 UTC+8 年月日时分秒毫秒。ROM、bootloader、 + early/DRAM log 与第三方直接 `printf` 不纳入此项。 +- [x] ServerCommand 生产解析器已改为 PSRAM 原位写入;`ParseHello` 机器码栈帧 + 从 4736 bytes 降为 64 bytes,所有 dispatcher 函数低于 1KB 编译门禁。 +- [ ] 连续冷/热启动 10 次,每次均越过 ServerHello/WakeNet ready 并运行 60 秒; + `ServerHello parsed stack_free_bytes >= 2048`,无 stack canary/Guru Meditation。 +- [x] 启用栈尾 watchpoint,定位并修复 `friend_service2` 在 + `NvsFriendStore::Save` 的溢出;好友/闹钟大快照迁入 PSRAM,任务栈均为 4KB, + 复刷后多轮对话未再触发 watchpoint。 +- [ ] GPIO4/GPIO6 电源轨正确。 +- [ ] GPIO11 LED 的 Starting/Connecting/Idle/Listening/Speaking/Error/Off 正确。 +- [ ] GPIO12 单击、双击、三击、四击、长按均只触发一次。 +- [ ] 三击/四击均上报 `button` 遥测;server 交换映射、`nothing` 和重启 + 持久化均正确,单击/双击/长按不受远程配置影响。 +- [ ] ES8311 初始化成功,开机音完整,无爆音、底噪或缺尾帧。 + +## 2. WiFi、Realtime 与普通对话 + +- [x] 从当前 NVS 读取 WiFi 凭据并 DHCP 成功(旧格式迁移仍待专项验证)。 +- [ ] 无凭据时双击 BLE 配网,小程序完成扫描、配置、通知和重连。 +- [ ] 错密、AP 不存在、路由器断电时无重连风暴。 +- [ ] AP 恢复后自动连接,WebSocket hello/心跳恢复。 +- [x] TLS 建连不再出现 `mbedtls_ssl_setup returned -0x7F00`;若后续仍出现,保存 + 同一时刻的 `RuntimeDiagnostics2` heap 快照。 +- [x] WebSocket TLS 握手期间由 PSRAM 承担动态对象和 record buffer,证书校验、 + upgrade、ClientHello/ServerHello 均成功;OTA HTTPS 握手仍在 OTA 专项中验证。 +- [ ] 首次 server 不可达与在线后全网断开分别播放配置的 + `server_unreachable`/`no_network` 提示,非法配置不覆盖已存值。 +- [x] 单次和连续多轮对话完成;上行 16k/下行 24k、60ms Opus 基础链路建立。 +- [ ] 完成至少 3 轮中文对话;每轮串口出现完整的 + `ConversationText2: direction=input text=...`,AI 每个 TTS 分句出现完整的 + `direction=output text=...`,中文无乱码、无截断,且前缀 MAC/日历毫秒时间正确。 +- [ ] 复刷确认 TTS 首字完整,串口不再出现 `downlink Opus dropped`。旧镜像长 + 日志中 22 个 session 共丢 71 个开头帧,最多单 session 6 帧;当前代码已加入 + 8 帧 PSRAM pre-roll 并通过自动测试,仍需真机听感与打断/网络抖动复验。 +- [x] 遥测突发期间不再出现 `command pool exhausted`,控制/音频槽不被 10Hz + 传感器文本占满,连续对话期间无由此导致的断线或重连风暴。 +- [ ] 唤醒词、近讲、远讲、噪声、TTS 自唤醒和 AEC 回声场景通过。 +- [ ] 普通 TTS 播报中说“你好播乐”,设备立即停播;日志依次出现 + `wake_word_detected`、`abort requested source=...kWakeWordDetected` 和 Listening, + 随后说出的新问题能得到新回复。 +- [ ] 连续完成 5 轮对话,每轮新 TTS 开始后的 0.5~1.5 秒内说“你好播乐”;不得因 + 上一轮 WakeNet 防重复计数冻结而漏检。另在 TTS 尾部 `tts_stream_ended` 到 + `playback_drained` 之间说一次,仍必须立即打断。 +- [ ] 故事/音乐等 `barge_in=false` 场景仍进入 `kWakeWordDuplex`,说“你好播乐” + 可以打断;不得退化成播放 reference 活跃时整段跳过 WakeNet。 +- [ ] 普通 TTS 播报 1 秒后,在 0.5m 和 1m 分别自然说出至少 10 个新问题,不带 + 唤醒词;日志应依次出现 server `barge-in voice detected during TTS`、设备 + `barge_in_candidate`/`playback paused`、最终 `barge_in_confirmed` 和旧 session + 取消。每个新问题均有 STT 输入和新 TTS 回复,问题首字不被切掉。 +- [ ] 专项复现“月亮是怎么升起来的”:分别在 TTS 中段和最后一句尾部开始提问。 + `tts_stream_ended` 后、`playback_drained` 前日志应继续保持 + `kBargeInDuplex capture=1`;最终输入必须是完整问题,不得变成“你觉得呢?”。 +- [ ] 对同一次 candidate 测量:从人声起点到设备静音、从停说到 confirmed、从 + confirmed 到新回复首帧的时延;保存固件与 server 同一时间段完整日志。 +- [ ] 构造会被 ASR 判为 TTS 回声或无意义噪声的候选;设备收到 + `barge_in_rejected` 后必须从原暂停位置继续,不能重播整句、爆音、丢 session 或 + 保持永久静音。 +- [ ] 无人说话连续播报 10 分钟,并分别加入空调/风扇、走动、轻音乐、桌面单次 + 敲击和物体碰撞;允许出现 candidate/rejected,但不得出现 confirmed、旧回复 + 取消或设备自行发送 `abort(reason=user_initiated)`。 +- [ ] server 下发音量 0/50/100 立即生效,超界值分别钳位到 0/100。 +- [ ] `wake_word=false/true` 分别禁止/恢复 WakeNet,按键发起对话始终可用。 +- [ ] `barge_in=false` 时 TTS 期间无自然插话上行;设为 true 后抓包确认每个上行 + 包只含一个 60ms Opus 帧,普通 Listening 仍可使用 5 帧批量。 +- [ ] 临时安全红灯按指定时长闪烁,结束后恢复期间最新的业务灯效。 +- [ ] 配网、轻睡眠和关机前 server 收到 `goodbye` 并立即清理会话;断网导致 + goodbye 发送失败时,设备仍能完成对应本地状态切换。复刷时同时确认长按关机 + 不再出现 `transport_base: poll_write ... connection abort` 和 + `transport_ws: Error transport_poll_write`。 + +## 3. 4G + +- [ ] ML307 `AT` 探测、SIM ready、CEREG registered、CSQ/operator 正常。 +- [ ] APN 拨号后 PPP 获取 IPv4,DNS/TLS/WebSocket 可用。 +- [ ] WiFi 离线 30 秒自动转 4G。 +- [ ] WiFi 连续弱于 -80 dBm 达门限后转 4G。 +- [ ] 四击 WiFi→4G→WiFi,提示音和 Realtime 重建正确。 +- [ ] 无模组/无 SIM/注册拒绝/PPP 丢线能回到 WiFi,不重启循环。 +- [ ] 4G 连续对话无控制面阻塞和不可恢复断流。 + +## 4. 传感器、日程与电源 + +- [ ] 五路 Touch press/release/long-press 成对且无漂移误触。 +- [ ] BMI270 静止、姿态、抛起、自由落体、接住和撞击事件合理。 +- [ ] 电池电压/百分比与万用表对照;充电状态符合硬件能力。 +- [x] 无电池或 ADC/分压异常时日志显示 `invalid battery sample`,状态保持 + unavailable,运行超过 60 秒且不触发 `critical_battery`、`low_battery_10` + 或软关机。 +- [ ] Reminder、重复/一次性 Alarm、首日 20:30 闹钟和 NVS 重启恢复。 +- [ ] 3 分钟 Idle 提示、15 秒响应、10 分钟告别和软关机。 +- [ ] 睡眠场景完整播放 `snore_light`,设备上报 `play_local:done` 后 server + 才下发 `light_sleep`;随后 WebSocket 关闭、灯灭且不会继续上行音频。 +- [ ] 轻睡眠状态下唤醒词或 GPIO12 可唤醒,网络和 Realtime 能重新建立。 +- [ ] GPIO12/RTC 唤醒后状态、网络和音频恢复。 + +## 5. OTA + +- [ ] optional/auto/force 三种策略。 +- [ ] HTTPS 下载、size/SHA256 校验、备用分区写入和重启。 +- [ ] 新镜像自检成功后确认有效。 +- [ ] 人为制造自检失败,bootloader 自动回滚旧 slot。 +- [ ] 断网、错误 hash、下载中断不破坏当前可启动分区。 + +## 6. 双设备通话与好友 + +- [ ] 主叫等待、被叫响铃、单击接听、任一方单击挂断。 +- [ ] 未接、拒绝、忙、离线和通话中掉网。 +- [ ] 双向音频、AEC、延迟、丢包和长通话。 +- [ ] 两台设备同时三击,可在 30 秒内互相发现并保存。 +- [ ] 再次三击取消、自然超时、距离边界和重复碰一碰。 +- [ ] Friend mode 结束后 BLE 释放,WiFi/Realtime/音频恢复。 +- [ ] 离线碰一碰后重启联网,pending `friend_add` 成功补传。 +- [ ] 写入旧 `device.name` 和 `friends.count/f_N` 后升级可迁移;旧 key + 仍保留,回滚后旧固件仍可读取。 + +## 7. 激活与记忆 + +- [ ] `play_local_sequence` 顺序、指定 index、1 秒首间隔和 150ms 数字间隔。 +- [ ] 激活码每次播完 6 秒后重复。 +- [ ] TTS、按键、来电、闹钟和生命周期变化可停止重播。 +- [ ] `memory_sync` 后重启,ClientHello 回传相同缓存。 +- [ ] 带旧 `claude_mem` 数据升级后迁移成功,回滚仍可读旧分区。 + +## 8. 稳定性门禁 + +本轮已完成超过 110 秒的启动与多轮对话冒烟测试;以下仍是正式长稳门禁: + +- [ ] 先连续运行 24 小时,再做 72 小时门禁。 +- [ ] 保存启动后 5 秒、30 秒及之后每 5 分钟的 `RuntimeDiagnostics2` 日志。 +- [ ] 所有任务 `stack_free_bytes >= 512`。 +- [ ] 内部 heap/PSRAM 历史最小值在预热后不持续下降。 +- [ ] 任务数量、socket、播放队列和音频帧池不持续增长。 +- [ ] 无 panic、watchdog、brownout、死锁或 Speaking/Listening 卡死。 +- [ ] 循环执行对话、打断、BLE、好友、切网、闹钟和 OTA 失败恢复。 + +## 9. 当前已知待查项 + +- [x] 复刷确认连接后不再出现 `realtime_protocol_error id=3102`。根因已定位为 server + 删除首日内建闹钟时下发保留 ID `-203000`,协议和固件解析已修复并通过测试。 +- [x] 已补齐 8 帧固定容量、PSRAM 分配的异步下行 pre-roll,session 切换/取消 + 隔离和容量边界已有 host 测试,ESP-IDF 构建通过。 +- [ ] 复刷后重测首字听感、连续对话和打断,确认旧镜像的 71 条首帧丢弃归零。 +- [ ] 复刷后长按关机,确认 goodbye/close drain 完成后才停 WiFi,旧镜像末尾的 + 两条 transport error 归零。 +- [x] 复刷确认强 WiFi 下不再周期安装 ML307 UART,也不再出现 `UART driver malloc + error`。代码已改为只在 WiFi 离线/弱信号或手动切网时探测,并使用 512B RX、 + 无 TX 软件队列的轻量 AT 探测配置。 +- [x] `RuntimeDiagnostics2` 中 IDF 自有 `ipc0` 保持 484 bytes,应用任务仍 + 使用 512-byte 告警线,避免把已观测的 492 bytes 误报为 LOW。 +- [ ] 当前链接报告静态 IRAM 仅剩 1 byte;它不影响本次已生成镜像,但正式切换前 + 应回收 IRAM 余量,后续不得直接新增 `IRAM_ATTR` 代码。 + +## 10. 结果回填 + +完成后同时更新: + +1. [validation-matrix.md](validation-matrix.md) 中对应 ⏳。 +2. [refactoring-roadmap.md](refactoring-roadmap.md) 的阶段验收项。 +3. 失败项的日志、复现步骤、设备板本和结论。 + +只有阶段 1~13 的真机/外部联调门禁全部通过,才把对应阶段改为 ✅,并讨论 +正式切换;当前不自动 commit、merge 或部署。 diff --git a/docs/long-run-log-analysis-20260721.md b/docs/long-run-log-analysis-20260721.md new file mode 100644 index 0000000..1f4b910 --- /dev/null +++ b/docs/long-run-log-analysis-20260721.md @@ -0,0 +1,128 @@ +# Firmware 2 长时间运行日志分析(2026-07-21) + +## 1. 日志范围 + +分析文件共 1838 行、219462 bytes。第一条时间戳为 `1074316ms`,最后一条为 +`2752561ms`:文件可见窗口约 27 分 58 秒,设备累计 uptime 到 45 分 53 秒。 +因此这份文件是长稳运行的后半段,不包含上电启动阶段;启动结论仍以此前保存的 +5 秒、30 秒日志为准。 + +## 2. 总体结论 + +旧镜像在该窗口内没有出现以下故障: + +- Guru Meditation、abort、backtrace 或自动重启; +- watchdog、stack overflow、栈尾 watchpoint 或 brownout; +- WebSocket 断线、重连风暴、命令池耗尽或 TLS 失败; +- ML307 UART malloc error、`3102` 协议错误或任务 LOW 告警; +- 电池异常跳变或误触发低电量关机。 + +设备完成了持续对话、Idle 提示、WakeNet/AEC 策略切换和最终长按软关机。需要修复 +的有效问题有两个:TTS 播放 session 建立前丢开头音频,以及软关机停 WiFi 早于 +WebSocket goodbye/close 队列 drain。其余 51 条 warning 是预期扩展或打断后的 +迟到音频,应该保留计数但不应使用 warning 级别。 + +## 3. 量化结果 + +| 指标 | 结果 | 结论 | +|---|---:|---| +| 可见 TTS start | 48 | session 14~61 连续 | +| 可见 TTS stream end | 47 | session 49 被唤醒词主动打断,属于正常取消 | +| 开头 Opus 丢帧 | 71 帧 / 22 session | 真问题;单 session 最多 6 帧 | +| unsupported 扩展 | 48 条 | 当前 server 的 `stt`/`llm`/`game` 类元数据,无硬件动作 | +| 打断后迟到音频 | 3 帧 | session 49 取消后的网络尾包 | +| 关机 transport error | 2 条 | goodbye 写入与 WiFi stop 竞态 | +| 五分钟诊断快照 | 6 组 | 任务数始终 27 | +| 电池样本 | 165 个 | 4005~4019mV、91%~92%,稳定 | + +内部 heap 历史最小值从第二组开始保持 `1563 bytes`,没有继续下降;当前空闲值会 +随 WakeNet/AEC 模型装卸在约 9.9KB~34KB 间变化,最后为 14867 bytes。PSRAM +历史最小值稳定在约 7.37MB。最后一组关键任务栈余量如下: + +| 任务 | 剩余栈 bytes | +|---|---:| +| capture2 | 6912 | +| websocket2 | 1884 | +| friend_service2 | 2272 | +| alarm2 | 2684 | +| reminder2 | 1212 | +| power_service2 | 1176 | +| battery_sensor2 | 960 | +| sys_evt | 660 | +| ipc0 | 484(IDF 任务门限 384) | + +所有应用任务均高于 512-byte 门限,系统 IPC 任务高于其独立的 384-byte 门限。 +当前窗口没有堆、任务数或栈余量持续恶化的证据,但尚不能替代 24h/72h 门禁。 + +## 4. TTS 首帧竞态 + +典型时序是: + +```text +RealtimeProtocol 收到 tts:start + → 设置 active_tts_session + → 发布 TtsStarted 到 Application 队列 + → transport 继续收到二进制 Opus + → Application 尚未执行 BeginRemotePlayback + → PlaybackPipeline 因 session 未建立而拒绝帧 +``` + +这不是网络随机丢包。session 61 在 `tts_started` 前连续拒绝 6 帧,日志时间仅相隔 +约 26ms,说明 transport 已快速读取到服务端排队的数据,而控制事件仍在另一任务中 +等待执行。 + +修复方式:`EspAudioEngine` 启动时在 PSRAM 一次性分配 8 帧固定 pre-roll。 +`SubmitOpusFrame` 与 `BeginRemotePlayback` 共用独立互斥边界,保证“暂存首帧”和 +“建立 session 后按序冲刷”不会再次发生检查后竞态。新 session、取消和停止会清除 +或隔离旧帧;超过容量才拒绝,不做逐帧动态分配。 + +## 5. 日志分级 + +该次旧镜像中 server 的 `stt`、`llm` 和 `game` 消息均无需执行硬件动作,因此 +统一增加 `unsupported_message_count`,日志从 warning 调整为 debug。后续重构 +已正式解析 `stt.text` 并打印为对话输入,当前只有 `llm` 和 `game` 继续计入未知 +扩展;这不改变本节对旧日志 48 条记录的统计结论。 + +session 49 被 WakeNet 打断后,设备已取消播放并清除 active TTS;随后到达的 3 个 +二进制尾包也属于正常网络尾流,改为 debug。格式损坏的二进制包仍会产生协议错误, +不会被此次分级掩盖。 + +## 6. 软关机收敛竞态 + +长按后旧镜像依次将 `goodbye`、`close` 投递给 WebSocket worker,但 EffectRouter +立即同步停止 WiFi。worker 随后写 goodbye 时 socket 已被 WiFi 中止,因此出现: + +```text +transport_base: poll_write ... Software caused connection abort +transport_ws: Error transport_poll_write +``` + +设备最终仍正确停止传感器并进入无定时唤醒的 final light sleep,所以这是有序关闭 +质量问题,不是关机失败。 + +修复后 `Close` 与 goodbye 使用同一 transport FIFO,并最多等待 750ms 取得 worker +完成信号。正常链路按 `goodbye → WebSocket close → WiFi stop` 收敛;真实断网或 +黑洞超过门限时仍允许本地关机继续,不会无限等待。 + +## 7. 自动验证和待复验 + +已完成: + +- host tests 17/17 通过,包含 pre-roll 顺序、session 隔离和容量边界; +- ESP-IDF 5.4.3 / ESP32-S3 全量链接通过; +- 新镜像 `build/borla-firmware2.bin` 大小 `0x248c60`; +- 4MB 应用分区剩余 `0x1b73a0`(43%); +- SHA256:`558f7e8a8fdd5d0d9efde495f182f8d93e1d29cbd21e63d63f0260a5a0b40bb9`。 + +新镜像尚未烧录。复刷后按以下条件验收: + +1. 连续完成至少 10 轮 TTS,`downlink Opus dropped` 为 0,人工确认首字完整。 +2. TTS 播放中触发一次唤醒词打断,状态回到 Listening;迟到尾包不出现 warning。 +3. 默认日志中不再出现 `unsupported server message ignored` warning。 +4. 长按关机,server 收到 `goodbye`;串口不再出现上述两条 transport error。 +5. 仍出现 `close drain timed out` 时保存同一时刻的 WiFi、heap 和 transport 日志, + 作为弱网关闭专项,而不是延长为无界等待。 +6. 复刷通过后继续 24h,再做 72h;每 5 分钟保存 heap、PSRAM、任务数和栈快照。 + +验收总表见 [validation-matrix.md](validation-matrix.md),操作清单见 +[hardware-validation-checklist.md](hardware-validation-checklist.md)。 diff --git a/docs/migration-from-firmware.md b/docs/migration-from-firmware.md new file mode 100644 index 0000000..ccebc4c --- /dev/null +++ b/docs/migration-from-firmware.md @@ -0,0 +1,317 @@ +# firmware → firmware2 功能迁移清单 + +> 最后更新:2026-07-27 +> 对照基准:`firmware/`(只读参考) +> 本文档是「旧固件有、firmware2 有没有」的唯一清单。架构与模块边界见 +> [architecture.md](architecture.md),阶段验收见 +> [refactoring-roadmap.md](refactoring-roadmap.md)。 + +## 1. 状态标记 + +| 标记 | 含义 | +|---|---| +| ✅ 已通过 | 代码已迁移,且有自动化测试覆盖并在本机跑通 | +| 🧪 待真机验证 | 代码已迁移,逻辑部分有测试,但行为依赖硬件/服务器,必须真机复核 | +| 🚧 部分迁移 | 能力存在但与旧固件有明确差异,差异已在备注列写明 | +| ⛔ 不迁移 | 有意不迁移,理由见备注 | + +「已通过」只用于**不依赖硬件**的部分(纯逻辑、协议编解码、状态机)。任何 +需要喇叭、麦克风、WiFi/4G、BLE、NVS 或真实 server 的行为一律标 🧪。 + +## 2. 本轮新迁移的功能 + +下面 14 项是本轮从 `firmware/` 补齐到 `firmware2/` 的。 + +| # | 功能 | 旧固件位置 | firmware2 落点 | 状态 | +|---|---|---|---|---| +| M1 | OTA 响应下发 WebSocket 端点(url/token)并落 NVS | `ota.cc CheckVersion/ParseResponse` | `ota/ota_response_parser.cc`、`ota/ota_service.cc ApplyEndpoint`、`protocol/realtime_config.cc SaveEndpoint` | 🧪 待真机验证 | +| M2 | 端点归一化:过期 staging 域名回落 + `0.0.0.0` 替换为 OTA 主机 | `ota.cc IsKnownSavedEndpoint` | `ota/ota_endpoint.{h,cc}` | ✅ 已通过 | +| M3 | `ota_notify` 升级播报(auto/force/optional/文件未就绪) | `application.cc OnConnected` | `ota/ota_service.cc AnnounceUpgrade`、`protocol/protocol_message_builder.cc BuildOtaNotify` | 🧪 待真机验证 | +| M4 | 唤醒应答提示音「我在」 | `application.cc MAIN_EVENT_WAKE_WORD` | `core/state_reducer.cc AddWakeAcknowledgement` + `kPlayDetachedPrompt` effect | 🧪 待真机验证 | +| M5 | welcome 之后抑制一次唤醒应答 | `application.h suppress_next_wake_response_`(**旧固件只声明未接线**) | `core/state_reducer.cc`、`RuntimeState::suppress_wake_response` | 🧪 待真机验证 | +| M6 | 60 秒周期 status 上报(volume + battery) | `application.cc MAIN_EVENT_STATUS_TICK` | `protocol/realtime_protocol.cc SendStatusSnapshot` | 🧪 待真机验证 | +| M7 | 开机检测 4G physical switch 打开 → `net4g_boot_on` | `application.cc Net4gSwitchMonitorLoop` | `connectivity/dual_network_policy.cc OnModemPresence` | ✅ 已通过(策略)/ 🧪(提示音) | +| M8 | 运行中 4G 开关拨动 → `net4g_on` / `net4g_off`(关→开单次、开→关两次消抖) | 同上 | 同上 | ✅ 已通过(策略)/ 🧪(提示音) | +| M9 | WiFi 持续断开 30 秒且模组无供电 → `net4g_no_wifi`,120 秒限频 | `application.cc NotifyWifiLostModemAbsent` | `dual_network_policy.cc NotifyWifiLostWithoutModem` | ✅ 已通过(策略)/ 🧪(提示音) | +| M10 | TTS 中途断流 → 播错误提示音再回 listening | `application.cc PlayTtsInterruptedPromptThenListen` | `core/state_reducer.cc kPlaybackFailed` + `kRequestConnectionErrorPrompt` effect | ✅ 已通过(状态机)/ 🧪(音频) | +| M11 | 接受 `{"type":"llm","emotion":...}` | `application.cc OnIncomingJson` | `protocol/server_message_dispatcher.cc ParseLlm` | ✅ 已通过 | +| M12 | TraceCtx 关联 id(trace/session/request)+ 日志前缀 + OTA HTTP 头 | `trace_ctx.{h,cc}`、`ota.cc` | `diagnostics/trace_context.{h,cc}`,接入 `device_log_formatter`、`realtime_protocol`、`ota_service` | ✅ 已通过(id 逻辑)/ 🧪(串口与 server 联调) | +| M13 | 进入配网模式播报「请用小程序帮我连接网络」 | `wifi_board.cc EnterBleConfigMode` | `core/state_reducer.cc EnterProvisioning` + `kPlayDetachedPrompt` | ✅ 已通过(状态机)/ 🧪(音频) | +| M14 | 配网成功播报「配网成功啦」 | `wifi_board.cc SetWifiConfigCallback` | `AppEventType::kProvisioningWifiSaved` → `core/state_reducer.cc` | ✅ 已通过(状态机)/ 🧪(音频) | + +### 2.0 M13/M14 说明(首启无声问题的直接原因) + +真机首启(无 WiFi 凭据)时设备**完全不出声**:`boot.ogg` 刚起播就被 +`EnterProvisioning` 的 `kCancelPlayback` 掐掉,之后再没有任何音频。 +唯一的提示是 LED 慢闪——小朋友和家长都读不出这是"要配网"。 + +排查发现 `wifi_config`(26247 B)和 `wifi_success`(3576 B)两个 OGG +资源**早就编译进固件了**,`LocalPrompt::kProvisioning` / `kWifiSuccess` +枚举和 `embedded_prompt_catalog.cc` 的映射也都在,只是没有任何一行代码 +调用它们。属于纯粹的漏迁,不是设计取舍。 + +两处都用 `DetachedPrompt` 而不是 `Prompt`:`kProvisioning` 是排他 +lifecycle,`ValidateRuntimeState` 要求它期间 `playback == kIdle`, +走 `kLocalPromptStarted` 生命周期会破坏不变量。优先级取 `kSystem`, +这样它不会被同一次 transition 里刚执行的 `kCancelPlayback` 顺带清掉。 + +`kProvisioningWifiSaved` 是新增事件,由 `BleProvisioningService` 在凭据 +写入 NVS 成功后发出,**不改变 lifecycle**——离开配网模式仍然由小程序下发 +重启命令驱动,与旧固件一致。 + +### 2.1 M1/M2 说明 + +旧固件里 OTA 检查响应是**唯一**能把已出货设备指向另一台 server 的通道。 +firmware2 之前完全没有解析 `websocket` 块,端点只能来自 NVS 或编译期默认值, +运维无法远程改。现在: + +- `websocket.url` / `websocket.token` 与 `firmware` 块**互相独立**解析:即使 + 本次没有新固件(甚至完全没有 `firmware` 块),端点也会被采纳。这一点有 + 专门的测试覆盖(`ota_response_parser_test.cc` + `TestEndpointBlockSurvivesEveryFirmwareOutcome`),因为「版本不更新时把 + manifest 清零」的那条路径最容易把端点一起清掉。 +- 端点生效时机:`RealtimeProtocol` 在 `Initialize()` 时一次性读取 transport + 配置,因此新端点**下次重启后生效**,与旧固件一致(旧固件也是写 NVS 后靠 + 下次启动读取)。 + +### 2.2 M4/M5 说明 + +`kPlayDetachedPrompt` 是本次新增的 effect。唤醒应答必须在**已经进入 +listening 之后**出声:如果走普通的 `kPlayLocalPrompt` 生命周期, +`kLocalPromptStarted` 会把会话状态推到 `kSpeaking` 并关掉上行,孩子刚要说话 +就被静音。所以它走单独的引擎入口 `IAudioEngine::PlayDetachedPrompt`,不发 +任何控制面事件。 + +M5 需要注意:旧固件 `suppress_next_wake_response_` **只有读、没有写**, +即抑制逻辑从未真正生效。firmware2 按该成员的注释意图把它接线了(welcome +提示音开始播时置位,下一次唤醒消费)。这是**行为增强而非等价迁移**,如果 +产品上希望保持旧行为(每次唤醒都答「我在」,包括 welcome 之后紧接的那次), +删掉 `state_reducer.cc` 里 `kLocalPromptStarted` 分支的置位即可。 + +### 2.3 M7/M8/M9 说明 + +4G 开关直接切断模组供电,固件无 GPIO 可读,只能靠 AT 探测模组在不在。 + +与旧固件的**已知差异(有意)**:探测周期旧固件是 3 秒,firmware2 沿用既有的 +`kModemProbeIntervalMs = 30000`(30 秒)。原因是 firmware2 每次探测都会装卸 +UART 驱动,30 秒的占空比更安全;代价是拨动开关后最长 30 秒才播提示音。 +如果真机验收觉得太慢,改 `dual_network_transport.h` 的 +`kModemProbeIntervalMs` 一个常量即可,策略层不用动。 + +另一处差异:旧固件只在 WiFi 劣化时探测,firmware2 在 WiFi 为当前 bearer 时 +**无条件按周期探测**——否则 WiFi 一切正常时用户拨动开关永远不会被发现。 + +M9 的触发门槛与旧固件对齐:**WiFi 必须先连上过、再持续断开满 30 秒** +(`wifi_disconnect_failover_ms`,与自动切 4G 用的是同一个阈值)才播报。 +不能只看「当前 WiFi 不在线」——那样开机还没联上网就会误播,网络抖一下也会播。 + +### 2.4 M12 说明 + +已接入: +- 日志前缀由 `[MAC][时间]` 变为 `[MAC][时间][trace_id]` +- `ServerHello` 时采纳 server 的 session_id,并开一个新的 `ws-*` trace +- 每次 `listen:start`(一个新对话回合)刷新 `turn-*` trace +- OTA HTTP 请求带 `X-Borla-Trace-Id` / `X-Borla-Session-Id` / `X-Request-Id` + +**未接入**(旧固件有、本轮有意不做):`websocket_protocol.cc` 里的 +`SendTraceMarkerLocked` —— 往 WS 里额外发 trace marker 文本帧。那是一套独立 +的埋点协议,需要与 server 同步契约后再做,单独做设备端没有意义。 + +## 3. 早已迁移、本轮复核确认的功能 + +这些在本轮开始前就已存在于 firmware2,本轮只做了对照复核。 + +| 功能 | firmware2 落点 | 状态 | +|---|---|---| +| 控制面状态机 / 事件循环 | `core/state_reducer.cc`、`app/application.cc` | ✅ 已通过 | +| WebSocket v3 二进制音频(批量/整包校验/背压) | `protocol/binary_audio_protocol.cc` | ✅ 已通过 | +| ServerHello 解析与校验 | `protocol/server_message_dispatcher.cc` | ✅ 已通过 | +| tts start/stop/sentence_start/sentence_end | 同上 | ✅ 已通过 | +| stt 文本 | 同上 | ✅ 已通过 | +| control: volume / wake_word / barge_in / light_sleep | 同上 | ✅ 已通过 | +| control: led alert(红灯临时告警) | 同上 | ✅ 已通过 | +| play_local(含 post_action / block_reconnect / index) | 同上 | ✅ 已通过 | +| play_local_sequence(激活码朗读) | 同上 + `activation/` | ✅ 已通过 | +| set_timer / cancel_timer(提醒) | `schedule/reminder_*.cc` | ✅ 已通过 | +| set_alarm / delete_alarm / sync_alarms / alarm_config | `schedule/alarm_*.cc` | ✅ 已通过 | +| 内置「第一天睡前」闹钟 | `schedule/alarm_schedule.cc` | ✅ 已通过 | +| call ring/invite/connected/ended/missed | `protocol/` + `core/state_reducer.cc` | 🧪 待真机验证(需双设备) | +| memory_sync + 旧 `claude_mem` 分区迁移 | `memory/memory_cache.cc` | 🧪 待真机验证 | +| wifi_config(server 要求进配网) | `protocol/` + `provisioning/` | 🧪 待真机验证 | +| BLE 配网 FF01~FF07 + MTU 分包 + WiFi 预扫描 | `provisioning/`、`platform/borla_s3/ble_provisioning_gatt.cc` | 🧪 待真机验证 | +| 好友碰一碰(BLE 扫描/广播/候选选择/NVS/重连补传) | `friend/`、`platform/borla_s3/ble_friend_exchange.cc` | 🧪 待真机验证(需双设备) | +| 旧 `device`/`friends` NVS 迁移到 `friend_v2` | `friend/friend_store.cc` | 🧪 待真机验证 | +| 按键 1/2/3/4 击 + 长按 | `platform/borla_s3/button_input.cc` + 归约器 | 🧪 待真机验证 | +| 三击/四击动作可由 ServerHello 配置 | `configuration/remote_behavior_config.cc` | ✅ 已通过 | +| 连接异常提示音可由 ServerHello 配置 | 同上 | ✅ 已通过 | +| 五路电容触摸(基线/阈值/消抖/卡死兜底) | `sensor/touch_channel.cc` | ✅ 已通过(算法)/ 🧪(硬件) | +| BMI270 IMU + Gravity 事件 | `sensor/imu_processor.cc` | ✅ 已通过(算法)/ 🧪(硬件) | +| 电池估算(放电曲线/充电判定/无效采样门禁) | `sensor/battery_estimator.cc` | ✅ 已通过(算法)/ 🧪(硬件) | +| 低电量 20% 提醒 / 10% 关机 | `power/power_service.cc` + 归约器 | 🧪 待真机验证 | +| IdleWatchdog(idle_check → idle_goodbye → 轻睡眠) | `power/idle_service.cc` | 🧪 待真机验证 | +| 长按关机 / soft-off / 定时唤醒 | `power/power_service.cc`、`platform/borla_s3/borla_s3_platform.cc` | 🧪 待真机验证 | +| WiFi 连接管理(SSID 轮换/指数退避/诊断) | `connectivity/connectivity_policy.cc` | ✅ 已通过 | +| ML307 UART/AT/PPP | `platform/borla_s3/ml307_transport.cc` | 🧪 待真机验证(需 SIM) | +| WiFi/4G 自动切换 + 四击手动切网 | `connectivity/dual_network_policy.cc` | ✅ 已通过(策略)/ 🧪(真机) | +| WakeNet 唤醒词 | `audio/wake_word_detector.cc` | 🧪 待真机验证 | +| AEC / NS / AGC / 能量 VAD | `audio/voice_dsp.cc`、`voice_activity_detector.cc` | ✅ 已通过(VAD)/ 🧪(声学) | +| 打断:本地唤醒词硬打断 + server 两阶段裁决 | 归约器 + `protocol/` | ✅ 已通过(状态机)/ 🧪(时延与误取消率) | +| 45 个内置提示音(含 snore_light) | `assets/prompts/`、`audio/embedded_prompt_catalog.cc` | ✅ 已通过(资源齐全)/ 🧪(播放) | +| OTA A/B 分区 + SHA256 + 回滚确认 | `ota/ota_service.cc` | ✅ 已通过(解析)/ 🧪(真实链路) | +| heap / PSRAM / 任务栈周期诊断 | `diagnostics/runtime_diagnostics_service.cc` | 🧪 待真机验证 | +| 日志带 MAC + 校时后本地时间 | `diagnostics/device_log_formatter.cc` | 🧪 待真机验证 | + +## 4. 有意不迁移 + +| 功能 | 旧固件位置 | 不迁移理由 | +|---|---|---| +| WiFi AP 配网(192.168.4.1) | `components/esp-wifi-connect/wifi_configuration_ap.cc` | 旧固件自己已注明「kept for fallback, **not used by default**」,默认路径是 BLE 配网。firmware2 只实现 BLE 配网。若产品仍需要 AP 兜底,这是一项独立需求 | +| `snore_light` 用 82Hz 方波循环合成 | `application.cc play_local` | firmware2 已有真实的 `snore_light.ogg` 资源,音质更好,无需保留合成音 | +| `kMinListeningDurationMs`(listening 至少 5 秒才允许切 speaking) | `application.cc SetDeviceState` | 这是针对「服务器抢答」的客户端兜底。firmware2 用的是 server 唯一裁决的两阶段插话协议(candidate → rejected/confirmed),再加一个固定 5 秒下限会与该协议打架 | +| `speaking_delay_timer_` / `tts_stream_idle_timer_` / `tts_timeout_timer_` 三个 TTS 看门狗 | `application.cc` | firmware2 用 `PlaybackController` 的 producer-start / stalled 超时统一覆盖,加上协议层心跳超时。M10 已把「断流后给孩子一个错误提示音」这条用户可感知的行为补上 | +| WS trace marker 文本帧 | `websocket_protocol.cc SendTraceMarkerLocked` | 需要先与 server 敲定契约,见 §2.4 | +| OTA 完成后播「升级成功,正在重启」 | `ota.cc StartUpgrade` | firmware2 的 `kUpgradeRequested` 会确定性关闭 realtime 通道,刷写时已无通道可播报。server 从重启后 hello 里的新版本号即可得知结果 | + +## 5. 与旧固件的已知行为差异 + +这些不是缺失,是 firmware2 架构带来的**有意**差异,真机验收时不要当 bug。 + +1. **4G 开关探测周期 30 秒**(旧 3 秒)。见 §2.3。 +2. **OTA 端点次启动生效**。见 §2.1。 +3. **升级成功播报缺失**。见 §4。 +4. **低电量 <10% 的开机拦截时机不同**:旧固件在 `Start()` 里同步读电池、 + 低于 10% 直接播提示音后关机、不继续启动;firmware2 由 `PowerService` + 轮询发 `kCriticalBattery`,归约器再走 `BeginSoftOffPrompt`。最终行为一致, + 但 firmware2 会先完成开机提示音和联网。 +5. **`listen` 消息固定 `mode:"auto"`**:旧固件有 auto/manual/realtime 三种 + `ListeningMode`,实际只用 auto。firmware2 只发 auto。 +6. **唤醒应答的抑制逻辑真正生效**。见 §2.2。 +7. **配网期释放 WiFi 驱动的方式不同**(重要,见下)。 + +### 5.1 配网模式下的内部 RAM 预算 + +ESP32-S3 上内部 RAM(`MALLOC_CAP_INTERNAL`)是全片最紧的资源,配网是唯一 +需要 BT controller 和 WiFi driver **同时在场**的场景,实测占用: + +| 占用方 | 内部 RAM | +|---|---| +| BT controller + NimBLE host | ~53 KB | +| WiFi driver(`esp_wifi_init`) | ~36.5 KB | + +旧固件的做法是 `DeinitWakeWord()` + `esp_wifi_stop()`:卸掉 WakeNet 模型 +腾地方,WiFi 驱动只停不卸,所以配网回调里 `esp_wifi_start()` 很便宜。 + +firmware2 不能照搬——它的 WakeNet 是**懒加载**的(`VoiceFrontend::Initialize` +不加载模型,只有 `WakeRequired(policy)` 为真时才 `wake_word_.Initialize()`), +而配网期 policy 恒为 `kOff`,模型压根没进内存,没有对应的 `DeinitWakeWord` +可调。于是改为 `IWifiTransport::ReleaseDriver()`(`esp_wifi_deinit`),实测 +放出 36484 字节,BLE 才能起来。 + +代价是 `BleProvisioningService::HandleConnect` 必须重新 `esp_wifi_init()`, +而那时 BT controller 已经占住 53 KB。为此把 `VoiceFrontend` 的 AEC 参考帧 +环形缓冲(15360 B)和唤醒词累加器(8192 B)从 `CompositionRoot` 的 `.bss` +移到 PSRAM,共腾出 23552 字节(`app_main::root` 164600 → 141048)。 + +推算的配网期余量(真机待确认): + +``` +BLE 启动前 73611 + 23552 = 97163 +BLE 起来后 20459 + 23552 = 44011 +esp_wifi_init 需 ~36484 → 余量 ~7.5 KB +``` + +余量偏薄,因此 `HandleConnect` 里加了 `internal RAM before WiFi retry` +日志,`wifi_.Start()` 失败时单独报错,一旦不够可以直接从串口读到数字。 + +> 后续若还需要腾内部 RAM,下一批候选是 `.bss` 里的连接类任务栈 +> (`dual_network2` 8 KB 实测峰值 908 B、`connectivity2` 8 KB 峰值 2484 B), +> 但这两个数字是**联网前**采的,收缩前必须先拿到联网后的高水位。 + +## 6. 测试情况 + +### 6.1 本机已跑通(19/19) + +```bash +cmake -S firmware2/host_tests -B build-host +cmake --build build-host +ctest --test-dir build-host --output-on-failure +``` + +| 测试 | 覆盖 | 本轮新增/修改 | +|---|---|---| +| `state_reducer_test` | 状态机全部分支 | 新增 M4/M5/M10 用例 | +| `effect_router_test` | Effect → Port 路由 | 新增 `kPlayDetachedPrompt`、`kRequestConnectionErrorPrompt` | +| `dual_network_policy_test` | 双网策略 | 新增 M7/M8/M9 用例 | +| `realtime_codec_test` | 协议编解码 | 新增 `llm`、`ota_notify`、status volume 用例 | +| `ota_response_parser_test` | OTA manifest | 新增端点块跨路径存活用例 | +| `ota_endpoint_test` | **新文件** — 端点归一化规则 | 全新 | +| `trace_context_test` | **新文件** — 关联 id 生成 | 全新 | +| 其余 12 个 | 播放、连接、VAD、传感器、日程、BLE 编解码等 | 未改动,回归通过 | + +> 本机没有装 libcjson,上面 19 个测试是用 `clang++` 直接编译跑的,其中 3 个 +> 依赖 cJSON 的测试链接了一份 pinned 的上游 cJSON(v1.7.18)。CI/开发机上按 +> `README.md` 的 cmake 流程跑即可(cmake 现已由 ESP-IDF 装在 +> `~/.espressif/tools/cmake`),`host_tests/CMakeLists.txt` 已登记两个新测试。 + +### 6.2 ESP-IDF 全量构建:已通过 + +本机已安装 ESP-IDF **v5.4.3**(`~/esp/esp-idf`,工具链在 `~/.espressif`), +构建结果: + +``` +$ idf.py set-target esp32s3 && idf.py build +... +Project build complete. +borla-firmware2.bin binary size 0x24c620 bytes. +Smallest app partition is 0x400000 bytes. 0x1b39e0 bytes (43%) free. +``` + +- 错误 **0**、警告 **0**(含 `-Wframe-larger-than=1024 -Werror` 的 + `server_message_dispatcher.cc` 门禁) +- 产物:`build/borla-firmware2.bin`(2.3 MB)、`bootloader.bin`、 + `partition-table.bin`、`srmodels.bin`(298 KB) +- 自定义唤醒词模型注入生效:`build/srmodels/` 下有 + `wn9l_ni3hao3bo1le4/` 与 `.borla_custom_done`,`srmodels.bin` 内可查到 + `wakenet9l_tts3h12_Ni3Hao3Bo1Le4_3_0.613_0.621` +- 已额外 `touch` 全部 `main/**/*.cc` 强制重编一次,排除增量缓存假阳性 + +环境说明:ESP-IDF 在 macOS 上不自带 cmake/ninja,本机用 +`idf_tools.py install cmake ninja` 装的(cmake 3.30.2 / ninja 1.12.1)。 +Python 用的是 3.14.5,requirements 全部有 cp314 wheel,无需降级。 + +复现命令: + +```bash +. ~/esp/esp-idf/export.sh +cd firmware2 && idf.py set-target esp32s3 && idf.py build +``` + +### 6.3 真机验收清单(需要你来做) + +按依赖顺序: + +| # | 场景 | 期望 | 关联项 | +|---|---|---|---| +| 1 | 上电开机 | 串口日志前缀含 `[MAC][时间][trace_id]` | M12 | +| 2 | 说唤醒词(idle 状态) | 听到「我在」,且紧接着能正常说话(不被静音) | M4 | +| 3 | 绑定后首次 welcome 播完,立刻说唤醒词 | **不**播「我在」,直接进入监听 | M5 | +| 4 | 连接 60 秒后看 server 日志 | 每 60 秒收到一条 `status`,含 `volume` 与 `battery` | M6 | +| 5 | WiFi 模式下拨动 4G 开关到 ON | ≤30 秒内播 `net4g_on` | M8 | +| 6 | 再拨回 OFF | ≤60 秒内播 `net4g_off`(两次探测消抖) | M8 | +| 7 | 带 4G 开关 ON 开机(走 WiFi) | 播 `net4g_boot_on` | M7 | +| 8 | 联网后拔掉路由器电源、4G 开关 OFF | 断开满 30 秒后播 `net4g_no_wifi`,且 2 分钟内不重复;开机阶段(还没连上过 WiFi)不应播 | M9 | +| 9 | TTS 播报中途拔网线/杀 server | 播 server_error 提示音后回到监听(不是静默卡住) | M10 | +| 10 | OTA 服务端返回带 `websocket.url` 的响应 | NVS `websocket/url` 被更新,重启后连到新端点 | M1 | +| 11 | OTA 服务端返回 `0.0.0.0` 端点 | 自动替换为 OTA 主机 | M2 | +| 12 | OTA 触发 auto 升级 | 先听到「即将开始升级」,约 8 秒后开始下载 | M3 | +| 13 | OTA 触发 optional | 只听到询问,不升级 | M3 | +| 14 | server 发 `{"type":"llm","emotion":"happy"}` | 日志出现 `direction=output emotion=happy`,不再是 unsupported | M11 | +| 15 | OTA 请求抓包 / 看 server 日志 | 请求头含 `X-Borla-Trace-Id`、`X-Request-Id` | M12 | +| 16 | 擦掉 NVS 后首启(无 WiFi 凭据) | 听到「请用小程序帮我连接网络」,LED 慢闪,`BLE provisioning ready name=Borla-XXXX` | M13 | +| 17 | 小程序连上设备、下发正确 WiFi 密码 | 听到「配网成功啦」,小程序收到成功回执 | M14 | +| 18 | 同上,看串口 `internal RAM before WiFi retry` | `free` 应 ≳ 44000;若出现 `WiFi driver restart failed` 说明内部 RAM 仍不够 | §5.1 | +| 19 | 小程序下发错误密码 | 小程序收到 `password_wrong`,设备不重启、继续广播 | §5.1 | + +§3 里标 🧪 的既有功能仍按 +[hardware-validation-checklist.md](hardware-validation-checklist.md) 走, +本文档不重复。 diff --git a/docs/ota.md b/docs/ota.md new file mode 100644 index 0000000..a359d7e --- /dev/null +++ b/docs/ota.md @@ -0,0 +1,57 @@ +# OTA 子系统 + +> 实现阶段:阶段 10 +> 当前状态:代码、解析测试和 ESP-IDF 构建已完成;真实服务与 A/B 回滚待验收 + +## 1. 安全边界 + +`OtaService` 是 OTA 的唯一执行者。状态机只决定是否进入升级生命周期, +`EffectRouter` 只调用 service;HTTP 下载、分区写入、SHA256 和 boot partition +切换都不会散落在 Application 或 Board 中。 + +默认只接受 HTTPS,使用 ESP-IDF CA bundle 校验证书。开发环境如必须访问 HTTP, +需要显式启用 `CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP`,生产配置不得开启。 + +## 2. 流程 + +1. WiFi 获得 IP 后异步调用版本检查接口,最多重试 3 次。 +2. 严格解析 `firmware.version/url/size/sha256/auto_update/force_upgrade`。 +3. 只有版本高于当前固件才形成有效 manifest。 +4. 策略映射为 optional、automatic 或 forced;automatic/forced 自动发布 + `UpgradeRequested`。 +5. 状态机进入 `Upgrading`,关闭实时通道和音频会话,但保留 IP 连接用于下载。 +6. 流式写入 `esp_ota_get_next_update_partition()`,不将固件整体放入内存。 +7. 同时校验下载字节数和 SHA256,任一不符就 abort,当前运行分区保持不变。 +8. `esp_ota_end()` 验证镜像后才设置新的 boot partition,并重启。 +9. 新镜像启动完成平台、网络、协议、传感器和业务服务装配后,调用 + `esp_ota_mark_app_valid_cancel_rollback()`。 +10. 如果 pending-verify 镜像初始化失败,标记无效并回滚重启。 + +Optional manifest 会保留在 service 诊断快照中,但当前设备侧没有“确认升级”的本地 +UI;后续控制面可调用同一 `StartUpgrade` 入口,不需要复制下载实现。 + +## 3. 配置 + +- `CONFIG_BORLA_OTA_URL`:版本检查 URL,默认生产 HTTPS 地址。 +- `CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP`:只供隔离开发环境使用,默认关闭。 +- `CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC`:TLS 握手和 record buffer 使用 PSRAM, + 与 Realtime 共用策略,避免并发检查版本时耗尽内部连续堆。 +- A/B 分区:两个 4 MiB app slot,bootloader rollback 已启用。 + +## 4. 已验证与待验证 + +已完成: + +- manifest 必填字段、版本比较、SHA256 格式、策略和非 HTTPS 拒绝的 host 测试。 +- 状态机升级互斥行为测试。 +- 13/13 host tests。 +- ESP-IDF 5.4.3 全量构建,镜像 `0x227ab0`,4 MiB app 分区剩余约 46%。 + +待外部环境/真机验证: + +- backend/server/admin 完整版本检查链路。 +- 真实 HTTPS 下载、断网续错、错误 size 和错误 SHA256。 +- 写入备用分区后启动新镜像。 +- 故意制造启动自检失败并确认自动回滚。 +- forced/automatic/optional 三种后台配置。 +- 升级期间对话、来电、按键和掉电行为。 diff --git a/docs/playback-system.md b/docs/playback-system.md new file mode 100644 index 0000000..4216fc1 --- /dev/null +++ b/docs/playback-system.md @@ -0,0 +1,186 @@ +# Firmware 2 统一播放系统 + +> 状态:代码、正式提示音资源与自动化验证已完成,ESP32-S3 实机播放验收未完成。 +> 协议基线:仓库根目录 `protocols/websocket_protocol.md`。 +> 音频格式:下行 24kHz、16bit、单声道、Opus、60ms/帧。 + +## 1. 设计目标 + +所有能发声的功能最终都通过同一个播放系统: + +```text +远程 TTS / 音乐 ──Opus──┐ + ├── PlaybackSession +本地提示 / 闹钟 ──PCM───┘ │ + ▼ + PlaybackController + │ + 固定容量帧队列 + │ + ▼ + 唯一 speaker-owner task + │ + Opus 解码 + │ + ▼ + ES8311 / I2S0 / PA +``` + +禁止其他模块直接调用 I2S 或 codec 写接口。`PlaybackPipeline` 是扬声器数据面的 +唯一入口,`PlaybackController` 是播放所有权的唯一决策者。 + +## 2. 模块职责 + +| 模块 | 职责 | 不负责 | +|---|---|---| +| `EspAudioEngine` | 实现 `IAudioEngine`,组合播放相关对象 | 协议解析、业务状态决策 | +| `PlaybackController` | session、优先级、抢占、取消、完成和指标 | FreeRTOS、I2S、Opus | +| `PlaybackPipeline` | 固定帧池、队列、唯一输出任务、超时和事件 | 决定产品播放优先级 | +| `OpusFrameDecoder` | 24kHz 单声道 Opus 解码与状态重置 | session 生命周期 | +| `LocalPromptPlayer` | 异步生产嵌入式 Opus,缺失时生成回退音 | 绕过 session 直接播音 | +| `Es8311AudioOutput` | I2C/I2S/codec/功放和软件音量 | 播放仲裁 | + +## 3. 会话与优先级 + +每次播放必须有设备本地的 `PlaybackSessionId`。当前 WebSocket `tts` 消息不包含 +播放 session 字段,因此阶段 4 的协议 adapter 在收到 `tts:start` 时分配低半区 +本地 ID,并在对应 `tts:stop` 时复用它;ServerHello 的 UUID 是连接会话,不能 +混作播放 ID。本地提示音由播放系统分配 `0x80000000` 以上的 ID,从命名空间上 +避免冲突。播放控制器会拒绝 0 或落入本地区间的远程播放 ID,防止错误 adapter +破坏该隔离条件。 + +当前优先级从低到高为: + +```text +Background < Conversation < LocalPrompt < System < Alarm < Call +``` + +规则如下: + +1. 没有活动会话时,新会话获得扬声器。 +2. 新会话优先级低于当前会话时拒绝。 +3. 新会话优先级等于或高于当前会话时抢占当前会话。 +4. 重复请求同一远程 ID 且来源相同视为幂等。 +5. 每次新会话都获得新的 generation,用于追踪同一控制器上的播放轮次。数据面 + 的强隔离键是启动期间不复用的 session ID;producer 必须始终携带创建时获得的 + ID,因此被抢占的旧 producer 无法把帧计入新会话。 + +## 4. 会话状态 + +```mermaid +stateDiagram-v2 + [*] --> Pending: StartSession + Pending --> Streaming: first frame queued + Pending --> Draining: EndInput before first frame + Streaming --> Draining: EndInput + Draining --> Completed: producer started and queue/in-flight both zero + Pending --> Failed: producer-start timeout + Streaming --> Failed: stalled/write/decode failure + Draining --> Failed: stalled/write/decode failure + Pending --> Cancelled: cancel/preempt + Streaming --> Cancelled: cancel/preempt + Draining --> Cancelled: cancel/preempt +``` + +`EndInput` 只表示 producer 不再产生新帧,不等于扬声器已经播放完。只有满足以下 +全部条件,管线才发布 `PlaybackDrained`: + +- producer 至少成功提交过一帧; +- 已收到 `EndInput`; +- 排队帧数为 0; +- 正在写 I2S 的帧数为 0。 + +这个约束防止异步 producer 还没提交首帧时被误判成播放完成。 + +## 5. 并发与取消保证 + +- 只有 `speaker-owner` 任务调用 `IAudioOutput::Write`。 +- 控制器和输出所有权由同一互斥边界保护。 +- 抢占会清空尚未消费的旧帧并重置 Opus decoder。 +- 如果旧帧正在同步写 I2S,抢占最多等待当前 60ms 帧完成。 +- 抢占返回后,旧 session 的待处理帧和后续提交帧都会被拒绝。 +- 抢占会发布 `PlaybackPreempted(old, replacement)`;如果旧 ID 仍是控制面的当前 + 对话播放,归约器会退出 Speaking 并请求服务端中止旧 TTS。 +- 过期 session 的 `EndInput`、`PlaybackDrained` 和 `PlaybackFailed` 不会改变 + 新 session 的运行状态。 + +## 6. 内存与实时约束 + +| 资源 | 配置 | +|---|---| +| 帧槽数量 | 48 | +| 下行 pre-roll | 8 个 Opus 帧,PSRAM 固定容量 | +| 每帧 PCM 上限 | 1440 samples / 2880 bytes | +| Opus 解码缓冲 | 1440 samples | +| 分配位置 | PSRAM | +| 队列实现 | 静态 FreeRTOS queue | +| 输出任务 | Core 1、priority 5、36KB PSRAM stack | +| producer 首帧超时 | 2s | +| 播放停滞超时 | 10s | + +帧池、解码缓冲和任务栈只在初始化/启动时分配。播放栈使用 ESP-IDF +`xTaskCreatePinnedToCoreWithCaps` 放入 PSRAM,避免 Opus 解码、播放 reference 和 +I2S 同步写入的深调用链挤占内部 DRAM;提交、解码和播放的稳态路径不进行逐帧 +动态内存分配。 + +WebSocket 任务可在 `TtsStarted` 事件尚排队时先收到二进制帧。`EspAudioEngine` +用独立互斥边界把“检查当前 session/暂存首帧”和“开始 session/冲刷首帧”串行化, +消除检查后启动造成的二次竞态。pre-roll 对象在启动时一次性分配到 PSRAM,最多 +保留 8 帧;新 session、取消和停止都会隔离或清除旧帧。 + +## 7. 控制面边界 + +音频帧不进入 `AppEventQueue`。控制面只传递生命周期事件: + +```text +TtsStarted(session) + → BeginRemotePlayback(session) + +Opus data frame + → IAudioEngine::SubmitOpusFrame(session, data) + +TtsStreamEnded(session) + → EndPlaybackInput(session) + +queue + I2S fully drained + → PlaybackDrained(session) +``` + +阶段 4 的 WebSocket adapter 负责把控制消息转换为事件,阶段 5 的数据面负责把 +二进制 Opus 帧送入 `SubmitOpusFrame`。 + +## 8. 可观测性 + +`PlaybackMetrics` 当前记录: + +- 启动、完成、取消、失败和抢占的会话数; +- 低优先级拒绝数; +- 过期帧、排队帧、写入帧和丢帧数; +- producer 首帧超时和播放停滞超时; +- 队列高水位。 + +阶段 13 将这些内部指标接入统一诊断输出;producer 首次填满固定帧池属于正常 +节流并自动重试,已降为 debug `producer pacing`,不再作为 warning 误报。当前可通过 +`EspAudioEngine::PlaybackMetricsSnapshot()` 获取快照。 + +## 9. 本地提示音资源 + +`firmware2/assets/prompts` 当前包含 45 个 Ogg/Opus 文件,其中包含睡眠场景 +使用的 `snore_light`。构建生成器会拒绝非 +Opus、损坏或无法分类的资源,并把音频 packet 生成只读 packed frame 数据。 +`LocalPromptPlayer` 使用独立 producer task 和播放 session 提交这些帧;帧池暂满 +时执行有界退避,session 被抢占后立即退出。程序化音阶只在对应资源不存在时 +作为安全回退。 + +单条本地提示音开始时上报 `play_local:start`,只有播放队列与 I2S 都 drain 后 +才上报 `play_local:done`。高优先级业务抢占或播放失败也会终结该生命周期,防止 +server 永久保留“设备正在本地播放”的锁。序列播放使用自己的完成语义,不发送 +单条 start/done。 + +## 10. 未完成项 + +- 尚未在目标板验证 ES8311、I2S、GPIO40 功放、音量和底噪。 +- 麦克风 capture、上行 Opus、AEC、VAD、barge-in、闹钟和通话已在后续阶段 + 接入,但仍需和本播放系统一起做真机声学与抢占回归。 + +真机播放项目完成前,路线图中的阶段 2 保持“进行中”。 diff --git a/docs/realtime-control-plane.md b/docs/realtime-control-plane.md new file mode 100644 index 0000000..3568735 --- /dev/null +++ b/docs/realtime-control-plane.md @@ -0,0 +1,159 @@ +# Firmware 2 WebSocket v3 控制面 + +> 实现阶段:重构路线图阶段 4 +> 当前状态:基础 WiFi/TLS/hello 和多轮对话真机联调已通过;断网门限、完整远程 +> 控制和长稳仍待验收 + +## 1. 边界 + +本模块负责 WebSocket/TLS 生命周期、v3 握手、JSON 控制消息、心跳和协议诊断。 +二进制音频帧只通过 `IRealtimeBinarySink` 进入阶段 5 数据面,不进入 +`AppEventQueue`,也不在 transport 中解码。 + +```text +Application ──effect──> RealtimeProtocol + ├── ProtocolMessageBuilder + ├── ServerMessageDispatcher + ├── ReconnectBackoff + └── EspWebsocketTransport ──> TCP/TLS + │ + └── callback ──> RealtimeProtocol + │ + └── AppEvent +``` + +## 2. 连接和握手 + +1. 网络 DHCP 成功后,控制面请求打开实时通道。 +2. transport 的静态任务解析 `ws://`/`wss://` URI,并完成 TCP/TLS 和 + WebSocket upgrade。 +3. 请求头携带 `Device-Id`、`Protocol-Version`、`Firmware-Version` 和可选 + Bearer token;token 不进入日志。 +4. 连接建立后发送 ClientHello。 +5. 只有校验通过的 ServerHello 才发布 `RealtimeConnected`。 +6. ServerHello 必须是 v3/WebSocket,且下行参数必须是 24kHz、单声道、 + Opus、60ms。 +7. ServerHello 可覆盖三击/四击动作和连接异常本地提示;合法值写入 NVS, + 缺失字段保留上次配置,非法值拒绝更新。 +8. hello 15 秒超时,JSON ping 每 30 秒发送,90 秒无任何下行即主动关闭。 +9. 非主动断线使用 1~30 秒指数退避并带 ±20% 抖动。 + +默认地址为 `wss://borlaws.lkall.com/v1/ws`。NVS namespace `websocket` 可用 +`url`、`token`、`version` 覆盖,版本会强制归一为 v3。 + +## 3. 消息处理 + +`ServerMessageDispatcher` 将 JSON 解析为固定大小 `ServerCommand`。已支持: + +- hello、ping、pong +- stt 最终识别文本(只写串口对话诊断,不改变运行状态) +- tts start/stop/sentence_start/sentence_end +- barge_in candidate/rejected/confirmed 两阶段自然插话裁决 +- play_local、显式 index、sequence 与 shutdown post-action/legacy fallback +- memory_sync +- timer、alarm 和 alarm_config +- call ring/invite/connected/ended/missed +- wifi_config +- control:音量、唤醒词、TTS 插话、轻睡眠和临时安全红灯 +- error + +设备上行 builder 已支持: + +- hello +- listen start/stop +- abort +- ping/pong +- status、alarm_fired、call accept/hangup 和 friend_add +- 三击/四击 `button` 遥测 +- 单条本地提示音 `play_local` start/done 生命周期 +- 配网、轻睡眠和关机前的 `goodbye` 优雅关闭 + +未知的未来消息被计数并忽略;格式错误会发布协议错误。等待 ServerHello 时收到 +非法消息会关闭连接,避免在未协商状态下继续工作。 + +当前 server 的 `stt` 下行会解析 `text` 并以 `ConversationText2 direction=input` +写入串口;`tts sentence_start` 的 `text` 以 `direction=output` 写入串口。两者均不 +改变设备状态,也不驱动播放时序。`llm` 和 `game` 仍作为未知扩展计数后忽略。 +单条 `play_local` 在开始和真正 drain 后分别回传 start/done;server 的睡眠 +场景依赖 `snore_light` 的 done 解锁后续 `light_sleep` 控制。 + +## 4. 并发和资源 + +| 资源 | 配置 | +|---|---| +| transport 任务 | 静态任务,优先级 4 | +| transport 命令队列 | 静态 10 个 `uint16_t` 索引 | +| transport 命令池 | 10 × 2574 bytes,PSRAM,启动时一次分配 | +| 遥测槽 | 2 × 2574 bytes,PSRAM,独立 latest-wins 双缓冲 | +| 单条控制消息 | 最大 2574 字节;ClientHello 缓存超限时回退为无缓存 | +| 下行消息缓冲 | PSRAM 8192 字节 | +| 读取分片 | 2048 字节 | +| WebSocket transport 任务栈 | 12288 bytes,内部 RAM | +| 下行 `ServerCommand` | 单个常驻对象,PSRAM,就地解析 | +| dispatcher 函数栈帧 | 编译门禁最大 1024 bytes;当前机器码最大 176 bytes,ServerHello 64 bytes | +| 生命周期 timer | 1 秒周期;ping 使用静态 JSON,pong 缓冲 128 bytes | +| mbedTLS 动态内存 | PSRAM(16KB 输入、4KB 输出及握手对象) | + +Application 调用 Open/Send 时只投递命令,不执行 DNS、TLS 或阻塞 socket 操作。 +Close 会投递到同一 transport 队列,并有界等待最多 750ms 确认此前的 goodbye、 +控制消息和 close 已由 I/O worker 顺序处理;Application 自身仍不执行 socket I/O。 +这样软关机随后停止 WiFi 时不会抢先中止已排队的 goodbye。命令 payload 不再作为 +大型局部变量或静态内部 DRAM 队列项,而是从 PSRAM +固定池取得槽位,发送完成后归还。二进制流量最多占用 8 个槽,始终为控制消息 +保留 2 个;10Hz 传感器文本走独立的双槽 latest-wins 通道,拥塞时覆盖旧遥测而不 +挤占控制/音频。每轮最多发送 2 条命令就回到 socket 读取,成功读取后让出 1 个 +tick,使 Application 能及时处理 `tts_started` 等生命周期事件。公共 `esp_timer` +回调不会嵌套约 5KB 的临时对象,约 3.6KB 的 `ServerCommand` 也不再放在协议回调 +栈上。`CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC` 明确把 TLS 分配放入 PSRAM,避免内部 +heap 碎片化后因找不到 16KB 连续块而返回 `MBEDTLS_ERR_SSL_ALLOC_FAILED` +(`-0x7F00`);OTA HTTPS 共用同一策略。WebSocket frame 支持分片重组和 8192 +字节上限;超限会关闭连接。 + +## 5. 自动验证 + +宿主机验证覆盖: + +- ClientHello、listen、abort 和 ping JSON +- ServerHello 成功、错误版本和错误音频参数 +- TTS、local prompt、shutdown、配网、error 和未知消息 +- sequence、memory、timer、alarm、call 和 friend_add +- ServerHello 按键映射、连接提示白名单和 button 遥测 +- runtime control 的类型校验、数值钳位、睡眠收敛和临时 LED effect +- `snore_light` 解析、本地提示 start/done 构建与状态机闭环 +- `goodbye` JSON 构建、Effect 路由及各主动关闭路径 +- abort 触发源透传:WakeNet 使用 `wake_word_detected`,按键使用 + `user_initiated`;自然插话由 server 下发两阶段裁决,不由设备回发 abort +- `barge_in` candidate 暂停、rejected 恢复、confirmed 取消且不回发 + abort/listen,以及非法 state 拒绝 +- `ws`/`wss` 默认端口、显式端口、IPv6 和非法 URI +- UTF-8 `stt.text` 与 `tts sentence_start.text` 解析,以及空/缺失文本拒绝 +- 同一 `ServerCommand` 原位复用与旧文本清除;dispatcher 1KB 栈帧编译门禁 +- 本地提示音和关机提示音的状态归约 + +ESP-IDF 5.4.3 已完成含证书包、cJSON 和 `tcp_transport` 的全量构建。 + +2026-07-21 实机已经完成证书校验、TLS upgrade、ClientHello/ServerHello,并在 +超过 110 秒内完成多轮对话。修复遥测背压后未再出现 `command pool exhausted`、 +WebSocket 断开或重连风暴;transport 最低剩余栈约 2.1KB。此前随机出现在调度器 +中的 panic 已由栈尾 watchpoint 证明是好友 NVS 保存任务溢出,并非 WebSocket +socket/TLS 本身。 + +## 6. 后续真机/外部联调 + +- HTTP 鉴权头与当前 server 的实际鉴权配置 +- 设备时间校准和完整 listen/abort/两阶段打断联调 +- 音量、唤醒词、插话开关、轻睡眠和临时红灯控制联调 +- `snore_light` 播放完成、done 解锁及随后进入轻睡眠的完整场景 +- server 收到 `goodbye` 后立即清理连接状态,发送失败时设备仍能完成本地收敛 +- 交换三击/四击映射、`nothing` 禁用及重启持久化 +- 无网络和 server 不可达时的远程提示映射 +- 拔网、服务黑洞、服务重启时的 15/30/90 秒门限和重连 +- 长时间运行的任务栈、PSRAM、heap、socket 泄漏和 watchdog +- `delete_alarm id=-203000` 的保留 ID 协议、解析器和 host 回归测试已经补齐; + 2026-07-21 复刷后不再触发 `realtime_protocol_error id=3102` +- 旧镜像长日志中的 48 条 `unsupported server message ignored` 来自 + `stt`/`llm`/`game` 扩展;当前代码已正式消费 `stt` 并打印输入文本,只有 + `llm`/`game` 继续保留未知扩展诊断计数。打断后的迟到二进制包保持 debug。 +- 长按关机时旧镜像先停 WiFi,导致 goodbye 写入出现两条 ESP transport error。 + transport close drain 已完成代码修复和构建,等待复刷确认 server 收到 goodbye + 且串口不再出现 `poll_write ... connection abort`。 diff --git a/docs/refactoring-roadmap.md b/docs/refactoring-roadmap.md new file mode 100644 index 0000000..98b3f7c --- /dev/null +++ b/docs/refactoring-roadmap.md @@ -0,0 +1,1201 @@ +# Firmware 2 重构路线图 + +> 最后更新:2026-07-21 +> 适用目录:`firmware2/` +> 旧固件目录:`firmware/`(只读参考,不在重构过程中修改) + +## 1. 文档目的 + +本文档是 `firmware2` 后续重构的唯一进度清单,用于回答三个问题: + +1. 当前已经完成了什么。 +2. 下一步按什么顺序实施。 +3. 每一步达到什么条件才可以标记为完成。 + +功能设计和模块边界见 [architecture.md](architecture.md)。跨系统消息格式仍以 +仓库根目录的 `protocols/` 为唯一契约来源。 + +## 2. 状态标记 + +| 标记 | 状态 | 使用条件 | +|---|---|---| +| ✅ | 已完成 | 代码、测试、构建和本阶段验收条件全部满足 | +| 🚧 | 进行中 | 已开始实施,但尚未满足全部验收条件 | +| ⬜ | 未开始 | 尚未实施,或只有接口占位而没有真实能力 | +| ⛔ | 阻塞 | 缺少硬件、外部环境、产品决策或协议前置条件 | + +状态更新规则: + +- 只有接口或空实现不能标记为已完成。 +- 仅宿主机测试通过但实机行为未验证的硬件模块不能标记为已完成。 +- 阶段内任一必需验收项未通过,整个阶段保持“进行中”。 +- 完成一个阶段后,应同时更新本文档的总览、任务清单、验证记录和变更记录。 + +## 3. 总体进度 + +| 阶段 | 内容 | 状态 | 当前说明 | +|---|---|---|---| +| 0 | 独立工程与控制面基础 | ✅ 已完成 | 基础状态机、事件队列、Effect/Port、测试和构建已完成 | +| 1 | Composition Root 与板级基础 | 🚧 进行中 | 实机启动冒烟通过,等待 LED/按键/电源轨完整验收 | +| 2 | 统一播放系统 | 🚧 进行中 | 代码、提示音、host 测试和构建已完成,等待实机播放验收 | +| 3 | WiFi 连接层 | 🚧 进行中 | 当前凭据与 DHCP 已通过,等待断网/恢复/旧凭据专项验收 | +| 4 | WebSocket 控制面 | 🚧 进行中 | TLS/hello/多轮对话已通过,等待完整控制、异常门限和长稳 | +| 5 | 语音上下行数据面 | 🚧 进行中 | 多轮对话与两阶段打断已编码,等待复刷声学/续播/长稳 | +| 6 | WakeNet、VAD、AEC 与打断 | 🚧 进行中 | 本地唤醒硬打断 + server 自然插话裁决完成,等待真机验收 | +| 7 | BLE 配网 | 🚧 进行中 | GATT、预扫描、候选连接和测试完成,等待小程序/真机验收 | +| 8 | Touch、IMU 与电池传感器 | 🚧 进行中 | 代码、host 测试和构建完成,等待传感器真机验收 | +| 9 | 闹钟、IdleWatchdog 与电源管理 | 🚧 进行中 | 代码、host 测试和构建完成,等待真机休眠/唤醒验收 | +| 10 | OTA | 🚧 进行中 | HTTPS 下载、SHA256、A/B 与回滚代码完成,等待真实链路/真机验收 | +| 11 | WiFi/4G 双网策略 | 🚧 进行中 | ML307 PPP、切换策略和 host 测试完成,等待真机/SIM 验收 | +| 12 | 通话与好友碰一碰 | 🚧 进行中 | 信令、音频、BLE/NVS 和 host 测试完成,等待双设备验收 | +| 13 | 全功能对照、稳定性验证与切换 | 🚧 进行中 | uptime 到 45:53 无崩溃/断线,等待复刷与 24h/72h | + +阶段按依赖顺序推进: + +```mermaid +flowchart TB + S0["阶段 0
控制面基础
✅ 已完成"] + S1["阶段 1
装配与板级基础
🚧 进行中"] + S2["阶段 2
统一播放系统
🚧 进行中"] + S3["阶段 3
WiFi 连接层
🚧 进行中"] + S4["阶段 4
WebSocket 控制面
🚧 进行中"] + S5["阶段 5
语音上下行
🚧 进行中"] + S6["阶段 6
WakeNet / VAD / AEC
🚧 进行中"] + S7["阶段 7
BLE 配网
🚧 进行中"] + S8["阶段 8
传感器
🚧 进行中"] + S9["阶段 9
闹钟 / 休眠 / 电源
🚧 进行中"] + S10["阶段 10
OTA
🚧 进行中"] + S11["阶段 11
WiFi / 4G 双网
🚧 进行中"] + S12["阶段 12
通话 / 好友
🚧 进行中"] + S13["阶段 13
全量验证与切换
🚧 进行中"] + + S0 --> S1 --> S2 --> S3 --> S4 --> S5 --> S6 + S6 --> S7 --> S8 --> S9 --> S10 --> S11 --> S12 --> S13 +``` + +原则上不跳过前置阶段。若为了验证风险而提前制作技术原型,原型不得直接视为阶段完成, +也不得绕开对应阶段的验收门禁。 + +## 4. 已完成:阶段 0——独立工程与控制面基础 + +状态:✅ 已完成 + +### 4.1 已完成内容 + +- [x] 在 `firmware2/` 创建独立 ESP-IDF 工程。 +- [x] `firmware2` 不链接、不包含 `firmware/` 的源码。 +- [x] 配置 ESP32-S3、16MB Flash、PSRAM 和 C++17。 +- [x] 建立基础 A/B OTA 分区表。 +- [x] 建立最小 `app_main`、NVS 和默认事件循环启动入口。 +- [x] 建立固定容量的静态 FreeRTOS `AppEventQueue`。 +- [x] 保证 `AppEvent` 可安全复制,不承载音频帧或动态字符串。 +- [x] 将运行状态拆分为六个正交维度: + - Lifecycle + - Connectivity + - Realtime + - Conversation + - Call + - Playback +- [x] 建立无 ESP-IDF 依赖的纯 C++ `ReduceState`。 +- [x] 建立 `ValidateRuntimeState` 状态不变量检查。 +- [x] 建立固定容量 `AppEffect` 输出。 +- [x] 建立以下 Port 接口: + - `IAudioEngine` + - `IConnectivityManager` + - `IRealtimeProtocol` + - `IDevicePlatform` + - `IProvisioningService` + - `IOtaService` +- [x] 建立 `EffectRouter`,只负责把 Effect 路由到 Port,不包含产品决策。 +- [x] 阶段 0 建立 `LoggingEffectSink` 用于启动验证;真实 `EffectRouter` 完成后 + 已删除该临时脚手架。 +- [x] 建立状态归约器宿主机测试。 +- [x] 建立 EffectRouter 宿主机测试。 +- [x] 宿主机测试 2/2 通过。 +- [x] ESP-IDF 5.4.3 完整构建通过。 +- [x] 成功生成 `build/borla-firmware2.bin`。 + +### 4.2 当前明确未完成的部分 + +阶段 0 完成时以下能力尚未实现。当前进展同步如下: + +- [x] BorlaS3 板级驱动代码已在阶段 1 实现,等待实机验收。 +- [x] LED、按键和电源控制代码已在阶段 1 实现,等待实机验收。 +- [x] ES8311、I2S、Opus 和单一扬声器任务已在阶段 2 实现,等待实机验收。 +- [x] WiFi 和 ML307 网络代码已实现,等待真实 AP/SIM/模组验收。 +- [x] WebSocket 连接代码已实现,等待当前 server 与真机联调。 +- [x] BLE 配网代码已实现,等待小程序与真机验收。 +- [x] Touch、IMU 和电池采集代码已在阶段 8 实现,等待实机验收。 +- [x] 闹钟、休眠和 OTA 代码已实现,等待真机/外部链路验收。 +- [x] 通话和好友功能代码已实现,等待双设备验收。 + +### 4.3 阶段 0 验证记录 + +宿主机: + +```text +state_reducer_test PASS +effect_router_test PASS +2/2 tests passed +``` + +ESP-IDF: + +```text +ESP-IDF: 5.4.3 +Target: ESP32-S3 +Build: PASS +Binary: build/borla-firmware2.bin +Binary size: 0x30b50 +App partition: 0x400000 +Free: approximately 95% +``` + +## 5. 阶段 1——Composition Root 与板级基础 + +状态:🚧 进行中 + +### 5.1 目标 + +让基础状态机真正运行在 Borla ESP32-S3 硬件适配层上,同时保持业务逻辑不进入 +`main.cc` 和 Board adapter。 + +### 5.2 实施步骤 + +1. [x] 新建 `CompositionRoot`。 +2. [x] 由 `CompositionRoot` 创建所有 Port adapter。 +3. [x] 使用真实 `EffectRouter` 替换启动入口中的 `LoggingEffectSink`。 +4. [x] 为尚未迁移的能力提供明确报错的 Stub adapter。 +5. [x] 实现 `BorlaS3Platform`: + - [x] MAC 和芯片信息。 + - [x] 固件版本。 + - [x] LED 初始化与状态显示。 + - [x] 重启。 + - [x] 错误上报。 + - [x] 软关机暂时保持安全占位。 +6. [x] 实现按键输入 adapter。 +7. [x] 按键回调只发布 `AppEvent`,不直接调用状态切换。 +8. [x] 增加启动和按键的宿主机/静态测试。 +9. [x] 进行首次实机启动验证。 + +### 5.3 验收条件 + +- [x] `main.cc` 只负责平台初始化和依赖装配。 +- [x] 串口能看到 `Cold → Starting → Running` 状态变化。 +- [ ] LED 能显示 Starting、Idle、Error、Off 基础状态。 +- [ ] 按键事件可以安全进入 `AppEventQueue`。 +- [x] 未实现的 Effect 有明确告警,不会静默成功。 +- [x] 宿主机测试通过。 +- [x] `idf.py build` 通过。 +- [x] ESP32-S3 实机启动超过 110 秒无 panic、无 watchdog reset。 + +### 5.4 当前实现说明 + +- `CompositionRoot` 统一持有平台、Application、EffectRouter 和所有 Port + adapter,析构与生命周期顺序由成员声明固定。 +- `BorlaS3Platform` 已接管 GPIO4/GPIO6 电源轨、设备身份、GPIO11 WS2812、 + 错误灯和重启。 +- GPIO12 按键支持单击、双击、三击、四击和长按。GPIO 回调只发布 + `ButtonClicked` / `ButtonLongPressed`,单击对话控制、双击配网和长按关机的 + 业务含义由纯状态机决定。 +- 音频、双网络、实时协议、配网、传感器、日程、电源、OTA、通话和好友 + Port 均已有真实 adapter。 +- `PowerService` 已实现有序停止和 light-sleep,等待 GPIO12/RTC 真机唤醒验收。 +- 三击进入好友模式,四击请求 WiFi/4G 手动切换;两条路径均保持 Effect/Port + 边界,不在按键回调中直接操作 BLE 或网络。 + +### 5.5 阶段 1 验证记录 + +宿主机: + +```text +state_reducer_test PASS +effect_router_test PASS +2/2 tests passed +``` + +已覆盖的新增状态行为: + +```text +single click: start / stop conversation +single click while speaking: cancel playback / abort / resume listening +single click while ringing or calling: accept / hang up effect +double click: enter provisioning lifecycle +long press: enter shutting-down lifecycle +``` + +ESP-IDF: + +```text +ESP-IDF: 5.4.3 +Target: ESP32-S3 +Dependencies: espressif/button 4.1.3, espressif/led_strip 3.0.3 +Build: PASS +Binary: build/borla-firmware2.bin +Binary size: 0x433d0 +App partition: 0x400000 +Free: approximately 93% +``` + +已完成一次真实烧录、启动和超过 110 秒的多轮对话冒烟测试。栈尾 watchpoint 定位并 +修复 `friend_service2` NVS 保存溢出后,不再出现随机调度器 panic。 + +尚待验证: + +```text +GPIO4 / GPIO6 电源轨实测 +GPIO11 WS2812 各基础灯效 +GPIO12 单击、双击、三击、四击和长按 +24h/72h 持续运行期间 panic / watchdog 情况 +``` + +## 6. 阶段 2——统一播放系统 + +状态:🚧 进行中 + +### 6.1 目标 + +建立唯一的扬声器所有者,让本地提示音、远程 TTS、闹钟、提醒和铃声最终共享 +同一套播放会话、优先级和取消机制。 + +### 6.2 实施步骤 + +1. [x] 实现 ES8311 codec adapter。 +2. [x] 实现 I2S 输出。 +3. [x] 建立 `PlaybackSessionId`。 +4. [x] 建立 `PlaybackController`。 +5. [x] 建立 `PlaybackPipeline`。 +6. [x] 迁移 Opus 解码。 +7. [x] 迁移本地提示音资源生成流程。 +8. [x] 实现播放优先级和抢占规则。 +9. [x] 实现唯一 session ID 隔离、generation 追踪和取消机制。 +10. [x] 区分以下两个事件: + - [x] `TtsStreamEnded`:服务端不再发送音频。 + - [x] `PlaybackDrained`:扬声器已经播放完。 +11. [x] 为以下历史问题增加测试: + - [x] producer 尚未推入第一帧时不能误判完成。 + - [x] 取消后的旧 producer 不能重新填充队列。 + - [x] 过期 session 的 drained 事件不能结束新播放。 + - [x] 本地提示音不能与远程 TTS 混播。 + +### 6.3 验收条件 + +- [ ] 开机提示音可以完整播放。 +- [x] 任意时刻只有一个播放会话拥有扬声器。 +- [x] 新高优先级播放可以确定性取消旧播放。 +- [x] 播放完成不依赖轮询多个全局布尔量。 +- [x] 队列水位、丢帧和播放超时可观测。 +- [x] 宿主机测试和 ESP-IDF 构建通过。 +- [ ] 实机播放测试通过。 + +### 6.4 当前实现说明 + +- `EspAudioEngine` 已替换组合根中的音频 Stub,统一持有输出、播放管线和本地 + 提示音播放器。 +- `Es8311AudioOutput` 使用共享 I2C0、I2S0 和 ES8311 DAC,板级引脚保持为 + SDA=GPIO2、SCL=GPIO1、BCLK=GPIO16、WS=GPIO17、DOUT=GPIO18、 + PA=GPIO40;输出固定为 24kHz、16bit、单声道。 +- `PlaybackPipeline` 只有一个 FreeRTOS 扬声器所有者任务。远程 TTS 和本地 + PCM 都必须先获得 `PlaybackSession`,不能绕过管线直接写 I2S。 +- 播放帧使用 48 个固定槽位和一个解码缓冲区,均在初始化时从 PSRAM 分配; + 稳态播放路径不按帧申请堆内存。 +- 本地自动生成的 session ID 使用 `0x80000000` 以上的独立命名空间,避免与 + 服务端下发的远程 session ID 冲突。 +- 高优先级会话会抢占当前会话;低优先级请求会被拒绝。抢占返回前最多等待 + 当前一个 60ms 帧同步写完,之后旧 session 的帧无法再到达功放。 +- producer 首帧等待超时为 2 秒,已开始播放后的停滞超时为 10 秒。会话、 + 抢占、拒绝、过期帧、丢帧、写入帧和队列高水位都有计数。 +- 45 个正式 Ogg/Opus 提示音已生成到 `firmware2/assets/prompts`,构建时由新 + 生成器校验 Ogg page、OpusHead/OpusTags、packet 连续性和分组命名,再生成 + packed Opus 数据。资源 producer 同样持有独立 session;程序化音阶仅作为资源 + 缺失时的安全回退。 +- capture 侧音频策略仍只记录策略值,麦克风、AEC 和 barge-in 的真实行为 + 分别属于阶段 5 和阶段 6。 + +详细设计见 [playback-system.md](playback-system.md)。 + +### 6.5 阶段 2 验证记录 + +宿主机: + +```text +state_reducer_test PASS +effect_router_test PASS +playback_controller_test PASS +packed_opus_reader_test PASS +4/4 tests passed +``` + +已覆盖的播放边界: + +```text +boot effect starts audio and queues the system prompt +TTS start creates the matching remote playback session +TTS stream end only closes producer input +pending producer cannot be mistaken for a drained session +preempted producer cannot refill the active queue +stale drained event cannot finish a replacement session +local system prompt preempts conversation TTS +producer-start and stalled-session timeouts +``` + +ESP-IDF: + +```text +ESP-IDF: 5.4.3 +Target: ESP32-S3 +Dependencies: 78/esp-opus 1.0.5, espressif/esp_codec_dev 1.4.0 +Build: PASS +Binary: build/borla-firmware2.bin +Prompt assets: 44 files, 513294 packed bytes, max Opus frame 180 bytes +Binary size: 0xe7db0 +App partition: 0x400000 +Free: approximately 77% +``` + +尚待验证: + +```text +真机 ES8311 初始化和 24kHz I2S 时钟 +GPIO40 功放使能、音量和底噪 +开机音从首帧到尾帧完整播放 +连续抢占时无旧 session 串音 +长时间播放期间 PSRAM、panic 和 watchdog 情况 +``` + +## 7. 阶段 3——WiFi 连接层 + +状态:🚧 进行中 + +### 7.1 目标 + +先建立稳定的 WiFi 单网连接,再引入 4G,避免网络驱动和网络切换策略继续耦合。 + +### 7.2 实施步骤 + +1. [x] 实现 `EspWifiTransport`。 +2. [x] 实现 `ConnectivityManager`。 +3. [x] 将 WiFi 事件转换为 `AppEvent`。 +4. [x] 加载已保存 SSID。 +5. [x] DHCP 成功后发布 `NetworkConnected`。 +6. [x] 连接中断后发布 `NetworkDisconnected`。 +7. [x] 实现指数退避。 +8. [x] 实现 RSSI 和连接诊断。 +9. [x] 将重试参数配置化。 +10. [x] 增加断网、恢复和重复事件测试。 + +### 7.3 验收条件 + +- [x] WiFi 回调不直接修改 `RuntimeState`。 +- [x] 断网不会阻塞 Application 主循环。 +- [x] 断网时不会产生高频重连风暴。 +- [x] 网络恢复后状态可回到 Online。 +- [x] Network adapter 不播放提示音、不决定重启、不切换 4G。 +- [x] 宿主机测试和 ESP-IDF 构建通过。 +- [ ] 实机断网恢复测试通过。 + +### 7.4 当前实现说明 + +- `EspWifiTransport` 只封装 ESP-NETIF、WiFi driver、STA 配置和链路快照。 + driver 回调只向 `ConnectivityManager` 投递固定大小事件。 +- `ConnectivityManager` 使用一个静态任务、24 项静态队列和单次 + `esp_timer` 串行处理启动、连接、DHCP、断开和重试。 +- `ConnectivityPolicy` 与 `ReconnectBackoff` 不依赖 ESP-IDF,重复启动、 + 重复成功、掉线风暴和停止后的迟到回调都有确定性行为。 +- 退避参数集中在 `board_config.h`:1 秒起步、60 秒封顶、2 倍增长、 + ±20% 抖动;DHCP 成功后复位。 +- 每次失败轮换到下一组已保存凭据。在线掉线只向 Application 发布一次 + `NetworkDisconnected`,恢复 DHCP 后再发布 `NetworkConnected`。 +- NVS 保持旧固件 `wifi` namespace 和 `ssid/password`、`ssid1/password1` + 至 `ssid9/password9` 键兼容,密码不会进入日志。 +- 无已保存凭据时发布 `ProvisioningRequested`,由状态机进入配网生命周期; + BLE adapter 仍等待阶段 7 实现。 +- `GetDiagnostics()` 可读取阶段、SSID、IPv4、RSSI、信道、凭据索引、退避次数 + 和最近断开原因。 + +详细设计见 [connectivity-system.md](connectivity-system.md)。 + +### 7.5 阶段 3 验证记录 + +宿主机: + +```text +state_reducer_test PASS +effect_router_test PASS +playback_controller_test PASS +packed_opus_reader_test PASS +connectivity_policy_test PASS +5/5 tests passed +``` + +WiFi 策略测试已覆盖: + +```text +missing credentials request provisioning +start and got-ip events are idempotent +driver startup failure enters backoff +online disconnect emits exactly one application event +duplicate disconnects cannot reschedule a retry storm +saved credentials rotate after failure +backoff caps at the configured maximum and resets after DHCP +late driver events are ignored after Stop +``` + +ESP-IDF: + +```text +ESP-IDF: 5.4.3 +Target: ESP32-S3 +Build: PASS +Binary: build/borla-firmware2.bin +Binary size: 0x163bb0 +App partition: 0x400000 +Free: approximately 65% +``` + +尚待验证: + +```text +从旧固件 NVS 读取真实已保存 WiFi +首次 STA 连接、DHCP 和串口诊断 +错误密码、AP 不存在、弱信号时的退避 +路由器断电期间无重连风暴 +路由器恢复后 NetworkDisconnected → NetworkConnected +多组已保存 SSID 的轮换顺序 +长时间运行期间任务栈、heap、panic 和 watchdog +``` + +## 8. 阶段 4——WebSocket 控制面 + +状态:🚧 进行中 + +### 8.1 前置契约 + +- `protocols/websocket_protocol.md` + +本阶段只做控制消息和连接生命周期,不迁移音频数据面。 + +### 8.2 实施步骤 + +1. [x] 实现 `WebsocketTransport`。 +2. [x] 实现 `RealtimeProtocol`。 +3. [x] 实现 hello 握手。 +4. [x] 实现心跳、超时和关闭。 +5. [x] 建立 `ServerMessageDispatcher`。 +6. [x] 将 JSON 转换为强类型命令或 `AppEvent`。 +7. [x] 第一批支持: + - [x] hello + - [x] listen + - [x] tts start/stop + - [x] abort + - [x] play_local + - [x] ping/pong + - [x] control + - [x] error +8. [x] 为非法 JSON、缺字段和未知类型增加测试。 + +### 8.3 验收条件 + +- [x] Application 中不存在大型 JSON `if/else` 分发器。 +- [x] 非法消息不会造成崩溃或状态污染。 +- [x] WebSocket 黑洞断开可以被检测并恢复。 +- [x] 连接回调只发布事件。 +- [x] 协议测试和 ESP-IDF 构建通过。 +- [x] 与现有 server 完成 TLS、hello 和基础消息联调。 +- [ ] 实机联调通过。 + +### 8.4 当前实现与验证记录 + +- `EspWebsocketTransport` 使用 ESP-IDF `tcp_transport`,TLS 使用系统证书包。 +- 网络 I/O 只在静态 transport 任务中执行,Application 不执行阻塞连接。 +- 15 秒 hello 超时、30 秒 ping 和 90 秒黑洞检测均由协议层 timer 管理。 +- ServerHello 校验 v3、session ID 和 24kHz/Opus/60ms 下行参数。 +- NVS `websocket` namespace 保存 URL、token 和协议版本,token 不写日志。 +- 远程 TTS 使用低半区 session ID,本地提示音继续使用高半区,避免冲突。 +- 二进制帧已预留 `IRealtimeBinarySink`,阶段 5 才接入音频数据面。 + +详细设计见 [realtime-control-plane.md](realtime-control-plane.md)。 + +```text +Host tests: 7/7 PASS +ESP-IDF 5.4.3 build: PASS +Binary: build/borla-firmware2.bin +Binary size: 0x198400 +App partition: 0x400000 +Free: approximately 60% +``` + +已完成:真机 DNS、证书校验、TLS/WebSocket upgrade、ClientHello/ServerHello; +长日志 uptime 到 45 分 53 秒,遥测 latest-wins、2 个控制保留槽和读公平性修复后 +无 `command pool exhausted`、断线或重连风暴。预期 server 扩展消息和打断后的 +迟到音频已降为 debug;当前进一步正式解析 `stt.text`,并与 +`tts sentence_start.text` 分别记录完整输入/输出文本。主动关闭新增 750ms 有界 +drain,等待复刷关机验证。 + +尚待验证: + +```text +当前 server 的完整鉴权、ping/pong、listen/abort/运行时控制联调 +MAC + 日历毫秒统一日志、STT/TTS 中文文本串口复验 +网络黑洞、服务重启和长期 socket/heap/watchdog +``` + +## 9. 阶段 5——语音上下行数据面 + +状态:🚧 进行中 + +### 9.1 目标 + +打通一次不含 WakeNet/AEC 的基础端到端对话。 + +### 9.2 固定参数 + +| 方向 | 参数 | +|---|---| +| 上行 | 16kHz、16bit、单声道、Opus、60ms | +| 下行 | 24kHz、16bit、单声道、Opus、60ms | +| 协议 | WebSocket v3 | + +### 9.3 实施步骤 + +1. [x] 建立 `CapturePipeline`。 +2. [x] 实现 I2S 麦克风采集。 +3. [x] 实现 Opus 编码。 +4. [x] 实现固定 60ms 帧。 +5. [x] 实现上行发送队列和背压。 +6. [x] 实现 WebSocket v3 二进制封装。 +7. [x] 实现现有批量音频帧格式。 +8. [x] 接入下行 Opus 到 `PlaybackController`。 +9. [x] 增加包校验、队列水位、丢帧和延迟监控(协议无序列号字段)。 +10. [x] 完成一次端到端对话。 + +### 9.4 验收条件 + +- [x] 音频帧不进入 `AppEventQueue`。 +- [x] 音频任务不直接写 `RuntimeState`。 +- [x] 所有队列都有明确容量和满队列策略。 +- [x] 录音、编码、发送、接收、解码和播放均可独立观测。 +- [x] 协议测试和 ESP-IDF 构建通过。 +- [ ] 连续对话无明显断音、堆增长或任务饥饿。 +- [ ] 实机和 server 联调通过。 + +详细设计见 [audio-data-plane.md](audio-data-plane.md)。 + +当前自动验证:完整 host tests 17/17 通过;ESP-IDF 构建通过。真机旧镜像已完成 +48 次 TTS 开始,暴露 22 个 session 共 71 个开头帧早于播放 session 建立。当前 +镜像 `0x24ace0` 已加入 8 帧 PSRAM pre-roll、唤醒词双工、自然插话单帧上行和 +server 两阶段暂停/裁决;连续对话首字听感、candidate/rejected 续播、confirmed +新问题、网络抖动和长期内存趋势仍需复刷验证。 + +## 10. 阶段 6——WakeNet、VAD、AEC 与打断 + +状态:🚧 进行中 + +### 10.1 目标 + +建立统一 Voice Frontend,通过 `AudioPolicy` 切换运行模式,不允许业务层组合多个 +底层布尔开关。 + +### 10.2 实施步骤 + +1. [x] 实现 WakeNet。 +2. [x] 实现能量 VAD。 +3. [x] 实现 AEC。 +4. [x] 实现 NS。 +5. [x] 实现 AGC。 +6. [x] 建立 AEC reference 单一生产/消费链路,不使用硬编码固定延迟。 +7. [x] 支持以下策略: + - [x] `kWakeWordOnly` + - [x] `kWakeWordDuplex` + - [x] `kConversationCapture` + - [x] `kBargeInDuplex` + - [x] `kCallDuplex` +8. [x] 保证每个麦克风帧只经过一次有状态 VoiceProcessor。 +9. [x] 实现提示音 reference 自唤醒抑制和指标(声学效果待实机)。 +10. [x] 增加 TTS 打断和残留队列测试。 +11. [x] 复用 Playback 首帧/停滞超时恢复。 +12. [x] 删除本地自然人声 detector、固定延迟和相关性硬裁决。 +13. [x] 实现 server `candidate/rejected/confirmed` 两阶段裁决。 +14. [x] candidate 暂停时保留 playback 帧、队列与 session,并暂停 server 下行。 +15. [x] `tts:stop` 到物理 `playback_drained` 期间保持 AEC/单帧 tail 上行。 +16. [x] WakeNet 冷却改为单调时钟;reference miss 不再跳过唤醒词检测。 + +### 10.3 验收条件 + +- [x] Application 不直接控制 WakeNet/VAD/AEC 的组合开关。 +- [ ] 本地提示音和 TTS 不会触发自唤醒。 +- [x] AEC reference 只有 Voice Frontend 单一消费者。 +- [x] 打断后旧播放在 session/generation 层不能继续入队。 +- [x] candidate 可撤销,rejected 原位续播,confirmed 才取消旧 session。 +- [x] TTS 缺失 stop 或网络断开时有超时/取消恢复路径。 +- [ ] 实机安静、噪声、近讲和远讲场景通过。 + +详细设计见 [voice-frontend.md](voice-frontend.md)。当前完整 host tests 17/17、 +server 打断相关定向回归 85/85;自定义 WakeNet 模型镜像生成和 ESP-IDF 构建通过。 + +## 11. 阶段 7——BLE 配网 + +状态:🚧 进行中 + +### 11.1 前置契约 + +- `protocols/ble_provisioning.md` + +### 11.2 实施步骤 + +1. [x] 实现 BLE GATT provisioning adapter。 +2. [x] 实现设备信息读取。 +3. [x] 实现 WiFi 预扫描和缓存。 +4. [x] 实现分包发送和接收。 +5. [x] 实现 WiFi 配置结果通知。 +6. [x] 实现已保存 WiFi 的查询和删除。 +7. [x] 实现 BLE/WiFi 顺序共存和静态 Host task;内部 SRAM 余量待真机测量。 +8. [x] 配网结果只通过 FF05 通知,不直接重启或切状态;只有显式 FF06 才重启。 + +### 11.3 验收条件 + +- [ ] 与现有小程序完成全流程配网。 +- [x] 分包协议与契约一致并有 host 测试。 +- [x] 密码不写日志,SavedWifi 不回传密码。 +- [x] BLE 断开、密码错误和连接超时均有恢复代码路径。 +- [ ] 配网时内部 SRAM 满足 NimBLE 启动要求。 + +详细设计见 [ble-provisioning.md](ble-provisioning.md)。 + +```text +Host tests: 10/10 PASS +ESP-IDF 5.4.3 build: PASS +Binary: 0x20e820 +App partition free: approximately 49% +``` + +## 12. 阶段 8——Touch、IMU 与电池 + +状态:🚧 进行中 + +### 12.1 前置契约 + +- `protocols/sensor_event.md` + +### 12.2 实施步骤 + +1. [x] 拆分 `CapacitiveTouchInput` 与 `TouchChannel`。 +2. [x] 实现触摸基线、阈值、滤波、去抖和成对边沿。 +3. [x] 拆分 `Bmi270Sensor` 与 `ImuProcessor`。 +4. [x] 实现硬件与任务 50Hz 采样。 +5. [x] 按 v2.1 契约实现 1~5 帧、通常五帧的 100ms 批次;WiFi 与 4G/PPP + 使用同一消息结构。 +6. [x] 实现 freefall、freefall_active、caught、dropped、impact 等重力事件。 +7. [x] 拆分 `BatteryMonitor` 与纯逻辑 `BatteryEstimator`。 +8. [x] 实现 ADC 校准、截尾均值、分压还原、电量换算和保守充电推断。 +9. [x] IMU/Touch 消息直接走数据面,电池通过只读快照提供,不进入控制事件队列。 + +### 12.3 验收条件 + +- [x] Touch/IMU/Battery 不位于大型 Board 文件中。 +- [x] 传感器协议字段与 `protocols/sensor_event.md` v2.1 一致并有 host 测试。 +- [x] IMU 数据不经过控制面事件队列。 +- [x] 阈值、采样率和批量参数集中配置。 +- [ ] 实机触摸、静止、抛掷、跌落和电量测试通过。 + +详细设计见 [sensors.md](sensors.md)。 + +```text +Host tests: 11/11 PASS +ESP-IDF 5.4.3 build: PASS +Binary: 0x216c30 +App partition free: approximately 48% +``` + +## 13. 阶段 9——闹钟、IdleWatchdog 与电源 + +状态:🚧 进行中 + +### 13.1 实施前必须确认 + +已按正式架构参数实现:3 分钟提示、15 秒响应窗口、10 分钟告别并软关机。 + +### 13.2 实施步骤 + +1. [x] 建立 `ReminderService`。 +2. [x] 建立 `AlarmService`。 +3. [x] 建立 `IdleService`。 +4. [x] 建立 `PowerService`。 +5. [x] 将闹钟 NVS 持久化与播放逻辑分离。 +6. [x] 将 IdleWatchdog timer 转换为服务事件。 +7. [x] 实现低电量 20% 提醒。 +8. [x] 实现低电量 10% 软关机。 +9. [x] 实现 light-sleep 和本地唤醒来源。 +10. [x] 保留首日 20:30 内建闹钟行为。 + +### 13.3 验收条件 + +- [x] 闹钟长播放不阻塞 Application(代码与静态任务验证)。 +- [x] 闹钟和 Reminder 竞争时有确定性优先级(host 测试)。 +- [x] Idle 提示音通过统一播放策略屏蔽自身 VAD(代码验证)。 +- [x] 软关机前连接、播放和传感器状态有序收敛(代码验证)。 +- [ ] 唤醒来源和 NVS 恢复均通过实机测试。 + +详细设计见 [schedules-and-power.md](schedules-and-power.md)。 + +```text +Host tests: 12/12 PASS +ESP-IDF 5.4.3 build: PASS +Binary: 0x21d4d0 +App partition free: approximately 47% +``` + +## 14. 阶段 10——OTA + +状态:🚧 进行中 + +### 14.1 前置契约 + +- `protocols/ota_protocol.md` + +### 14.2 实施步骤 + +1. [x] 实现版本检查。 +2. [x] 解析固件 URL、版本、大小和 SHA256。 +3. [x] 实现 optional、auto、force 三种升级策略。 +4. [x] 实现下载和备用分区写入。 +5. [x] 实现 SHA256 校验。 +6. [x] 设置新 boot partition。 +7. [x] 实现启动自检和 `MarkCurrentVersionValid`。 +8. [ ] 验证自动回滚。 +9. [x] OTA 过程只通过 OTA service 发布进度事件。 + +### 14.3 验收条件 + +- [x] 下载失败不破坏当前运行分区(代码路径验证)。 +- [x] SHA256 错误拒绝升级(代码与解析测试)。 +- [x] OTA 期间禁止通话和新对话(状态机测试)。 +- [ ] 新固件自检失败能够回滚。 +- [ ] 与现有 server/backend/admin OTA 链路联调通过。 + +详细设计见 [ota.md](ota.md)。 + +```text +Host tests: 13/13 PASS +ESP-IDF 5.4.3 build: PASS +Binary: 0x227ab0 +App partition free: approximately 46% +``` + +## 15. 阶段 11——WiFi/4G 双网策略 + +状态:🚧 进行中(代码完成,等待真机/SIM 验收) + +### 15.1 目标 + +在 WiFi 单网稳定之后接入 ML307,并把网络传输、网络选择策略和用户提示彻底分离。 + +### 15.2 实施步骤 + +1. [x] 实现 `Ml307Transport`。 +2. [x] 实现 AT/UART、LTE 注册、拨号和 PPP 生命周期。 +3. [x] 实现 4G 模组存在性探测。 +4. [x] 建立独立、可宿主机测试的 `DualNetworkPolicy`。 +5. [x] 实现 WiFi 持续断线 30 秒后转 4G。 +6. [x] 实现 WiFi RSSI 连续弱信号策略。 +7. [x] 实现 4G 失败回退 WiFi。 +8. [x] 将 APN、拨号命令、切网门限和采样参数配置化。 +9. [x] 用户提示由上层 Effect 决策,不由底层 ML307 transport 播放。 +10. [x] 四击触发手动 WiFi/4G 切换。 +11. [x] 复用同一个 ConnectivityManager 上游接口,切换时显式断开并重建 + Realtime。 + +### 15.3 验收条件 + +- [x] Transport 不写 NVS、不播放提示音、不直接重启。 +- [x] NetworkPolicy 可宿主机测试。 +- [x] 模组缺失时手动切换停留在 WiFi,并产生“4G 不可用”上层提示事件。 +- [x] PPP UART 在独立静态任务中运行,不堵塞 Application 控制面。 +- [ ] WiFi、弱网、断网、4G 开关和模组缺失场景通过。 + +详细设计见 [dual-network.md](dual-network.md)。 + +```text +Host tests: 14/14 PASS(阶段 11 完成时) +ESP-IDF 5.4.3 build: PASS +真机待验证: UART43/44、电源/模组存在、SIM 注册、PPP、DNS/TLS、自动/手动切换 +``` + +## 16. 阶段 12——通话与好友碰一碰 + +状态:🚧 进行中(代码完成,等待双设备真机验收) + +### 16.1 前置条件 + +- `kCallDuplex` 音频策略已经通过实机测试。 +- AEC 全双工稳定。 +- BLE 配网和 BLE 资源释放稳定。 +- WebSocket call/friend 协议保持兼容。 + +### 16.2 实施步骤 + +1. [x] 实现主叫等待、来电响铃、接听、连接、挂断和未接状态。 +2. [x] 实现通话专用 playback session 与 `kCallDuplex` 上下行音频。 +3. [x] 实现通话中网络异常统一收敛和 Realtime 恢复路径。 +4. [x] 迁移好友碰一碰 BLE 广播、扫描和候选选择。 +5. [x] 通过独占状态处理 NimBLE 与 Realtime/音频资源竞争。 +6. [x] 实现好友 NVS 离线优先保存和重连补传 `friend_add`。 +7. [x] 为非法/重复通话信令、候选去重、RSSI 门限、MAC 归一和好友列表增加 + host 测试。 +8. [x] 三击进入/退出好友模式,等待 NimBLE 完全停止后再恢复网络与 Realtime。 + +### 16.3 验收条件 + +- [x] 通话状态与普通 Conversation 状态在状态不变量中互斥。 +- [x] 来电通过通话优先级抢占 TTS/普通本地提示,代码路径不混播。 +- [x] 挂断后状态机恢复 `kWakeWordOnly`。 +- [x] Friend mode 结束事件只在 NimBLE 停止后发布,随后才恢复 Realtime。 +- [ ] 双设备实机测试通过。 + +详细设计见 [calls-and-friends.md](calls-and-friends.md)。 + +```text +Host tests: 16/16 PASS(阶段 12 完成时) +ESP-IDF 5.4.3 build: PASS +真机待验证: 双设备通话、AEC、弱网挂断、BLE 配对、共存、离线补传 +``` + +## 17. 阶段 13——全功能对照与正式切换 + +状态:🚧 进行中(代码与自动验证完成,等待硬件回归) + +### 17.1 功能对照 + +- [x] 启动和提示音代码。 +- [x] WiFi 配网代码。 +- [x] 4G 网络代码。 +- [x] WebSocket 重连代码。 +- [x] 普通语音对话代码。 +- [x] 连续对话代码。 +- [x] TTS 打断代码。 +- [x] 本地提示音与显式 `index` 选择代码。 +- [x] Touch 代码。 +- [x] IMU/重力事件代码。 +- [x] 电池和充电估算代码。 +- [x] Reminder 代码。 +- [x] Alarm 代码。 +- [x] IdleWatchdog 代码。 +- [x] 软关机和唤醒代码。 +- [x] OTA 和回滚代码。 +- [x] 通话代码。 +- [x] 好友碰一碰代码。 +- [x] 激活码顺序播放及 6 秒重复代码。 +- [x] 记忆 NVS 缓存、ClientHello 回传和旧 `claude_mem` 迁移代码。 +- [x] ServerHello 三击/四击映射、连接错误提示的 NVS 持久化及按键遥测代码。 +- [x] 旧 `device`/`friends` NVS 数据向 `friend_v2` 的保留式迁移代码。 +- [x] 运行时音量、唤醒词、TTS 插话、轻睡眠和临时安全红灯控制代码。 +- [x] `snore_light` 本地资源、单条提示音 start/done 和睡眠场景解锁闭环。 +- [x] 配网、轻睡眠和关机前的 `goodbye` 优雅关闭与 server 清理信令。 +- [x] `CompositionRoot` 与生产构建已移除所有 `Pending*` 占位 adapter。 + +上述勾选仅表示代码存在并已通过可执行的自动验证,不代表真机功能验收。逐项 +硬件结果记录在 [validation-matrix.md](validation-matrix.md)。 + +### 17.2 稳定性门禁 + +- [x] 周期性内部堆/PSRAM 最小余量和全部任务栈高水位诊断代码已接入。 +- [x] 真机旧镜像 uptime 到 45 分 53 秒并完成多轮对话,无 panic/watchdog/断线/ + 重连风暴;新 pre-roll/close-drain 镜像仍待复刷。 +- [ ] 连续运行测试通过。 +- [ ] 多轮对话无持续堆内存下降。 +- [ ] 所有任务栈高水位满足安全余量(低于 512 字节自动告警)。 +- [ ] 无看门狗复位。 +- [ ] 无不可恢复的 Speaking/Listening 卡死。 +- [ ] 网络切换不产生重连风暴。 +- [ ] 音频队列无长期堆积。 +- [ ] 关键链路 trace 完整。 + +稳定性验证步骤见 +[hardware-validation-checklist.md](hardware-validation-checklist.md),运行诊断格式见 +[runtime-diagnostics.md](runtime-diagnostics.md)。 + +### 17.3 切换条件 + +只有以下条件全部满足,才允许将 `firmware2` 作为新的正式固件: + +- [ ] 阶段 0~12 全部完成。 +- [ ] 协议兼容测试通过。 +- [ ] 全功能实机回归通过。 +- [ ] OTA A/B 回滚通过。 +- [ ] 旧固件所有现场修复都有测试或明确替代实现。 +- [ ] 产品确认用户可感知行为一致。 +- [ ] 已制定灰度、回退和版本升级方案。 + +## 18. 每个任务的标准执行流程 + +后续每个任务都按以下顺序执行: + +1. 阅读相关架构、模块、流程和 `protocols/` 文档。 +2. 在旧 `firmware/` 中只读定位现有行为和历史修复。 +3. 补充行为测试或明确验收清单。 +4. 在 `firmware2/` 中定义接口和所有权。 +5. 实现最小能力。 +6. 运行宿主机测试。 +7. 运行 `idf.py build`。 +8. 对硬件功能执行实机验证。 +9. 检查内存、任务栈、队列和日志。 +10. 更新本文档状态和验证记录。 + +涉及通信格式变化时,必须在第 3 步之前先更新 `protocols/`;只做等价迁移时, +不得自行改变现有协议。 + +## 19. 提交粒度 + +建议每个可独立验收的子任务对应一个提交,例如: + +```text +refactor(firmware): 建立 firmware2 依赖装配入口 +feat(firmware): 实现 BorlaS3 基础平台适配 +feat(firmware): 建立统一播放会话 +feat(firmware): 接入 WiFi 连接管理 +feat(firmware): 实现 WebSocket 控制面 +``` + +提交、合并和部署仍遵循项目约束:只有用户明确要求时才执行。 + +## 20. 变更记录 + +### 2026-07-21 + +- 最新真机日志中,用户在 TTS 尾部提问“月亮是怎么升起来的”,server 最终只收到 + “你觉得呢?”。日志证明 `tts_stream_ended` 后设备仍处于 playback draining,旧 + 控制却已关闭 `barge_in`,形成 producer EOF 到物理扬声器排空之间的采集空窗; + drain 后残余音频又作为普通监听 pre-roll 进入 ASR。 +- 协议明确 `tts:stop` 不是 physical drain。两阶段固件新增 tail uplink gate, + server 保持 TTS 回声上下文与自然插话窗口,直到设备 `playback_drained` 后发送 + `listen:start`;无活动人声时丢弃尾音 pre-roll,有活动人声时保留完整采集继续 + ASR/回声判定。 +- 修复“你好播乐”在 TTS 中漏检的两个确定性盲区:WakeNet 的 2 秒防重复从仅在 + WakeNet 输入时递减的帧计数改为单调时钟;AEC reference FIFO 单帧 miss 时仍用 + 零 reference 处理并送入 WakeNet。播放中段与 draining 状态的本地硬打断状态机 + 回归均通过。 +- 本轮 firmware2 host tests 17/17、server 打断相关定向回归 85/85、ESP-IDF 5.4.3 + ESP32-S3 全量构建通过。镜像 `0x24ace0`,应用分区剩余 `0x1b5320`(43%), + SHA256 `14c7fb88ea2c4ab177e1986fb2efd0d4d91213647ebe6fa15a12f264691270df`。 + 代码与自动验证已完成;TTS 中段/尾部唤醒、完整自然问题和无人误取消仍待真机。 + +- 三轮真机日志确认旧方向不可继续:本地能量 detector、连续三帧确认、跨帧相关性 + 和固定 60ms reference 延迟均会在无人说话时被残余 TTS 触发,无法可靠区分 + “扬声器回声”和“近端真人”。相关实现、静态历史缓冲、事件和独立 host test 已 + 从 firmware2 删除;不再通过继续降低或提高阈值修补最终裁决。 +- 自然插话改为 server 唯一裁决:固件在 TTS 期间逐 60ms 上行 AEC 后音频;server + VAD 下发 `candidate` 让设备可撤销暂停,再用 ASR 与当前/近期 TTS 文本过滤回声, + 下发 `rejected` 原位续播或 `confirmed` 取消旧 session 并处理新问题。server 在 + candidate 期间也暂停下行,避免固定队列溢出。 +- 修复 CapturePipeline 原始/处理 PCM 缓冲别名;新增 playback pause/resume effect、 + 三态协议解析、feature 协商和单帧上行。WakeNet 的 `wake_word_detected` 本地硬 + 打断保持独立,故事/音乐关闭自然插话时仍可使用“你好播乐”。 +- firmware2 host tests 17/17、server 定向回归 64/64、ESP-IDF 5.4.3 全量构建和 + size 门禁通过。镜像 `0x24abb0`,应用分区剩余 `0x1b5450`(43%),静态 D/IRAM + 剩余 28345 bytes,静态 IRAM 剩余 1 byte,SHA256 + `f8c79570896e277a74d83421df58feb736ebe4b83b86e0519b464e3fb16c0714`。自然插话 + 静音时延、rejected 续播、confirmed 新回复及 10 分钟误取消率等待真机验收。 + +- 分析新镜像重复启动日志:前三次均在 `ServerMessageDispatcher::ParseHello` 触发 + stack canary,第四次解析后也只剩 196 bytes。根因是 4672-byte + `ServerCommand` 虽常驻 PSRAM,各 `ParseXxx` 仍按值返回并生成 4736-byte 栈帧。 +- 将所有 server 消息解析器改为直接写入 PSRAM `incoming_command_`,删除生产 + 按值 Parse API,并增加 1KB 栈帧编译门禁。Xtensa 机器码确认 ParseHello + 4736→64 bytes、ParseInto 32 bytes、全部 dispatcher 函数最大 176 bytes。 +- 修复重启保留 epoch 但未恢复时区造成握手前误显示 UTC,以及 WiFi 分段 vprintf + 每片重复添加前缀的问题。握手前强制 `TIME-UNSYNCED`,有效 ServerHello 后才 + 切换本地日历毫秒;非标准日志只在线首加前缀。 +- 本轮 host tests 17/17、ESP-IDF 5.4.3 构建和栈帧门禁通过;镜像 `0x24b400`, + 应用分区剩余 `0x1b4c00`(43%),静态 D/IRAM 剩余 28353 bytes,SHA256 + `2e32a14ea4fd88e787b73762f2a43b14e29a62f1e72d55429827f25c76fa8f0f`。连续启动 + 10 次、ServerHello 剩余栈、校时切换和 WiFi 日志格式等待复刷验证。 + +- 按协议先行补充 server→设备 `stt` 契约。`ServerMessageDispatcher` 现解析最长 + 1023 字节 UTF-8 输入文本,并提取 `tts sentence_start.text`;Realtime 用 + `ConversationText2` 分别打印 `direction=input` 与 `direction=output`,不改变 + 对话状态或播放时序。 +- 新增应用期统一日志 formatter:每条普通 `ESP_LOG` 前置 WiFi STA MAC; + ServerHello 校时后使用设备本地 `YYYY-MM-DD HH:MM:SS.mmm`,校时前明确显示 + `TIME-UNSYNCED+ms`。ROM/bootloader/early/DRAM/direct printf 不经过应用 + 回调,已在运行诊断文档中明确边界。 +- 上述代码与自动验证已完成:host tests 17/17、ESP-IDF 5.4.3 全量构建通过;镜像 + `0x24c8a0`,应用分区剩余 `0x1b3760`(43%),静态 D/IRAM 剩余 28369 bytes, + SHA256 `db0f5bf14795ab722db3f28f57fd5df9a885cf1b4b3404c8fd729ec83bc00466`。 + MAC/UTC+8 日历毫秒格式与中英文对话文本仍等待复刷串口验证,不标记真机完成。 + +- 分析 1838 行、约 219KB 的长日志:文件可见窗口约 27 分 58 秒,设备 uptime + 到 45 分 53 秒。48 次 TTS、6 组五分钟诊断、27 个任务期间无 panic、watchdog、 + brownout、重启、断线或重连;电池 165 个样本稳定在 4005~4019mV、91%~92%。 +- 定位 22 个 TTS session 共 71 个开头 Opus 帧被丢弃:二进制帧在协议 task 设置 + session 后、Application 执行 `BeginRemotePlayback` 前到达。新增 PSRAM 固定 + 8 帧 pre-roll,并用互斥边界保证暂存与开始/冲刷的原子顺序;增加 session 隔离、 + 顺序和容量 host 测试。 +- 将 48 条预期 `stt`/`llm`/`game` 扩展和打断后的 3 个迟到音频包降为 debug, + 保留协议诊断计数。 +- 定位长按关机末尾两条 transport error 为 goodbye/close 尚在 I/O 队列时 WiFi + 已被同步停止。Close 现在最多等待 750ms,让 worker 按 `goodbye → close` 顺序 + drain,再允许 EffectRouter 继续停网;真实断网仍不阻塞本地收敛。 +- 本轮 host tests 17/17、ESP-IDF 5.4.3 增量全量链接通过。新镜像 `0x248c60`, + 应用分区剩余 `0x1b73a0`(43%),静态 D/IRAM 剩余 28393 bytes,SHA256 + `558f7e8a8fdd5d0d9efde495f182f8d93e1d29cbd21e63d63f0260a5a0b40bb9`。串口当前由 + 用户的 monitor 占用,新镜像尚未烧录,pre-roll 与关机日志保持待真机验证。 + +- 根据最新稳定对话日志继续清理真实错误与误报警:`3102` 根因是 server 下发 + `delete_alarm id=-203000` 删除首日内建闹钟,而解析器只允许正 ID;协议先行补充 + 保留 ID,并增加接受 `-203000`、拒绝 `0`/其他负数的 host 回归测试。 +- 修复强 WiFi 稳态每 30 秒探测 ML307 导致的 UART 内部 heap 分配失败:只在 + WiFi 离线/弱信号或手动切网时探测,AT presence 使用 512B RX/无 TX 队列,PPP + 才使用 4096B/2048B 缓冲;显式传入 IRAM ISR flag,避免驱动自动修正提示。 +- 清理非故障 warning:WPA2 凭据显式设置 WPA2 门限;正常播放 producer pacing + 降为 debug;无效电池只在状态边沿告警;IDF IPC 任务使用 384B、应用任务保持 + 512B 栈告警线。 +- 修复后 host tests 17/17 与 ESP-IDF 5.4.3 构建通过。最终镜像 `0x248960`, + 应用分区剩余 `0x1b76a0`(43%),SHA256 + `c8ba3f97250c347a69f499ce1634805402f669e494a576a99ac1f4da5949347f`;烧录和 51 秒 + 真机复验通过,日志无 `W`/`E`,`3102`、UART malloc error 和 IPC LOW 均消失, + 电池稳定为约 3992mV/90%。 + +- 最终定位启动后随机 `vPortYieldFromInt`/`vTaskSwitchContext` panic:开启 + `CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK` 后,首个非法写入准确落在 + `friend_service2` 的 `NvsFriendStore::Save`。2KB 栈同时承载约 1.8KB 持久化 + 快照和 NVS 调用链,越界破坏了静态任务 TCB,调度器只是后续暴露点。 +- 将好友、闹钟和记忆路径的大型持久化工作对象统一改为 PSRAM RAII 对象;好友与 + 闹钟任务使用集中定义的 4KB 内部栈。WebSocket transport 栈提升到 12KB,约 + 3.6KB 的 `ServerCommand` 改为单个 PSRAM 常驻对象并就地解析。 +- 修复 WebSocket 拥塞:传感器文本改为独立双槽 latest-wins,二进制流量始终保留 + 2 个控制槽,每轮最多发送 2 条命令后回读 socket,并在成功读取后让出 1 个 tick。 + 多轮对话中不再出现 `command pool exhausted`、断线或重连风暴。 +- 上一轮 host tests 17/17、ESP-IDF 5.4.3 构建及烧录通过。镜像 `0x2488a0`,应用 + 分区剩余 `0x1b7760`(43%),静态 D/IRAM 剩余 28505 bytes;静态 IRAM 仅余 + 1 byte,需在正式切换前回收。SHA256 + `7340cbb6a99423491e0b9fa021caf8439d7829e1cc5d10f62205f0a290fab674`。 +- 最终真机运行超过 110 秒并完成多轮对话,无 Guru Meditation、自动重启、栈尾 + watchpoint、命令池耗尽或 WebSocket 重连风暴;TLS PSRAM、提示音常驻 worker + 和无效电池不误关机均完成复刷验证。 +- 当时保留三个后续项:每次连接后一次 `realtime_protocol_error id=3102`、个别 session + 单个下行 Opus 首帧早于 `tts_started`、WiFi/音频活跃且内部 heap 较低时 ML307 + UART 安装失败。它们未阻断本次启动和基础对话,但必须分别进入协议、音频和 4G + 专项验收。 + +- 根据首次真机启动日志定位并修复关键任务栈溢出:`playback` 原 8KB、 + `connectivity2` 原 2KB 均不足,后续启动路径中的 `capture2` 和 + `dual_network2` 同步纳入预算修复。 +- 新增统一 `core/task_stack_budget.h`:播放 36KB、采集 32KB,使用 PSRAM + capabilities task;连接管理与双网任务各 8KB,保持内部 RAM。栈单位明确为 + ESP-IDF bytes,并增加 host 编译期预算门禁。 +- 运行诊断改为启动后 5 秒、30 秒各输出一次,此后每 5 分钟输出,便于捕捉 + Opus、I2S 与 WiFi 初始化阶段的栈峰值。 +- 修复后 host tests 17/17 通过,ESP-IDF 5.4.3 clean build 通过;镜像 + `0x247c50`,SHA256 + `cc868793186ac2e216b318ccebc78586f0333f2e25fdcf91ae33ccf1dbfca8d2`。 +- 上述代码与自动验证标记为已完成;重新烧录后 60 秒无 panic、早期栈水位和 + 内部 heap 余量仍需真机确认,暂不标记硬件验收完成。 +- 第二次真机日志确认设备已越过 `playback`/`connectivity2` 原崩溃点并成功 + DHCP;随后在 Realtime 第四次 1 秒 tick 的重连分支触发 `esp_timer` 栈溢出。 +- 根因是 timer 回调的 2574-byte heartbeat 局部缓冲与 WebSocket 2574-byte + 命令临时对象嵌套,超过共享 timer 的 3584-byte 栈;不是首轮修复回归。 +- heartbeat ping 改为静态 JSON(pong 上限 128 bytes);WebSocket 10 项大命令队列 + 改为静态索引队列 + PSRAM 固定命令池,并将预期的播放池背压日志限制为每个 + session 一条。 +- 全任务诊断从共享 `esp_timer` 迁到独立 priority 2、8KB PSRAM worker;静态 + D/IRAM 余量从 10493 增加到 36021 bytes,也为 TLS 释放约 25KB 内部内存。 +- 第二轮修复 host tests 17/17 与 ESP-IDF 5.4.3 clean build 均通过;镜像 + `0x247dc0`,SHA256 + `58a7b47080f62adb2958b96de9cf1e059d6de6abe7b7253e1f4be55eeb72b090`。 +- 第二轮代码与自动验证已完成;`esp_timer`、TLS、5秒/30秒诊断和 60 秒稳定 + 启动等待重新烧录确认。 +- 第三次真机日志确认第二轮 `esp_timer` 修复通过:设备运行至 36 秒无 panic, + 5/30 秒全任务高水位均高于 512 bytes;由于电池误关机,完整 60 秒门禁仍未完成。 +- 定位 `mbedtls_ssl_setup returned -0x7F00` 为 TLS 内存分配失败:当时内部 + heap 最大连续块仅 6656 bytes,而 PSRAM 尚余约 7.6MB。构建配置已切换为 + `CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC=y`,让 WebSocket/OTA TLS 动态对象和 + 16KB/4KB record buffer 使用 PSRAM。 +- 将每次提示音动态创建的 4KB 内部栈任务重构为单一常驻 worker:6KB 栈和 + producer context 均位于 PSRAM,有界队列深度 4,避免断网重试期间任务创建 + 失败和任务资源抖动。 +- 修复 GPIO10 返回 0~39mV 时被当作 0% 电量的问题:新增 2500~4500mV + 物理有效性门禁,无效读数不进入估算器并立即清除有效快照,因此不能触发 + `critical_battery`/软关机;实际 ADC 引脚、分压与电池仍待真机核对。 +- 第三轮修复 host tests 17/17 与 ESP-IDF 5.4.3 full clean build 均通过;镜像 + `0x2481e0`,应用分区剩余 `0x1b7e20`(43%),静态 D/IRAM 剩余 + 35805 bytes,SHA256 + `8047e8523ed174dde411b9ac1612ca0d9f4b1944f490ba22bfa4294e4dc65c71`。 +- TLS 建连、提示音 worker 和无效电池不关机的真机复刷仍待执行,相关阶段继续 + 保持“进行中”。 +- 第四次复刷尝试的 `fullclean build` 成功并生成上述 `0x2481e0` 镜像,但旧镜像 + 已处于无定时唤醒的 final light-sleep,ESP ROM 下载握手返回 + `No serial data received`,因此实际 flash/monitor 均未发生。本次不改变任何 + 真机验收状态;需先断电重连或通过 BOOT+RESET 进入下载模式后再次烧录。 +- 完成阶段 11 代码:ML307 UART/AT/LTE/PPP transport、双网选择策略、弱网及 + 断网自动切换、4G 失败回退、四击手动切换和提示事件分层。 +- 完成阶段 12 代码:通话信令与独立会话、`kCallDuplex` 音频、好友 BLE + 扫描/广播、候选筛选、NVS 离线保存和 Realtime 重连补传。 +- 完成阶段 13 缺口代码:`play_local_sequence`、激活码 6 秒重复、本地提示 + `index` 透传、记忆同步/NVS/旧分区迁移,以及周期性 heap/任务栈诊断。 +- 完成 ServerHello 远程行为配置:三击/四击动作映射、连接失败提示 NVS + 持久化,以及三击/四击并行遥测。 +- 完成旧 `device`/`friends` NVS 好友与昵称数据向 `friend_v2` 的保留式迁移。 +- 完成运行时 `control` 强类型解析和执行:音量、唤醒词、TTS 插话、轻睡眠与 + 临时安全红灯;关闭插话时同步关闭 TTS 上行门并清除残留批次。 +- 增加 `snore_light` Ogg/Opus 资源和单条 `play_local` start/done 生命周期, + 修复 server 睡眠场景等待本地播放完成后才能进入轻睡眠的闭环。 +- 补齐 `goodbye` 优雅关闭:配网、轻睡眠和关机先通知 server 清理,再关闭 + Realtime;消息失败不阻塞设备本地收敛。 +- 清除阶段 0 脚手架遗留的 `Pending*` adapter,生产组合根不含占位实现。 +- 删除已退出 CMake 的 `LoggingEffectSink` 临时文件,源码树不再保留备用占位 + Effect 执行路径。 +- 先更新 `protocols/websocket_protocol.md`,明确 ClientHello feature、 + `memory_cache`、`memory_sync`、`button_map`、连接错误提示和按键遥测契约。 +- 当时 host tests 增加到 16/16;ESP-IDF 5.4.3 全量构建通过,阶段基线镜像 + `0x247660`,4MB 应用分区空余 `0x1b89a0`(约 43%)。 +- 阶段 1~13 的硬件、server、小程序、双设备、声学、长稳和 A/B 回滚验收 + 尚未执行,相关阶段保持“进行中”,并集中记录到真机验证清单。 +- 完成阶段 9 代码:Reminder、Alarm/NVS、ScheduleCoordinator、AlertRinger、 + IdleService、低电量策略、PowerService、light-sleep 和本地唤醒。 +- 完成阶段 10 代码:HTTPS 版本检查、策略解析、流式 A/B 写入、size/SHA256 + 校验、boot slot 切换、新镜像确认和失败回滚入口。 +- host tests 增加到 13/13;ESP-IDF 5.4.3 全量构建通过,镜像 `0x227ab0`。 +- 阶段 9、10 的真机低功耗、RTC 唤醒、真实 OTA 和 A/B 回滚验收未执行, + 因此均保持“进行中”。 +- 完成阶段 5 音频上下行数据面:全双工 I2S、24k→16k、Opus 编码、v3 + 二进制批量上行和下行播放接入。 +- 完成阶段 6 Voice Frontend:ESP-SR 2.4.6、自定义 WakeNet 模型分区、VAD、 + AEC/NS/AGC、播放 reference、自唤醒抑制和 speaking 打断。 +- 完成阶段 7 BLE 配网代码:FF01~FF07、MTU 分包、WiFi 预扫描缓存、候选 DHCP + 验证后落盘、SavedWifi 安全列表及静态 NimBLE Host task。 +- 完成阶段 8 传感器代码:五路 Touch、自适应阈值、BMI270 50Hz、IMU 批次、 + Gravity 低延迟旁路、ADC 电池估算和独立静态任务。 +- host tests 增加到 11/11;ESP-IDF 5.4.3 全量构建通过,镜像 `0x216c30`, + 应用分区约 48% 空余。 +- 阶段 8 的传感器真机验收未执行,因此保持“进行中”。 +- 阶段 5~7 的真机、server、小程序和声学验收未执行,因此保持“进行中”。 +- 启动阶段 3,状态标记为进行中。 +- 完成 `EspWifiTransport`、`ConnectivityManager`、纯 C++ + `ConnectivityPolicy` 和 `ReconnectBackoff`。 +- 完成兼容旧固件 NVS 键的凭据存储、最多 10 组 SSID 轮换、RSSI/IP/信道和 + 断开原因诊断。 +- 完成 1~60 秒指数退避、±20% 抖动、重复事件抑制和 DHCP 成功复位。 +- 阶段 3 加入连接策略测试,完整 host 测试 5/5 通过;ESP-IDF 5.4.3 构建 + 通过,镜像大小 `0x163b10`。 +- 保留 WiFi 真机连接、断网恢复和长期稳定性验收项未勾选,因此阶段 3尚未 + 标记完成。 +- 启动阶段 2,状态标记为进行中。 +- 完成 `EspAudioEngine`、`PlaybackController`、`PlaybackPipeline` 和 + `OpusFrameDecoder`。 +- 完成 ES8311、I2C0、I2S0、GPIO40 功放和 24kHz 单声道输出适配。 +- 完成播放优先级、抢占、唯一 ID 隔离、generation 追踪、首帧/停滞超时和 + 指标快照。 +- 完成 45 个本地 Ogg/Opus 资源、严格构建期校验和 packed frame reader。 +- 阶段 2 host 测试 4/4 通过,ESP-IDF 5.4.3 构建通过。 +- 保留实机播放验收项未勾选,因此阶段 2 尚未标记完成。 +- 启动阶段 1,状态标记为进行中。 +- 完成 `CompositionRoot`、真实 `EffectRouter` 装配和显式 `Pending*` Stub。 +- 完成 Borla-S3 电源轨、身份、WS2812、重启和错误上报平台适配。 +- 完成 GPIO12 按键事件适配和按键业务状态机测试。 +- 阶段 1 host 测试 2/2 通过,ESP-IDF 5.4.3 构建通过。 +- 保留实机验收项未勾选,因此阶段 1 尚未标记完成。 +- 创建完整重构路线图。 +- 将阶段 0 标记为已完成。 +- 记录阶段 0 的宿主机测试和 ESP-IDF 构建结果。 +- 将只有接口、尚无真实实现的模块统一标记为未开始。 +- 明确后续阶段顺序、交付物和验收门禁。 diff --git a/docs/runtime-diagnostics.md b/docs/runtime-diagnostics.md new file mode 100644 index 0000000..f538831 --- /dev/null +++ b/docs/runtime-diagnostics.md @@ -0,0 +1,91 @@ +# Firmware 2 运行时诊断 + +> 当前状态:已取得累计 45 分 53 秒、多轮对话基线,24h/72h 趋势仍待确认 + +## 1. 统一日志身份与时间 + +应用入口已安装统一的 `ESP_LOG` 输出格式。时钟完成服务端 ServerHello 校准后, +每条应用运行日志使用设备 WiFi STA MAC 和设备本地日期时间: + +```text +[58:E6:C5:72:83:6C][2026-07-21 14:23:09.962] I RuntimeDiagnostics2: heap ... +``` + +时间字段精确到毫秒。年月日、时分秒使用 ServerHello 的 `server_time` 与 +`tz_offset`;当前 server 下发 UTC+8。只有有效 ServerHello 已执行 +`settimeofday`/`tzset` 后,formatter 才将时钟标记为同步。上电到该时刻之间没有 +可信的本地日历时间,因此明确输出: + +```text +[58:E6:C5:72:83:6C][TIME-UNSYNCED+131368ms] I BorlaFirmware2: ... +``` + +校时后自动切换为日历时间,不打印误导性的 1970 年日期。该回调覆盖 app_main +之后通过普通 `ESP_LOGx` 输出的应用和 IDF 运行日志。ROM、bootloader、 +`ESP_EARLY_LOGx`/`ESP_DRAM_LOGx` 以及第三方库直接调用 `printf` 的内容不经过 +`esp_log_set_vprintf`,所以无法附加应用期 MAC/日历前缀。 + +WiFi 二进制组件会用多次 vprintf 拼接一个逻辑行;formatter 只在线首添加一次 +MAC/时间,后续片段沿用同一行,换行后再生成下一组前缀。 + +对话文本使用独立标签,完整输出服务端 `stt.text` 和 +`tts(state=sentence_start).text`: + +```text +[58:E6:C5:72:83:6C][2026-07-21 14:23:10.104] I ConversationText2: direction=input text=今天天气怎么样 +[58:E6:C5:72:83:6C][2026-07-21 14:23:11.337] I ConversationText2: direction=output text=今天是晴天 +``` + +这是串口明文诊断能力,日志文件会包含儿童输入和 AI 回复,保存、分享与生产环境 +日志策略必须按敏感对话数据处理。 + +## 2. Heap 与任务栈快照 + +`RuntimeDiagnosticsService` 在启动后 5 秒和 30 秒分别输出早期快照,覆盖音频 +初始化、提示音播放和 WiFi 启动的栈峰值;之后每 5 分钟输出一次。诊断使用独立 +priority 2 worker,8KB 任务栈与最多 64 项的任务快照缓冲都放在 PSRAM,避免在 +共享 `esp_timer` 任务中执行全任务枚举和逐项日志。 + +每次快照包含: + +- 内部 heap 当前空闲、历史最小空闲、最大连续块。 +- PSRAM 当前空闲、历史最小空闲、最大连续块。 +- 当前 FreeRTOS 任务数量。 +- 每个任务的状态、优先级和栈高水位。 + +ESP-IDF 的该目标下栈高水位按剩余字节记录;应用任务小于 512 bytes 时日志带 +`LOW` 告警。IDF 的 `ipc0`/`ipc1` 使用 384-byte 门限,避免把实测仍有约 492 bytes +余量的系统 IPC 栈误报为应用风险。示例: + +```text +I RuntimeDiagnostics2: heap internal free=... min=... largest=...; psram ... +I RuntimeDiagnostics2: task=playback state=... priority=5 stack_free_bytes=... +W RuntimeDiagnostics2: task=... stack_free_bytes=420 LOW +``` + +构建配置启用 `CONFIG_FREERTOS_USE_TRACE_FACILITY`,只用于任务快照,不启用运行 +时间统计。诊断暂不自动重启设备,避免把观测策略和产品恢复策略耦合。 + +2026-07-21 最终真机镜像已运行超过 110 秒并完成多轮对话。30 秒活动期内部 heap +约 `free=14539/min=2343/largest=2432`,PSRAM 仍约有 7.38MB;WebSocket transport +最低剩余栈约 2.1KB、friend 约 2.2KB、alarm 约 2.9KB,应用自有任务均高于 +512 bytes。最新复刷中 IDF 自有 `ipc0` 为 484 bytes,使用独立的 384-byte 告警线 +后正常按 info 输出;本轮未发生 panic/watchdog。TLS 已切换到 PSRAM并完成证书 +校验与 WebSocket upgrade, +常驻 6KB PSRAM 提示音 worker 也已复刷确认。 + +栈尾 watchpoint 曾准确捕获 `friend_service2` 在 `NvsFriendStore::Save` 的首个越界 +写入,证明此前随机调度器 panic 来自任务栈破坏。修复后大型好友/闹钟/记忆工作 +对象均放入 PSRAM,friend/alarm 栈提升到 4KB;watchpoint 保持启用作为回归保护。 + +2026-07-21 完整长日志文件的可见窗口为 17 分 54 秒至 45 分 53 秒(约 27 分 +58 秒),包含 6 组五分钟快照。任务数始终为 27;内部 heap 历史最小值稳定在 +1563 bytes,当前空闲随 WakeNet/AEC 模型装卸在约 9.9KB~34KB 变化,最后为 +14.9KB;PSRAM 历史最小值稳定在约 7.37MB。最后一组关键栈余量包括 websocket +1884、friend 2272、alarm 2684、battery 960、power 1176、sys_evt 660、ipc0 +484 bytes,均高于各自门限。165 个电池样本稳定在 4005~4019mV、91%~92%。 +期间无 panic、watchdog、brownout、重启、任务增长或网络重连。 + +真机验收时至少保存启动后 5 秒/30 秒、连续对话后、BLE 配网后、好友模式后、 +4G 切换后和 OTA 失败恢复后的快照。任何任务低于 512 bytes、内部 heap 最小值 +持续下降、最大连续块持续缩小或任务数量持续增长,都先标记失败并保留完整日志。 diff --git a/docs/schedules-and-power.md b/docs/schedules-and-power.md new file mode 100644 index 0000000..82aef07 --- /dev/null +++ b/docs/schedules-and-power.md @@ -0,0 +1,74 @@ +# 定时、闹钟与电源管理 + +> 实现阶段:阶段 9 +> 当前状态:代码、宿主机测试和 ESP-IDF 构建已完成;真机低功耗与唤醒待验收 + +## 1. 模块边界 + +- `ReminderService` 只管理 server 下发的相对定时提醒,使用单调时钟,重启后不持久化。 +- `AlarmService` 管理绝对时间闹钟,规则持久化到 NVS;`AlarmStore` 独立负责 + `alarm_v2` 命名空间、版本和校验和。 +- `ScheduleCoordinator` 统一接收 `set_timer`、`cancel_timer`、`set_alarm`、 + `delete_alarm`、`sync_alarms` 和 `alarm_config`,并解决同一时刻的竞争。 +- `AlertRinger` 通过统一 `PlaybackSession` 异步播放,最长 60 秒;按键、唤醒词或 + server 取消命令都能停止,不直接写 I2S。 +- `IdleService` 只依据用户活动发布控制事件,不自行关闭网络或播放提示。 +- `PowerService` 负责关机前有序停止传感器、提醒和闹钟,再选择最近唤醒时间进入 + light-sleep。 + +## 2. 时间与优先级 + +Idle 参数采用架构文档的正式值: + +1. 无活动 3 分钟:播放一次提示并进入 15 秒响应窗口。 +2. 仍无响应:关闭实时通道。 +3. 无活动 10 分钟:播放告别提示并软关机。 + +同一时刻有多个日程时,闹钟优先于 reminder;同类按稳定的 slot/id 顺序处理。 +首日 20:30 内建闹钟保留,server 同步完成后由正式配置接管。 + +低电量策略: + +- 非充电且电量首次降到 20% 或以下:发布低电量提醒。 +- 非充电且电量降到 10% 或以下:发布软关机请求。 +- 充电状态不触发低电量关机。 + +## 3. 协议与持久化 + +协议字段以根目录 `protocols/websocket_protocol.md` 为准。Reminder 是当前运行周期 +内的相对时间任务;绝对闹钟持久化。NVS 记录包含格式版本、条目数量和校验和, +损坏记录会被拒绝,不会带着未校验数据启动。 + +首日 20:30 内建闹钟使用保留 ID `-203000`。server 在首日流程已经完成时可下发 +`delete_alarm` 删除该 ID;解析器只额外允许这个负数,`0` 和其他负数仍拒绝。 + +闹钟 NVS 记录和 service 保存快照均通过 `MakePsramObject` 在 PSRAM 中创建,避免 +约 2KB 以上持久化结构压入 FreeRTOS 小栈;`alarm_service2` 使用集中定义的 4KB +内部栈预算并由 host 回归门禁约束。好友和记忆持久化采用同一规则。 + +最终休眠只保留最近一次 RTC 唤醒时间。绝对闹钟可由 NVS 恢复;尚未到期的 +Reminder 在深度重启后不会恢复,这是相对定时器的当前产品边界。 + +## 4. 验证状态 + +已完成: + +- 纯逻辑 schedule host 测试。 +- Idle、低电量和状态机行为测试。 +- 12/12 host tests(阶段 9 完成时)。 +- ESP-IDF 5.4.3 全量构建。 +- 大型持久化工作对象 PSRAM 化、friend/alarm 4KB 栈预算和栈尾 watchpoint 构建; + 基础启动与多轮对话超过 110 秒无相关溢出。 +- 长按关机已在真机完成 `ShuttingDown → WiFi stop → sensor stop → final light sleep`; + 旧镜像中 goodbye/close 尚在 transport 队列时 WiFi 已停止,产生两条连接中止 + error。Close 现有界等待 I/O worker drain 后才允许 EffectRouter 继续停网,代码、 + host tests 和 ESP-IDF 构建已通过,等待复刷确认。 + +待真机验证: + +- 闹钟长响、用户取消和与 TTS/通话的抢占。 +- RTC 时间有效性、跨天、时区及首日 20:30 行为。 +- 3 分钟/10 分钟 Idle 全流程。 +- GPIO12 与 RTC timer 的 light-sleep 唤醒。 +- 20% 提示、10% 软关机及充电旁路。 +- 休眠前任务、I2S、网络和传感器是否完全收敛。 diff --git a/docs/sensors.md b/docs/sensors.md new file mode 100644 index 0000000..936b0d2 --- /dev/null +++ b/docs/sensors.md @@ -0,0 +1,123 @@ +# Firmware 2 传感器子系统 + +> 实现阶段:重构路线图阶段 8 +> 协议:`protocols/sensor_event.md` v2.1 +> 当前状态:代码、纯逻辑测试和 ESP-IDF 构建完成,等待真机验收 + +## 1. 模块边界 + +```text +Touch PAD3/9/13/7/8 + └── CapacitiveTouchInput + └── TouchChannel(校准、EMA、阈值、消抖、成对边沿) + └── SensorMessageCodec ──> RealtimeProtocol ──> WebSocket + +BMI270 / I2C0 + └── Bmi270Sensor(配置上传、50Hz、量程和坐标换算) + └── ImuProcessor(IIR、静止门限、批次、重力旁路) + └── SensorMessageCodec ──> RealtimeProtocol ──> WebSocket + +GPIO10 / ADC1_CH9 + └── BatteryMonitor(截尾均值、eFuse ADC 校准、3/2 分压还原) + └── BatteryEstimator(EMA、SOC 曲线、保守充电推断) + └── IBatteryStatusProvider +``` + +`SensorService` 分别使用静态 Touch、IMU 和 Battery 任务,避免 32ms 电池多次采样 +破坏 IMU 的 20ms 周期。IMU 批次和传感器 JSON 直接走数据面,不进入 +`AppEventQueue`。WebSocket 未打开或有界发送队列已满时立即丢弃,不离线缓存。 + +## 2. Touch + +- 物理通道固定映射为 `touch_1`~`touch_5`。 +- 启动稳定 500ms 后采集 10 个样本建立每通道基线与噪声。 +- 阈值为 `baseline + max(5 × noise, 300)`。 +- 非按下状态持续缓慢跟踪基线和噪声,离群样本不参与学习。 +- 原始值使用 7/8 EMA;释放路径绕过 EMA 长尾。 +- Down 使用 4 个越阈样本确认,Up 使用 1 个样本确认。 +- 每个确认的 Down 保证对应一个 Up,Up 包含 `duration_ms`。 + +Touch 任务只配置五个产品通道,不占用 I2C、电池、LED、电源键等 GPIO。 + +## 3. BMI270 与 IMU + +- BMI270 地址 `0x68`,共享 `BorlaS3I2cBus`,总线 400kHz。 +- 配置镜像来自锁定版本 `espressif/esp-dsp 1.8.0` 的 Apache-2.0 官方资产; + `firmware2` 自己实现配置分块上传和传感器读写,不链接旧固件驱动。 +- 加速度量程 ±16g、陀螺仪量程 ±2000°/s,硬件输出和任务轮询均为 50Hz。 +- 驱动统一执行 Y/Z 轴取反,输出单位为 g 和 °/s。 +- IIR 系数 α=0.75;运动时每 5 帧形成一个 100ms 批次。 +- 连续 50 帧合加速度偏差小于 10mg 后停止批次上报;偏差达到 50mg 时恢复。 +- 即将静止时剩余的 1~4 帧会作为短批次发出。 + +当前 `sensor_event.md` v2.1 规定 `samples` 通常为 5 帧、边界短批次为 1~5 +帧,不按承载网络改变消息结构。Wi‑Fi 和 4G/PPP 都发送相同的 100ms JSON +批次;固件不会使用协议中不存在的 50 帧私有扩展。 + +## 4. Gravity 低延迟旁路 + +重力事件使用未滤波加速度模长,直接从 50Hz 任务发送: + +- `< 0.30g` 持续 60ms:`freefall`。 +- 继续失重每 500ms:`freefall_active`。 +- 失重结束后收集 800ms 峰值:1.4g 为 `caught`,4.5g 为 `dropped`, + 7g 为 `severe_impact`。 +- 无前置失重的 4.5g/7g 峰值:`impact`/`severe_impact`。 +- 同类事件冷却 1000ms,Gravity 独立序号从 0 开始。 + +消息包含协议要求的 `gravity_zone=body`、`gravity_action`、`magnitude` 和 +`peak_g`。 + +## 5. 电池 + +- ADC 每 10 秒采集一次;每次 32 点排序,丢弃最高和最低各 8 点。 +- 优先使用芯片 eFuse curve-fitting 校准,缺失时使用原始 12-bit 近似换算。 +- 板端分压按 `VBAT = ADC × 3/2` 还原。 +- 还原后的电压只有处于 2500~4500mV 才视为有效;超界意味着电池未接、ADC + 引脚/分压配置不符或采样故障。无效读数不会进入 EMA/SOC,也会立即把 + `IBatteryStatusProvider` 快照标记为 unavailable,电源服务不得据此触发 + 低电量提示或关机。 +- SOC 使用本项目实测 3000~4090mV 分段曲线。 +- 放电 EMA 权重为 1/5,推断充电时为 3/10。 +- 板卡没有独立 CHRG 引脚,因此 `charging` 只能根据连续电压趋势和高压区保守 + 推断;它必须通过插拔 USB 真机标定,不能视为硬件事实。 + +`IBatteryStatusProvider` 提供带时间戳的线程安全快照,供阶段 9 的低电量和电源 +服务使用。 + +## 6. 自动验证与真机待验 + +```text +Host tests: 17/17 PASS +ESP-IDF 5.4.3 build: PASS +Binary size: 0x248960 +App partition: 0x400000 +Free: 0x1b76a0(约 43%) +``` + +纯逻辑测试覆盖 Touch 配对、阈值、IMU 五帧/短批次、静止与恢复、60ms +freefall、落地分级、协议字段/容量和电池 SOC/充电状态机。 + +真机仍需验证: + +1. 五路通道实际映射、基线、误触率、Down 延迟和长按释放。 +2. BMI270 配置状态、轴向、单位、50Hz 周期和 I2C/ES8311 并发。 +3. 静止停止上报与拿起恢复。 +4. 安全软垫场景下的抛起、接住、跌落和冲击门限。 +5. ADC 与万用表电压误差、SOC 曲线,以及 USB 插入/拔出/充满的 charging 推断。 +6. WebSocket 离线丢弃和长期运行稳定性;在线队列背压已完成基础真机验证。 + +2026-07-21 第三次启动日志中 GPIO10 只得到 0~39mV,还原值不具备单节锂电池 +物理意义,旧逻辑因此在 30 秒检查时误触发 `critical_battery`。代码侧的超界隔离 +和禁止误关机已完成并通过 host/ESP 构建。最终镜像真机记录到 0~93mV 时始终 +保持 unavailable,超过 110 秒未触发低电量提示或软关机。GPIO10、分压网络以及 +测试板是否实际安装电池仍需真机确认。 + +无效电池状态现在只在首次进入时输出一条 warning,后续相同无效样本降为 debug; +采样恢复到有效范围时输出一次恢复日志,避免每 10 秒重复刷屏又保留诊断边沿。 +最新复刷的 51 秒窗口内电池稳定为约 3992mV/90%,未出现电池 warning;最终精度 +仍需用万用表对照。 + +10Hz 传感器文本已改走 WebSocket 独立双槽 latest-wins 通道;多轮对话期间未再 +出现 `command pool exhausted` 或由此导致的断线。离线丢弃和 24h/72h 背压趋势 +仍需专项验证。 diff --git a/docs/startup-reboot-analysis-20260721.md b/docs/startup-reboot-analysis-20260721.md new file mode 100644 index 0000000..adfffd2 --- /dev/null +++ b/docs/startup-reboot-analysis-20260721.md @@ -0,0 +1,82 @@ +# Firmware 2 重复启动崩溃分析(2026-07-21) + +## 1. 现象与结论 + +烧录后应用连续三次在 WebSocket ServerHello 阶段自动重启,第四次暂时进入运行态。 +这不是电源、WiFi、TLS 或 flash 损坏,而是 `websocket2` 任务解析 ServerHello 时 +触发栈金丝雀。第四次同样只剩 196 bytes 栈,只是没有立即命中 watchpoint,不能 +视为正常启动。 + +三次崩溃的共同证据: + +```text +Debug exception reason: Stack canary watchpoint triggered +ServerMessageDispatcher::ParseHello(...) +ServerHello parsed stack_free_bytes=196 +``` + +首次 `Failed to connect to ESP32-S3: No serial data received` 发生在 ROM 下载握手前, +与随后三次应用栈溢出是两个独立问题。 + +## 2. 根因 + +为输出完整 STT/TTS 文本,`ServerCommand` 新增了 1024-byte 固定文本缓冲,使对象 +达到 4672 bytes。`RealtimeProtocol` 的常驻命令对象虽然已经分配在 PSRAM,旧解析 +接口仍让每个 `ParseXxx` 按值返回 `ServerCommand`,编译器因此在 +`websocket2` 的 12288-byte 内部栈上创建完整临时对象。 + +故障镜像的 Xtensa 机器码显示: + +```text +sizeof(ServerCommand) = 4672 +ParseHello entry a1, 0x1280 # 栈帧 4736 bytes +``` + +TLS/WebSocket 读取链已经使用较深栈,叠加该临时对象后只剩 196 bytes,并会根据 +当次调用深度和中断时机随机越过栈尾。因此表现为前三次崩溃、第四次暂时成功。 + +## 3. 修复 + +所有生产解析函数改成 `ParseXxx(root, ServerCommand* output)`,直接重置并写入 +PSRAM 中的 `incoming_command_`: + +- 删除生产代码中的按值 `Parse()` API; +- 删除 `Command()` / `Invalid()` 大对象返回; +- hello、STT、TTS、control、alarm、memory、call 等所有分支原位填充; +- 保留 1023-byte UTF-8 对话文本能力,不通过缩短文本规避问题; +- 为 dispatcher 源文件增加 `-Wframe-larger-than=1024` + `-Werror` 编译门禁。 + +修复后 Xtensa 机器码: + +```text +ParseHello stack frame: 64 bytes +ParseInto stack frame: 32 bytes +所有 dispatcher 函数最大栈帧: 176 bytes +``` + +同时修复日志中暴露的两个非致命问题: + +1. 只有有效 ServerHello 执行 `settimeofday`/`tzset` 后才标记时钟已同步;重启保留 + 的 RTC epoch 不再被误认为已校时,握手前统一显示 `TIME-UNSYNCED`。 +2. WiFi 二进制组件用多次 vprintf 拼接一条日志;formatter 现在只在逻辑行首添加 + 一次 MAC/时间,避免每个片段重复前缀。 + +## 4. 自动验证 + +- Host tests:17/17 PASS; +- `ParseInto` 同一 PSRAM/对象缓冲连续复用测试通过,旧文本不会泄漏到下一命令; +- dispatcher 1KB 编译期栈帧门禁通过; +- ESP-IDF 5.4.3 / ESP32-S3 构建通过; +- 镜像:`0x24b400`,应用分区剩余 `0x1b4c00`(43%); +- SHA256:`2e32a14ea4fd88e787b73762f2a43b14e29a62f1e72d55429827f25c76fa8f0f`。 + +## 5. 待真机验证 + +复刷后必须完成: + +1. 连续冷/热重启至少 10 次,每次都越过 ServerHello、WakeNet ready 并保持 60 秒; +2. `ServerHello parsed stack_free_bytes` 不再是 196,目标至少 2048 bytes; +3. 无 `Stack canary watchpoint`、Guru Meditation 或自动重启; +4. 握手前日志显示 `TIME-UNSYNCED`,握手后切换到 UTC+8 日历毫秒; +5. WiFi 日志每个逻辑行只有一个 MAC/时间前缀; +6. 完成至少三轮 STT/TTS 中文对话,确认输入输出文本完整。 diff --git a/docs/validation-matrix.md b/docs/validation-matrix.md new file mode 100644 index 0000000..0876234 --- /dev/null +++ b/docs/validation-matrix.md @@ -0,0 +1,78 @@ +# Firmware 2 验证矩阵 + +> 更新时间:2026-07-21 +> 说明:✅ 已执行并通过;⏳ 已有代码但需真机/外部服务;— 不适用 + +## 1. 自动验证结果 + +| 验证 | 结果 | 记录 | +|---|---|---| +| Host configure/build | ✅ | CMake 构建成功 | +| Host tests | ✅ | 17/17 PASS(含流式/尾部两阶段打断、唤醒硬打断与关键任务栈预算回归门禁) | +| Server 打断定向回归 | ✅ | 85/85 PASS(含 TTS tail drain、真人语音保留、残余 pre-roll 丢弃) | +| ESP-IDF full build | ✅ | ESP-IDF 5.4.3 / ESP32-S3 | +| 固件镜像 | ✅ | `build/borla-firmware2.bin`, `0x24ace0`; SHA256 `14c7fb88ea2c4ab177e1986fb2efd0d4d91213647ebe6fa15a12f264691270df` | +| 应用分区余量 | ✅ | 4MB 分区,`0x1b5320`,约 43% | +| 静态 D/IRAM 余量 | ✅ | 当前剩余 28345 bytes;静态 IRAM 剩余 1 byte | +| 静态 IRAM 余量 | ⏳ | 当前仅剩 1 byte;构建可用,但后续新增 `IRAM_ATTR` 前必须先回收预算 | +| 第一轮启动栈修复 | ✅ | 真机已越过 playback/connectivity 原崩溃点并完成 DHCP;完整长稳仍待验 | +| esp_timer 栈修复 | ✅ | 第三次真机日志运行至 36 秒无溢出,5/30 秒诊断中剩余栈稳定为 3084 bytes | +| TLS 内存域修复 | ✅ | mbedTLS 改用 PSRAM;真机已完成证书校验、TLS 和 WebSocket upgrade,不再出现 `-0x7F00` | +| 电池无效值保护 | ✅ | 真机 0~93mV 异常采样保持 unavailable,超过 110 秒未触发误关机;实际电压标定仍待验 | +| 提示音常驻 worker | ✅ | 6KB PSRAM 常驻 worker 真机多次播放/重连期间稳定,未再出现任务创建失败 | +| Friend/NVS 栈溢出修复 | ✅ | 栈尾 watchpoint 定位到 `NvsFriendStore::Save`;大记录迁入 PSRAM,friend/alarm 栈提升为 4KB,复刷后未再溢出 | +| WebSocket 背压修复 | ✅ | 遥测 latest-wins、控制槽保留和读公平性已实机验证;多轮对话无命令池耗尽或重连风暴 | +| 首日闹钟删除协议 | ✅ | `3102` 根因为保留 ID `-203000` 被拒;协议/解析/测试修复后真机连接不再报错 | +| ML307 在线探测内存 | ✅ | 强 WiFi 不再周期安装 UART;越过原 36 秒故障点无 UART malloc error | +| 启动日志告警分级 | ✅ | 51 秒真机日志无 `W`/`E`;正常播放节流、电池重复样本和 IPC 阈值已正确分级 | +| 45 分钟运行日志 | ✅ | uptime 到 45:53;48 次 TTS、27 个任务、6 组诊断,无 panic/watchdog/断线/重连,电池 4005~4019mV | +| TTS 下行 pre-roll | ⏳ | 旧镜像 22 个 session 共丢 71 个开头帧;8 帧 PSRAM pre-roll 与边界测试已完成,等待复刷听感/日志 | +| 主动关闭 drain | ⏳ | goodbye→close 现有界等待 transport worker 后才停 WiFi;构建通过,等待复刷确认末尾无 transport error | +| MAC + 日历毫秒日志 | ⏳ | 统一 `ESP_LOG` formatter 已完成并通过 ESP 构建;等待复刷确认校时前/后格式和 UTC+8 日期 | +| 对话输入/输出文本日志 | ⏳ | `stt.text`/`tts sentence_start.text` 协议、解析与 host 测试完成;等待串口确认中文完整性 | +| ServerHello 解析栈修复 | ⏳ | `ParseHello` 栈帧 4736→64 bytes,全部解析器最大 176 bytes且有1KB编译门禁;等待连续启动10次真机确认 | +| 唤醒词打断 | ⏳ | WakeWordDuplex + 本地 abort 已实现;真实时间冷却和 reference-miss 盲区已修复,等待 TTS 中段/尾部真机确认 | +| 自然人声立即打断 | ⏳ | server VAD/ASR 两阶段裁决及 producer-stop→physical-drain tail 采集已实现;等待完整问题与误取消真机复刷 | +| 协议文档先行 | ✅ | feature、memory、stt、远程行为、运行时控制和本地播放生命周期契约已更新 | +| 原工程隔离 | ✅ | `firmware2` 不链接 `firmware/` 源码 | + +## 2. 功能矩阵 + +| 功能 | 代码 | Host/编译 | 真机 | 外部联调 | +|---|---:|---:|---:|---:| +| 启动、状态机、按键、LED | ✅ | ✅ | ⏳ | — | +| 启动关键任务栈与早期诊断 | ✅ | ✅ | ✅ | — | +| Realtime timer/命令池内存安全 | ✅ | ✅ | ✅ | — | +| TLS PSRAM 分配 | ✅ | ✅ | ✅ | ✅ server | +| 提示音常驻 PSRAM worker | ✅ | ✅ | ✅ | — | +| ES8311/I2S/本地提示音 | ✅ | ✅ | ⏳ | — | +| WiFi、凭据、退避、恢复 | ✅ | ✅ | ⏳ | — | +| ML307 LTE/PPP、双网切换 | ✅ | ✅ | ⏳ | ⏳ SIM/运营商 | +| WebSocket v3/TLS/重连 | ✅ | ✅ | ✅ 基础链路 | ✅ hello/多轮对话;⏳ 断网门限/长稳 | +| ServerCommand PSRAM 原位解析 | ✅ | ✅ 栈帧门禁 | ⏳ 连续启动10次 | — | +| MAC/年月日时分秒毫秒日志 | ✅ | ✅ | ⏳ | — | +| STT 输入/TTS 输出文本日志 | ✅ | ✅ | ⏳ | ⏳ server 对话 | +| Opus 上下行、连续对话 | ✅ | ✅ | ✅ 基础链路 | ✅ 多轮对话;⏳ pre-roll 复刷/声学 | +| WakeNet/VAD/AEC/NS/AGC | ✅ | ✅ | ⏳ | — | +| TTS 唤醒词/自然人声打断 | ✅ | ✅ | ⏳ 时延/误取消/续播 | ✅ server 自动回归;⏳ 真机新问题回复 | +| BLE 配网 | ✅ | ✅ | ⏳ | ⏳ 小程序 | +| Touch/BMI270/电池 | ✅ | ✅ | ⏳ | — | +| 无效电池采样禁止误关机 | ✅ | ✅ | ✅ | — | +| Reminder/Alarm/Idle/电源 | ✅ | ✅ | ⏳ | ⏳ server | +| OTA/SHA256/A-B/回滚 | ✅ | ✅ | ⏳ | ⏳ backend/server | +| 双设备通话 | ✅ | ✅ | ⏳ | ⏳ server + 双设备 | +| 好友碰一碰/离线补传 | ✅ | ✅ | ⏳ | ⏳ server + 双设备 | +| 旧好友/设备昵称 NVS 迁移 | ✅ | ✅ | ⏳ | — | +| 激活码顺序播放/重复 | ✅ | ✅ | ⏳ | ⏳ server | +| 记忆缓存/旧分区迁移 | ✅ | ✅ | ⏳ | ⏳ server | +| 远程按键映射/连接提示/遥测 | ✅ | ✅ | ⏳ | ⏳ server | +| 运行时音量/唤醒词/插话/LED | ✅ | ✅ | ⏳ | ⏳ server | +| 鼾声播放/done/轻睡眠闭环 | ✅ | ✅ | ⏳ | ⏳ server | +| goodbye/主动关闭清理 | ✅ | ✅ | ⏳ close drain 复刷 | ⏳ server | +| heap/全任务栈诊断 | ✅ | ✅ | ✅ 启动/多轮对话 | — | +| 24h/72h 稳定性 | — | — | ⏳ | ⏳ server | + +本轮已经具备 ESP32-S3 和当前 server,完成了启动、TLS/hello 和基础多轮对话 +验证。剩余 ⏳ 项需要尚未执行的外设/声学操作、SIM、第二台设备、破坏性测试或 +24h/72h 长稳,不能因代码存在而标记为通过。执行步骤见 +[hardware-validation-checklist.md](hardware-validation-checklist.md)。 diff --git a/docs/voice-frontend.md b/docs/voice-frontend.md new file mode 100644 index 0000000..538fd9f --- /dev/null +++ b/docs/voice-frontend.md @@ -0,0 +1,119 @@ +# Firmware 2 Voice Frontend + +> 实现阶段:重构路线图阶段 6 +> 当前状态:两阶段自然插话代码、Host 测试和 ESP-IDF 构建完成,等待真机声学验收 + +## 1. 设计边界 + +业务层只选择 `AudioPolicy`,不能直接组合 WakeNet、VAD、AEC、NS 或 AGC 开关。 +`VoiceFrontend` 是每个麦克风帧唯一的有状态处理器,但它不负责判断“自然人声是否 +应该打断 TTS”。自然插话的最终裁决权只在 server。 + +| AudioPolicy | WakeNet | AEC | 上行 | 用途 | +|---|---:|---:|---:|---| +| `kWakeWordOnly` | 是 | 否 | 否 | 空闲唤醒 | +| `kWakeWordDuplex` | 是 | 是 | 否 | TTS 中只允许唤醒词硬打断 | +| `kConversationCapture` | 否 | 否 | 是 | 正常提问与停说 VAD | +| `kBargeInDuplex` | 是 | 是 | 是 | TTS 中持续上传 AEC 后音频 | +| `kCallDuplex` | 否 | 是 | 是 | 双设备通话 | + +`kWakeWordDuplex` 保证故事、音乐或 server 临时关闭自然插话时,“你好播乐”仍可 +在设备说话期间命中。`kBargeInDuplex` 只提供声学前处理和低延迟上行,不在设备端 +使用 RMS、峰值、相关性或固定帧数发布自然插话事件。 + +## 2. 模型、缓冲和 AEC + +- ESP-SR 固定为 `2.4.6`;WakeNet 产品模型位于 + `firmware2/model_data/wn9l_ni3hao3bo1le4/`。 +- 构建阶段重新打包 `srmodels.bin`,模型分区位于 flash `0x820000`。 +- 正常监听的能量 VAD 连续 2 帧进入 speech,连续 13 帧静音后发布 + `ConversationStopRequested`;60ms 帧下尾静音约 780ms。 +- `CapturePipeline` 分离原始 16k PCM 与处理后 16k PCM 缓冲。AEC/NS/AGC 的输入、 + 输出不再别名到同一块内存;Opus 编码只读取处理后缓冲。 +- 扬声器实际写 I2S 前的 24k PCM 按软件音量缩放后复制到 reference sink,再转换 + 为 16k,由 Voice Frontend 单一消费。 +- Duplex 策略使用 `AEC_MODE_VOIP_HIGH_PERF/filter=4`。AEC handle 跨 TTS 保温, + 但不再人为插入固定 60ms reference 延迟,也不再维护跨帧相关性搜索历史。 +- reference 缺失时仍会记录指标;自然插话正确性不能依赖设备端对单帧 AEC 输出的 + 二分类。即使 reference FIFO 某一帧暂时为空,也继续用零 reference 完成 DSP 并把 + 输出送入 WakeNet,不能让一次 reference miss 形成 60ms 唤醒盲区。 +- WakeNet 命中后的 2 秒防重复窗口使用单调时钟截止时间。不能使用“已送入 WakeNet + 的帧数”计数,因为正常提问阶段不会运行 WakeNet,帧计数会冻结并错误屏蔽下一次 + TTS 开头约 2 秒。 + +## 3. 两条打断路径 + +### 3.1 唤醒词硬打断 + +这是设备本地、无需等待 server ASR 的确定性路径: + +```text +WakeNet 命中“你好播乐” + → 立即取消本地 playback + → abort(reason=wake_word_detected) + → listen:start + → 进入 ConversationCapture +``` + +播放 session/generation 会拒绝取消后迟到的旧 TTS 帧。 + +### 3.2 自然人声两阶段打断 + +```text +TTS 播放 + kBargeInDuplex + → 固件逐个发送 60ms AEC 后 Opus 帧 + → server VAD 命中 + → barge_in:candidate + → 固件暂停当前播放,保留队列/session,继续 AEC 上行 + → server ASR + 当前/近期 TTS 文本回声校验 + ├─ rejected → 固件从原位置续播 + └─ confirmed → 固件取消旧播放;server 终止旧生成并处理新问题 +``` + +关键约束: + +- `candidate` 只是可撤销的静音门控,不改变设备的 Speaking 状态。 +- 固件暂停时保留已经取出的当前帧和后续队列;server 同时暂停下行生产,避免验证 + 窗口内把设备固定队列灌满。 +- `confirmed` 后设备不再回发 `abort` 或 `listen:start`。server 已持有完整插话音频 + 和识别文本,由 server 直接终止旧回复并启动新问题。 +- `rejected`、TTS `stop`、新 TTS `start`、取消播放和断线都会清除遗留暂停状态。 +- TTS 插话上行使用单帧二进制包,不经过普通监听的 5 帧/约 300ms 批处理。 +- `tts:stop` 只表示 server 已结束下行生产,不表示设备扬声器队列已经排空。支持 + `barge_in_two_phase` 的连接在 `PlaybackState::kDraining` 期间继续保持 + `kBargeInDuplex`、AEC 和单帧上行;只有设备播放真正排空并发送 `listen:start` + 后,server 与固件才一起关闭 TTS 尾部采集窗口。 +- 尾部边界到达时,若 server VAD 已经捕获真人语音,则保留采集帧和当前 TTS 文本 + 继续 ASR/回声过滤;若没有活动语音,则丢弃扬声器尾音 pre-roll,避免普通 ASR + 把残留音频识别成“你觉得呢?”之类的伪输入。 + +旧的 `BargeInVoiceDetector`、本地能量阈值/连续三帧确认、0~120ms 相关性搜索、 +固定 60ms reference 延迟和 `speech_barge_in_detected` 事件均已删除。真机日志已经 +证明这些本地启发式会把 AEC 残余 TTS 当成真人,继续调阈值无法建立可靠的最终裁决。 + +## 4. 自动验证与待验 + +自动验证已覆盖: + +- `candidate` 只暂停,不取消、不发送 abort/listen; +- `rejected` 原位恢复,`confirmed` 清空旧 session; +- WakeNet speaking 硬打断路径保持独立; +- WakeNet 防重复窗口使用真实时间,AEC reference miss 不跳过唤醒词检测; +- `barge_in` 三种 server 消息解析与非法状态拒绝; +- TTS 插话单帧上行和正常监听批量上行; +- TTS producer stop 到物理播放 drain 之间继续两阶段采集,drain 后区分并保留真人 + 语音或丢弃扬声器残留; +- raw/processed 捕获缓冲分离; +- server 候选期暂停下行、回声拒绝恢复、有效 ASR 确认并处理新问题。 + +当前结果:firmware2 Host tests 17/17;server 打断相关定向回归 85/85;ESP-IDF +5.4.3 ESP32-S3 全量构建通过。 + +真机仍需验证: + +- TTS 中“你好播乐”能立即硬打断; +- 0.5m/1m 自然说新问题时,先暂停、确认后取消旧回复并回答新内容; +- 无人、空调、风扇、走动、敲击场景只产生短暂 candidate/rejected,不能取消旧回复; +- rejected 后音频从暂停点连续恢复,无爆音、重复或队列溢出; +- candidate 到静音、confirmed 到新回复的端到端时延; +- AEC CPU、内部 RAM、任务栈和 watchdog 长稳。 diff --git a/host_tests/CMakeLists.txt b/host_tests/CMakeLists.txt new file mode 100644 index 0000000..1428f77 --- /dev/null +++ b/host_tests/CMakeLists.txt @@ -0,0 +1,268 @@ +cmake_minimum_required(VERSION 3.16) +project(borla_firmware2_host_tests LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +enable_testing() + +find_package(PkgConfig REQUIRED) +pkg_check_modules(CJSON REQUIRED IMPORTED_TARGET libcjson) + +add_executable( + state_reducer_test + state_reducer_test.cc + ../main/core/app_effect.cc + ../main/core/app_event.cc + ../main/core/runtime_state.cc + ../main/core/state_reducer.cc +) + +target_include_directories(state_reducer_test PRIVATE ../main) +target_compile_options(state_reducer_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME state_reducer_test COMMAND state_reducer_test) + +add_executable( + effect_router_test + effect_router_test.cc + ../main/core/app_effect.cc + ../main/core/runtime_state.cc + ../main/adapters/effect_router.cc +) + +target_include_directories(effect_router_test PRIVATE ../main) +target_compile_options(effect_router_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME effect_router_test COMMAND effect_router_test) + +add_executable( + playback_controller_test + playback_controller_test.cc + ../main/audio/playback_controller.cc +) + +target_include_directories(playback_controller_test PRIVATE ../main) +target_compile_options(playback_controller_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME playback_controller_test COMMAND playback_controller_test) + +add_executable( + packed_opus_reader_test + packed_opus_reader_test.cc + ../main/audio/packed_opus_reader.cc +) + +target_include_directories(packed_opus_reader_test PRIVATE ../main) +target_compile_options(packed_opus_reader_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME packed_opus_reader_test COMMAND packed_opus_reader_test) + +add_executable( + connectivity_policy_test + connectivity_policy_test.cc + ../main/connectivity/connectivity_policy.cc + ../main/connectivity/reconnect_backoff.cc +) + +target_include_directories(connectivity_policy_test PRIVATE ../main) +target_compile_options(connectivity_policy_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME connectivity_policy_test COMMAND connectivity_policy_test) + +add_executable( + dual_network_policy_test + dual_network_policy_test.cc + ../main/connectivity/dual_network_policy.cc +) + +target_include_directories(dual_network_policy_test PRIVATE ../main) +target_compile_options( + dual_network_policy_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME dual_network_policy_test + COMMAND dual_network_policy_test) + +add_executable( + ml307_at_parser_test + ml307_at_parser_test.cc + ../main/connectivity/ml307_at_parser.cc +) + +target_include_directories(ml307_at_parser_test PRIVATE ../main) +target_compile_options( + ml307_at_parser_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME ml307_at_parser_test + COMMAND ml307_at_parser_test) + +add_executable( + friend_types_test + friend_types_test.cc + ../main/friend/friend_types.cc +) + +target_include_directories(friend_types_test PRIVATE ../main) +target_compile_options( + friend_types_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME friend_types_test COMMAND friend_types_test) + +add_executable( + realtime_codec_test + realtime_codec_test.cc + ../main/core/playback_types.cc + ../main/core/remote_behavior.cc + ../main/memory/memory_types.cc + ../main/protocol/protocol_message_builder.cc + ../main/protocol/server_message_dispatcher.cc +) + +target_include_directories(realtime_codec_test PRIVATE ../main) +target_link_libraries(realtime_codec_test PRIVATE PkgConfig::CJSON) +target_compile_options(realtime_codec_test PRIVATE -Wall -Wextra -Werror) +set_source_files_properties( + ../main/protocol/server_message_dispatcher.cc + PROPERTIES COMPILE_OPTIONS "-Wframe-larger-than=1024") + +add_test(NAME realtime_codec_test COMMAND realtime_codec_test) + +add_executable( + websocket_uri_test + websocket_uri_test.cc + ../main/protocol/websocket_uri.cc +) + +target_include_directories(websocket_uri_test PRIVATE ../main) +target_compile_options(websocket_uri_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME websocket_uri_test COMMAND websocket_uri_test) + +add_executable( + audio_data_plane_test + audio_data_plane_test.cc + ../main/audio/pcm_rate_converter.cc + ../main/protocol/binary_audio_protocol.cc +) + +target_include_directories(audio_data_plane_test PRIVATE ../main) +target_compile_options(audio_data_plane_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME audio_data_plane_test COMMAND audio_data_plane_test) + +add_executable( + voice_activity_detector_test + voice_activity_detector_test.cc + ../main/audio/voice_activity_detector.cc +) + +target_include_directories(voice_activity_detector_test PRIVATE ../main) +target_compile_options( + voice_activity_detector_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME voice_activity_detector_test + COMMAND voice_activity_detector_test) + +add_executable( + ble_provisioning_codec_test + ble_provisioning_codec_test.cc + ../main/provisioning/ble_provisioning_codec.cc +) + +target_include_directories(ble_provisioning_codec_test PRIVATE ../main) +target_link_libraries( + ble_provisioning_codec_test PRIVATE PkgConfig::CJSON) +target_compile_options( + ble_provisioning_codec_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME ble_provisioning_codec_test + COMMAND ble_provisioning_codec_test) + +add_executable( + sensor_pipeline_test + sensor_pipeline_test.cc + ../main/sensor/battery_estimator.cc + ../main/sensor/imu_processor.cc + ../main/sensor/sensor_message_codec.cc + ../main/sensor/sensor_types.cc + ../main/sensor/touch_channel.cc +) + +target_include_directories(sensor_pipeline_test PRIVATE ../main) +target_compile_options( + sensor_pipeline_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME sensor_pipeline_test + COMMAND sensor_pipeline_test) + +add_executable( + schedule_test + schedule_test.cc + ../main/schedule/alarm_schedule.cc + ../main/schedule/reminder_schedule.cc +) + +target_include_directories(schedule_test PRIVATE ../main) +target_compile_options(schedule_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME schedule_test COMMAND schedule_test) + +add_executable( + trace_context_test + trace_context_test.cc + ../main/diagnostics/trace_context.cc +) + +target_include_directories(trace_context_test PRIVATE ../main) +target_compile_options( + trace_context_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME trace_context_test COMMAND trace_context_test) + +add_executable( + ota_endpoint_test + ota_endpoint_test.cc + ../main/ota/ota_endpoint.cc +) + +target_include_directories(ota_endpoint_test PRIVATE ../main) +target_compile_options( + ota_endpoint_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME ota_endpoint_test COMMAND ota_endpoint_test) + +add_executable( + ota_response_parser_test + ota_response_parser_test.cc + ../main/ota/ota_endpoint.cc + ../main/ota/ota_response_parser.cc + ../main/ota/ota_types.cc +) + +target_include_directories(ota_response_parser_test PRIVATE ../main) +target_link_libraries( + ota_response_parser_test PRIVATE PkgConfig::CJSON) +target_compile_options( + ota_response_parser_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME ota_response_parser_test + COMMAND ota_response_parser_test) + +add_executable( + task_stack_budget_test + task_stack_budget_test.cc +) + +target_include_directories(task_stack_budget_test PRIVATE ../main) +target_compile_options( + task_stack_budget_test PRIVATE -Wall -Wextra -Werror) + +add_test( + NAME task_stack_budget_test + COMMAND task_stack_budget_test) diff --git a/host_tests/audio_data_plane_test.cc b/host_tests/audio_data_plane_test.cc new file mode 100644 index 0000000..ed93bbb --- /dev/null +++ b/host_tests/audio_data_plane_test.cc @@ -0,0 +1,185 @@ +#include "audio/downlink_preroll_buffer.h" +#include "audio/pcm_rate_converter.h" +#include "protocol/binary_audio_protocol.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace borla; + +class CollectingVisitor final : public IBinaryAudioFrameVisitor { +public: + bool OnOpusFrame(const uint8_t* data, size_t size) override + { + frames.emplace_back(data, data + size); + return true; + } + + std::vector> frames; +}; + +void TestExactFrameRateConversion() +{ + std::array input{}; + std::array output{}; + for (size_t index = 0; index < input.size(); ++index) { + input[index] = static_cast(index); + } + + Pcm24kTo16kConverter converter; + assert(converter.Convert( + input.data(), input.size(), output.data(), output.size())); + assert(output[0] == 0); + assert(output[1] == 1); + assert(output[2] == 3); + assert(output[3] == 4); + assert(output.back() == 1438); + assert(!converter.Convert( + input.data(), input.size() - 1, output.data(), output.size())); +} + +void TestBatchRoundTrip() +{ + BinaryAudioBatchBuilder builder; + const std::array first{1, 2, 3}; + const std::array second{4, 5, 6, 7}; + assert(builder.Push(first.data(), first.size())); + assert(builder.Push(second.data(), second.size())); + + std::array packet{}; + size_t packet_size = 0; + assert(builder.Build(packet.data(), packet.size(), &packet_size)); + assert(packet[0] == kBinaryAudioTypeOpus); + assert(packet[1] == kBinaryAudioFlagBatch); + assert(packet_size == 4 + 2 + first.size() + 2 + second.size()); + + CollectingVisitor visitor; + size_t frames = 0; + assert(VisitBinaryAudioPacket( + packet.data(), packet_size, visitor, &frames)); + assert(frames == 2); + assert(visitor.frames[0] == + std::vector(first.begin(), first.end())); + assert(visitor.frames[1] == + std::vector(second.begin(), second.end())); +} + +void TestSingleAndMalformedPackets() +{ + const std::array payload{9, 8, 7}; + std::array built{}; + size_t built_size = 0; + assert(BuildBinaryAudioSingleFrame( + payload.data(), payload.size(), + built.data(), built.size(), &built_size)); + assert(built_size == 7); + assert(built[0] == kBinaryAudioTypeOpus); + assert(built[1] == 0); + + const std::array single{ + 0, 0, 0, 3, 9, 8, 7}; + assert(std::equal(built.begin(), built.begin() + built_size, + single.begin())); + CollectingVisitor visitor; + assert(VisitBinaryAudioPacket( + single.data(), single.size(), visitor)); + assert(visitor.frames.size() == 1); + + auto malformed = single; + malformed[3] = 4; + CollectingVisitor invalid_visitor; + assert(!VisitBinaryAudioPacket( + malformed.data(), malformed.size(), invalid_visitor)); + + const std::array zero_frame{ + 0, 1, 0, 4, 0, 0, 1, 2}; + assert(!VisitBinaryAudioPacket( + zero_frame.data(), zero_frame.size(), invalid_visitor)); + + const std::array valid_then_broken{ + 0, 1, 0, 7, 0, 2, 1, 2, 0, 3, 9}; + CollectingVisitor atomic_visitor; + assert(!VisitBinaryAudioPacket( + valid_then_broken.data(), + valid_then_broken.size(), + atomic_visitor)); + assert(atomic_visitor.frames.empty()); +} + +void TestBatchCapacity() +{ + BinaryAudioBatchBuilder builder; + std::array frame{}; + for (size_t index = 0; + index < kBinaryAudioBatchFrames; + ++index) { + assert(builder.Push(frame.data(), frame.size())); + } + assert(builder.Full()); + assert(!builder.Push(frame.data(), frame.size())); + builder.Reset(); + assert(builder.Empty()); +} + +void TestDownlinkPrerollPreservesOrderAndSessionIsolation() +{ + DownlinkPrerollBuffer preroll; + const std::array first{1, 2, 3}; + const std::array second{4, 5}; + assert(preroll.Push(41, first.data(), first.size())); + assert(preroll.Push(41, second.data(), second.size())); + assert(preroll.session_id() == 41); + assert(preroll.frame_count() == 2); + assert(preroll.FrameSize(0) == first.size()); + assert(std::memcmp( + preroll.FrameData(0), first.data(), first.size()) == 0); + assert(std::memcmp( + preroll.FrameData(1), second.data(), second.size()) == 0); + + assert(preroll.Push(42, second.data(), second.size())); + assert(preroll.session_id() == 42); + assert(preroll.frame_count() == 1); + assert(preroll.FrameData(1) == nullptr); + + preroll.Reset(); + assert(preroll.session_id() == 0); + assert(preroll.frame_count() == 0); +} + +void TestDownlinkPrerollIsBounded() +{ + DownlinkPrerollBuffer preroll; + std::array frame{}; + for (size_t index = 0; + index < DownlinkPrerollBuffer::kCapacity; + ++index) { + frame[0] = static_cast(index); + assert(preroll.Push(7, frame.data(), frame.size())); + } + assert(!preroll.Push(7, frame.data(), frame.size())); + assert(!preroll.Push(0, frame.data(), frame.size())); + assert(!preroll.Push(7, nullptr, frame.size())); + std::array oversized{}; + assert(!preroll.Push(7, oversized.data(), oversized.size())); +} + +} // namespace + +int main() +{ + TestExactFrameRateConversion(); + TestBatchRoundTrip(); + TestSingleAndMalformedPackets(); + TestBatchCapacity(); + TestDownlinkPrerollPreservesOrderAndSessionIsolation(); + TestDownlinkPrerollIsBounded(); + std::cout << "audio data plane tests passed\n"; + return 0; +} diff --git a/host_tests/ble_provisioning_codec_test.cc b/host_tests/ble_provisioning_codec_test.cc new file mode 100644 index 0000000..a245d41 --- /dev/null +++ b/host_tests/ble_provisioning_codec_test.cc @@ -0,0 +1,141 @@ +#include "provisioning/ble_provisioning_codec.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace borla; + +class ChunkCollector final : public IBleChunkVisitor { +public: + bool OnBleChunk(const uint8_t* data, size_t size) override + { + chunks.emplace_back(data, data + size); + return true; + } + + std::vector> chunks; +}; + +void TestCredentialAssemblyAndValidation() +{ + BleChunkAssembler assembler; + const std::string json = + R"({"ssid":"Home","password":"secret123"})"; + const std::array first{ + 0, 0, '{', '"', 's', 's', 'i', 'd', '"', ':', '"', 'H'}; + std::vector second{1, 1}; + second.insert( + second.end(), json.begin() + 10, json.end()); + + assert( + assembler.Push(first.data(), first.size()) == + BleChunkAssemblyResult::kAccepted); + assert( + assembler.Push(second.data(), second.size()) == + BleChunkAssemblyResult::kComplete); + WifiCredential credential; + assert(ParseProvisioningCredential( + assembler.data(), assembler.size(), &credential)); + assert(std::strcmp(credential.ssid.data(), "Home") == 0); + assert(std::strcmp( + credential.password.data(), "secret123") == 0); + + const std::array out_of_order{2, 1, 'x'}; + assert( + assembler.Push( + out_of_order.data(), out_of_order.size()) == + BleChunkAssemblyResult::kInvalid); +} + +void TestChunkRoundTripAtDefaultMtu() +{ + const std::string json(97, 'x'); + ChunkCollector collector; + assert(VisitBleNotificationChunks( + json.data(), json.size(), 23, collector)); + assert(collector.chunks.size() == 6); + + BleChunkAssembler assembler; + for (size_t index = 0; + index < collector.chunks.size(); + ++index) { + const auto& chunk = collector.chunks[index]; + const auto expected = + index + 1 == collector.chunks.size() + ? BleChunkAssemblyResult::kComplete + : BleChunkAssemblyResult::kAccepted; + assert(assembler.Push(chunk.data(), chunk.size()) == expected); + } + assert(assembler.size() == json.size()); + assert(std::memcmp( + assembler.data(), json.data(), json.size()) == 0); +} + +void TestJsonContractsHidePasswords() +{ + DeviceIdentity identity; + std::strcpy(identity.mac, "AA:BB:CC:DD:EE:FF"); + std::strcpy(identity.app_version, "2.0.0-dev"); + std::strcpy(identity.board, "borla_s3"); + std::array output{}; + size_t size = 0; + assert(BuildProvisioningDeviceInfoJson( + identity, output.data(), output.size(), &size)); + assert(std::strstr(output.data(), "AA:BB:CC:DD:EE:FF")); + assert(std::strstr(output.data(), "borla_s3")); + + std::array saved{}; + assert(saved[0].Set("Home", "top-secret")); + assert(saved[1].Set("Office", "also-secret")); + assert(BuildProvisioningSavedWifiJson( + saved.data(), saved.size(), + output.data(), output.size(), &size)); + assert(std::strstr(output.data(), "\"ssid\":\"Home\"")); + assert(std::strstr(output.data(), "\"index\":1")); + assert(std::strstr(output.data(), "secret") == nullptr); + assert(std::strstr(output.data(), "password") == nullptr); +} + +void TestScanAndResultJson() +{ + std::array networks{}; + std::strcpy(networks[0].ssid.data(), "Home"); + networks[0].rssi_dbm = -42; + networks[0].auth_mode = 3; + std::strcpy(networks[1].ssid.data(), "Guest"); + networks[1].rssi_dbm = -70; + + std::array output{}; + size_t size = 0; + assert(BuildProvisioningScanJson( + networks.data(), networks.size(), + output.data(), output.size(), &size)); + assert(std::strstr(output.data(), "\"rssi\":-42")); + assert(std::strstr(output.data(), "\"auth\":3")); + + assert(BuildProvisioningResultJson( + false, "password_wrong", + output.data(), output.size(), &size)); + assert(std::strcmp( + output.data(), + R"({"success":false,"error":"password_wrong"})") == 0); +} + +} // namespace + +int main() +{ + TestCredentialAssemblyAndValidation(); + TestChunkRoundTripAtDefaultMtu(); + TestJsonContractsHidePasswords(); + TestScanAndResultJson(); + std::cout << "BLE provisioning codec tests passed\n"; + return 0; +} diff --git a/host_tests/connectivity_policy_test.cc b/host_tests/connectivity_policy_test.cc new file mode 100644 index 0000000..b442e46 --- /dev/null +++ b/host_tests/connectivity_policy_test.cc @@ -0,0 +1,185 @@ +#include "connectivity/connectivity_policy.h" +#include "connectivity/wifi_types.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +const ConnectivityAction* FindAction( + const ConnectivityPolicyResult& result, + ConnectivityActionType type) +{ + for (size_t index = 0; index < result.action_count; ++index) { + if (result.actions[index].type == type) { + return &result.actions[index]; + } + } + return nullptr; +} + +ReconnectBackoffConfig DeterministicConfig() +{ + return ReconnectBackoffConfig{ + 100, + 500, + 2, + 0, + }; +} + +void TestCredentialValidation() +{ + WifiCredential credential; + assert(!credential.Set("", "password")); + assert(credential.Set("borla-test", "")); + assert(credential.IsValid()); + + const char too_long_ssid[] = + "123456789012345678901234567890123"; + assert(!credential.Set(too_long_ssid, "password")); +} + +void TestBackoffCapsAndResets() +{ + ReconnectBackoff backoff(DeterministicConfig()); + assert(backoff.NextDelayMs(0) == 100); + assert(backoff.NextDelayMs(0) == 200); + assert(backoff.NextDelayMs(0) == 400); + assert(backoff.NextDelayMs(0) == 500); + assert(backoff.NextDelayMs(0) == 500); + assert(backoff.attempt_count() == 5); + + backoff.Reset(); + assert(backoff.attempt_count() == 0); + assert(backoff.NextDelayMs(0) == 100); +} + +void TestMissingCredentialsRequestsProvisioning() +{ + ConnectivityPolicy policy(DeterministicConfig()); + const ConnectivityPolicyResult result = policy.Start(0); + assert( + policy.state() == + ConnectivityPolicyState::kCredentialsMissing); + assert( + FindAction( + result, + ConnectivityActionType::kRequestProvisioning) != nullptr); + + assert(policy.Start(3).action_count == 0); + const ConnectivityPolicyResult stop = policy.Stop(); + assert( + FindAction(stop, ConnectivityActionType::kStopTransport) != + nullptr); + assert(policy.state() == ConnectivityPolicyState::kStopped); +} + +void TestConnectDisconnectAndRecovery() +{ + ConnectivityPolicy policy(DeterministicConfig()); + + ConnectivityPolicyResult result = policy.Start(2); + assert( + FindAction(result, ConnectivityActionType::kStartTransport) != + nullptr); + assert(policy.Start(2).action_count == 0); + + result = policy.OnTransportReady(); + const ConnectivityAction* connect = + FindAction(result, ConnectivityActionType::kConnectCredential); + assert(connect != nullptr); + assert(connect->credential_index == 0); + + result = policy.OnGotIp(); + assert( + FindAction(result, ConnectivityActionType::kPublishConnected) != + nullptr); + assert(policy.state() == ConnectivityPolicyState::kOnline); + assert(policy.OnGotIp().action_count == 0); + + result = policy.OnDisconnected(201, 0); + assert( + FindAction( + result, + ConnectivityActionType::kPublishDisconnected) != nullptr); + const ConnectivityAction* retry = + FindAction(result, ConnectivityActionType::kScheduleRetry); + assert(retry != nullptr); + assert(retry->delay_ms == 100); + assert(policy.credential_index() == 1); + + assert(policy.OnDisconnected(202, 0).action_count == 0); + result = policy.OnRetryElapsed(); + connect = + FindAction(result, ConnectivityActionType::kConnectCredential); + assert(connect != nullptr); + assert(connect->credential_index == 1); + + result = policy.OnGotIp(); + assert( + FindAction(result, ConnectivityActionType::kPublishConnected) != + nullptr); + assert(policy.retry_attempt_count() == 0); + assert(policy.last_disconnect_reason() == 201); +} + +void TestTransportFailureUsesBackoff() +{ + ConnectivityPolicy policy(DeterministicConfig()); + policy.Start(1); + + ConnectivityPolicyResult result = + policy.OnTransportStartFailed(0); + const ConnectivityAction* retry = + FindAction(result, ConnectivityActionType::kScheduleRetry); + assert(retry != nullptr); + assert(retry->delay_ms == 100); + assert(!policy.transport_ready()); + + result = policy.OnRetryElapsed(); + assert( + FindAction(result, ConnectivityActionType::kStartTransport) != + nullptr); + assert( + policy.state() == + ConnectivityPolicyState::kStartingTransport); +} + +void TestStopRejectsLateDriverEvents() +{ + ConnectivityPolicy policy(DeterministicConfig()); + policy.Start(1); + policy.OnTransportReady(); + policy.OnGotIp(); + + const ConnectivityPolicyResult result = policy.Stop(); + assert( + FindAction(result, ConnectivityActionType::kCancelRetry) != + nullptr); + assert( + FindAction(result, ConnectivityActionType::kStopTransport) != + nullptr); + assert(policy.state() == ConnectivityPolicyState::kStopped); + assert(policy.OnGotIp().action_count == 0); + assert(policy.OnDisconnected(1, 0).action_count == 0); + assert(policy.OnRetryElapsed().action_count == 0); +} + +} // namespace + +int main() +{ + TestCredentialValidation(); + TestBackoffCapsAndResets(); + TestMissingCredentialsRequestsProvisioning(); + TestConnectDisconnectAndRecovery(); + TestTransportFailureUsesBackoff(); + TestStopRejectsLateDriverEvents(); + + std::cout << "connectivity policy tests passed\n"; + return 0; +} diff --git a/host_tests/dual_network_policy_test.cc b/host_tests/dual_network_policy_test.cc new file mode 100644 index 0000000..69bbf37 --- /dev/null +++ b/host_tests/dual_network_policy_test.cc @@ -0,0 +1,206 @@ +#include "connectivity/dual_network_policy.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +bool Has( + const DualNetworkPolicyResult& result, + DualNetworkActionType type) +{ + for (size_t index = 0; index < result.action_count; ++index) { + if (result.actions[index].type == type) { + return true; + } + } + return false; +} + +DualNetworkPolicyConfig Config() +{ + return {30000, -80, 3, 2, 120000}; +} + +void TestMissingWifiRequestsProvisioning() +{ + DualNetworkPolicy policy(Config()); + const auto result = policy.Start(false, 0); + assert(Has(result, DualNetworkActionType::kRequestProvisioning)); + assert(policy.selected_bearer() == NetworkBearer::kNone); +} + +void TestDisconnectedWifiFailsOver() +{ + DualNetworkPolicy policy(Config()); + assert(Has(policy.Start(true, 100), + DualNetworkActionType::kStartWifi)); + policy.OnWifiOnline(200); + policy.OnWifiDisconnected(1000); + + assert(policy.OnMonitor( + 30999, -127, ModemPresence::kPresent).action_count == 0); + const auto result = + policy.OnMonitor(31000, -127, ModemPresence::kPresent); + assert(Has(result, DualNetworkActionType::kStopWifi)); + assert(Has(result, DualNetworkActionType::kStartCellular)); + assert(Has(result, DualNetworkActionType::kRequestReconnect)); + assert(policy.selected_bearer() == NetworkBearer::kCellular); +} + +void TestWeakWifiRequiresConsecutiveSamples() +{ + DualNetworkPolicy policy(Config()); + policy.Start(true, 0); + policy.OnWifiOnline(100); + assert(policy.OnMonitor( + 1000, -85, ModemPresence::kPresent).action_count == 0); + assert(policy.OnMonitor( + 2000, -85, ModemPresence::kPresent).action_count == 0); + policy.OnMonitor(2500, -60, ModemPresence::kPresent); + assert(policy.weak_sample_count() == 0); + policy.OnMonitor(3000, -90, ModemPresence::kPresent); + policy.OnMonitor(4000, -90, ModemPresence::kPresent); + const auto result = + policy.OnMonitor(5000, -90, ModemPresence::kPresent); + assert(Has(result, DualNetworkActionType::kNotifyDisconnected)); + assert(policy.selected_bearer() == NetworkBearer::kCellular); +} + +void TestAbsentModemPreventsAutomaticAndManualSwitch() +{ + DualNetworkPolicy policy(Config()); + policy.Start(true, 0); + policy.OnWifiOnline(100); + policy.OnWifiDisconnected(1000); + assert(policy.OnMonitor( + 40000, -127, ModemPresence::kAbsent).action_count == 0); + const auto manual = + policy.RequestManualSwitch(41000, ModemPresence::kAbsent); + assert(Has( + manual, + DualNetworkActionType::kPromptCellularUnavailable)); + assert(policy.selected_bearer() == NetworkBearer::kWifi); +} + +void TestCellularFailureFallsBackToWifi() +{ + DualNetworkPolicy policy(Config()); + policy.Start(true, 0); + policy.RequestManualSwitch(100, ModemPresence::kPresent); + policy.OnCellularOnline(200); + const auto result = policy.OnCellularDisconnected(300); + assert(Has(result, DualNetworkActionType::kStopCellular)); + assert(Has(result, DualNetworkActionType::kStartWifi)); + assert(Has(result, DualNetworkActionType::kRequestReconnect)); + assert(policy.selected_bearer() == NetworkBearer::kWifi); +} + +} // namespace + +void TestModemSwitchSensingAnnouncements() +{ + DualNetworkPolicy policy(Config()); + policy.Start(true, 0); + + // Unknown probes (UART driver unavailable) must never be read as OFF. + assert(policy.OnModemPresence( + ModemPresence::kUnknown, 1000).action_count == 0); + assert(policy.stable_modem_presence() == ModemPresence::kUnknown); + + // First usable reading with the switch ON -> boot announcement, once. + assert(Has(policy.OnModemPresence(ModemPresence::kPresent, 2000), + DualNetworkActionType::kPromptCellularBootOn)); + assert(policy.stable_modem_presence() == ModemPresence::kPresent); + assert(policy.OnModemPresence( + ModemPresence::kPresent, 5000).action_count == 0); + + // ON -> OFF needs two consecutive misses (UART jitter debounce). + assert(policy.OnModemPresence( + ModemPresence::kAbsent, 8000).action_count == 0); + assert(Has(policy.OnModemPresence(ModemPresence::kAbsent, 11000), + DualNetworkActionType::kPromptCellularOff)); + assert(policy.stable_modem_presence() == ModemPresence::kAbsent); + assert(policy.OnModemPresence( + ModemPresence::kAbsent, 14000).action_count == 0); + + // A single miss followed by a hit must not announce OFF at all. + assert(Has(policy.OnModemPresence(ModemPresence::kPresent, 17000), + DualNetworkActionType::kPromptCellularOn)); + assert(policy.OnModemPresence( + ModemPresence::kAbsent, 20000).action_count == 0); + assert(policy.OnModemPresence( + ModemPresence::kPresent, 23000).action_count == 0); + assert(policy.stable_modem_presence() == ModemPresence::kPresent); + + // Booting with the switch already OFF says nothing. + DualNetworkPolicy quiet(Config()); + quiet.Start(true, 0); + assert(quiet.OnModemPresence( + ModemPresence::kAbsent, 1000).action_count == 0); + assert(quiet.stable_modem_presence() == ModemPresence::kAbsent); +} + +void TestWifiLostWithoutModemIsRateLimited() +{ + DualNetworkPolicy policy(Config()); + policy.Start(true, 0); + + // Modem presence is still unknown: stay quiet rather than guess. + assert(policy.NotifyWifiLostWithoutModem(1000).action_count == 0); + + policy.OnModemPresence(ModemPresence::kAbsent, 2000); + assert(policy.stable_modem_presence() == ModemPresence::kAbsent); + + // WiFi has never been up yet — a booting device must not be told to flip + // the 4G switch just because it has not associated yet. + assert(policy.NotifyWifiLostWithoutModem(3000).action_count == 0); + + policy.OnWifiOnline(4000); + assert(policy.NotifyWifiLostWithoutModem(5000).action_count == 0); + + // Now WiFi drops. The prompt waits for the same 30 s deadline the + // automatic failover uses, so brief blips stay silent. + policy.OnWifiDisconnected(10000); + assert(policy.NotifyWifiLostWithoutModem(15000).action_count == 0); + assert(policy.NotifyWifiLostWithoutModem(39999).action_count == 0); + assert(Has(policy.NotifyWifiLostWithoutModem(40000), + DualNetworkActionType::kPromptCellularUnavailable)); + + // The WiFi monitor fires every few seconds; only one prompt per window. + assert(policy.NotifyWifiLostWithoutModem(45000).action_count == 0); + assert(policy.NotifyWifiLostWithoutModem(159999).action_count == 0); + assert(Has(policy.NotifyWifiLostWithoutModem(160000), + DualNetworkActionType::kPromptCellularUnavailable)); + + // WiFi coming back stops the prompting entirely. + policy.OnWifiOnline(170000); + assert(policy.NotifyWifiLostWithoutModem(300000).action_count == 0); + + // Flipping the switch on also clears the rate-limit window, so the next + // qualifying outage is reported without waiting out the old one. + policy.OnWifiDisconnected(310000); + policy.OnModemPresence(ModemPresence::kPresent, 311000); + assert(policy.NotifyWifiLostWithoutModem(345000).action_count == 0); + policy.OnModemPresence(ModemPresence::kAbsent, 346000); + policy.OnModemPresence(ModemPresence::kAbsent, 347000); + assert(Has(policy.NotifyWifiLostWithoutModem(348000), + DualNetworkActionType::kPromptCellularUnavailable)); +} + +int main() +{ + TestMissingWifiRequestsProvisioning(); + TestDisconnectedWifiFailsOver(); + TestWeakWifiRequiresConsecutiveSamples(); + TestAbsentModemPreventsAutomaticAndManualSwitch(); + TestCellularFailureFallsBackToWifi(); + TestModemSwitchSensingAnnouncements(); + TestWifiLostWithoutModemIsRateLimited(); + std::cout << "dual network policy tests passed\n"; + return 0; +} + diff --git a/host_tests/effect_router_test.cc b/host_tests/effect_router_test.cc new file mode 100644 index 0000000..2c8178e --- /dev/null +++ b/host_tests/effect_router_test.cc @@ -0,0 +1,381 @@ +#include "adapters/effect_router.h" + +#include +#include + +namespace { + +using namespace borla; + +class FakeAudio final : public IAudioEngine { +public: + bool Start() override + { + started = true; + return true; + } + void Stop() override { started = false; } + void ApplyPolicy(AudioPolicy value) override { policy = value; } + void SetVolume(uint8_t value) override { volume = value; } + void SetWakeWordEnabled(bool value) override + { + wake_word_enabled = value; + } + void SetBargeInEnabled(bool value) override + { + barge_in_enabled = value; + } + void SetPlaybackPaused(bool value) override + { + playback_paused = value; + } + void ReleaseWakeWord() override + { + wake_word_released = true; + } + void LogAudioMetrics(const char*) override {} + bool LogAudioFrameStats() override { return false; } + bool WaitForPlaybackIdle(uint32_t) override { return true; } + void CancelPlayback(PlaybackSessionId value) override + { + cancelled_session = value; + } + void BeginRemotePlayback( + PlaybackSessionId value, + PlaybackPriority value_priority) override + { + remote_session = value; + priority = value_priority; + } + void EndPlaybackInput(PlaybackSessionId value) override + { + ended_session = value; + } + bool SubmitOpusFrame( + PlaybackSessionId, + const uint8_t*, + size_t) override + { + return true; + } + PlaybackSessionId PlayLocalPrompt( + LocalPrompt value, + PlaybackPriority value_priority, + int16_t value_selector) override + { + prompt = value; + priority = value_priority; + selector = value_selector; + return 101; + } + PlaybackSessionId PlayLocalSequence( + const LocalPromptSequence&, + PlaybackPriority value_priority) override + { + priority = value_priority; + return 102; + } + PlaybackSessionId PlayDetachedPrompt( + LocalPrompt value, + PlaybackPriority value_priority) override + { + detached_prompt = value; + detached_priority = value_priority; + detached_count++; + return 103; + } + uint8_t OutputVolumePercent() const override { return volume; } + + bool started = false; + LocalPrompt detached_prompt = LocalPrompt::kError; + PlaybackPriority detached_priority = PlaybackPriority::kBackground; + int detached_count = 0; + AudioPolicy policy = AudioPolicy::kOff; + uint8_t volume = 0; + bool wake_word_enabled = true; + bool barge_in_enabled = false; + bool playback_paused = false; + bool wake_word_released = false; + PlaybackSessionId cancelled_session = 0; + PlaybackSessionId remote_session = 0; + PlaybackSessionId ended_session = 0; + PlaybackPriority priority = PlaybackPriority::kBackground; + LocalPrompt prompt = LocalPrompt::kError; + int16_t selector = -1; +}; + +class FakeConnectivity final : public IConnectivityManager { +public: + void Start() override { started = true; } + void Stop() override { started = false; } + void SwitchNetwork() override { switched = true; } + bool IsOnline() const override { return online; } + ConnectivityDiagnostics GetDiagnostics() const override { return {}; } + + bool started = false; + bool switched = false; + bool online = false; +}; + +class FakeRealtime final : public IRealtimeProtocol { +public: + void Open() override { opened = true; } + void Close() override { opened = false; } + void SendStartListening() override { start_listening_count++; } + void SendStopListening() override { stop_listening_count++; } + void SendAbortSpeaking( + ConversationInterruptSource source) override + { + abort_source = source; + abort_speaking_count++; + } + void SendGoodbye() override { goodbye_count++; } + void SendAcceptCall() override { accept_call_count++; } + void SendHangupCall() override { hangup_call_count++; } + void SendButtonClick(uint8_t click_count) override + { + button_click_count = click_count; + } + void SendLocalPlaybackState( + LocalPrompt prompt, + bool started) override + { + local_prompt = prompt; + local_started = started; + local_state_count++; + } + bool SendFriendAdd( + const char*, + const char*, + const char*, + const char*) override + { + return true; + } + bool SendOtaNotify(const char*, bool) override + { + ota_notify_count++; + return true; + } + void RequestConnectionErrorPrompt() override + { + connection_error_prompt_count++; + } + + bool opened = false; + int ota_notify_count = 0; + int connection_error_prompt_count = 0; + int start_listening_count = 0; + int stop_listening_count = 0; + int abort_speaking_count = 0; + ConversationInterruptSource abort_source = + ConversationInterruptSource::kWakeWordDetected; + int goodbye_count = 0; + int accept_call_count = 0; + int hangup_call_count = 0; + uint8_t button_click_count = 0; + LocalPrompt local_prompt = LocalPrompt::kError; + bool local_started = false; + int local_state_count = 0; +}; + +class FakePlatform final : public IDevicePlatform { +public: + bool Initialize() override { return true; } + const DeviceIdentity& Identity() const override { return identity; } + void SetLed(LedPattern value) override { led = value; } + void ShowTemporaryLedAlert(uint32_t duration_ms) override + { + alert_duration_ms = duration_ms; + } + void ReportError(uint32_t value) override { error_id = value; } + void Reboot() override { rebooted = true; } + void EnterSoftOff(uint64_t) override { soft_off = true; } + SoftOffWakeReason ConsumeSoftOffWakeReason() override + { + return SoftOffWakeReason::kNone; + } + + LedPattern led = LedPattern::kOff; + uint32_t error_id = 0; + uint32_t alert_duration_ms = 0; + bool rebooted = false; + bool soft_off = false; + DeviceIdentity identity{}; +}; + +class FakeProvisioning final : public IProvisioningService { +public: + void Start() override { started = true; } + void Stop() override { started = false; } + bool started = false; +}; + +class FakeFriend final : public IFriendService { +public: + void Start() override { started = true; } + void Stop() override { started = false; } + bool started = false; +}; + +class FakeOta final : public IOtaService { +public: + void StartUpgrade(uint32_t value) override { request_id = value; } + uint32_t request_id = 0; +}; + +class FakeAlert final : public IAlertRinger { +public: + void Start(AlertKind value) override + { + started = true; + kind = value; + } + void Stop() override { started = false; } + bool started = false; + AlertKind kind = AlertKind::kReminder; +}; + +class FakePower final : public IPowerService { +public: + void EnterSoftOff() override { soft_off = true; } + bool soft_off = false; +}; + +void TestRoutesEffectsWithoutProductLogic() +{ + FakeAudio audio; + FakeConnectivity connectivity; + FakeRealtime realtime; + FakePlatform platform; + FakeFriend friend_service; + FakeProvisioning provisioning; + FakeOta ota; + FakeAlert alert; + FakePower power; + EffectRouter router( + audio, connectivity, realtime, platform, friend_service, + provisioning, ota, alert, power); + RuntimeState state; + + router.Handle( + AppEffect::Simple(AppEffectType::kStartConnectivity), state); + router.Handle(AppEffect::Simple(AppEffectType::kStartAudio), state); + router.Handle(AppEffect::Audio(AudioPolicy::kBargeInDuplex), state); + router.Handle( + AppEffect::Simple(AppEffectType::kSetAudioVolume, 72), state); + router.Handle( + AppEffect::Simple( + AppEffectType::kSetWakeWordEnabled, 0), + state); + router.Handle( + AppEffect::Simple( + AppEffectType::kSetBargeInEnabled, 1), + state); + router.Handle( + AppEffect::Simple(AppEffectType::kPausePlayback), state); + assert(audio.playback_paused); + + // Provisioning must free the WakeNet instance before NimBLE starts: the BT + // controller needs the internal RAM and the wake word is unused there. + assert(!audio.wake_word_released); + router.Handle( + AppEffect::Simple(AppEffectType::kEnterProvisioning), state); + assert(audio.wake_word_released); + assert(provisioning.started); + router.Handle( + AppEffect::Simple(AppEffectType::kResumePlayback), state); + assert(!audio.playback_paused); + router.Handle(AppEffect::Led(LedPattern::kSpeaking), state); + router.Handle( + AppEffect::Simple( + AppEffectType::kShowTemporaryLedAlert, 5000), + state); + router.Handle( + AppEffect::Simple(AppEffectType::kStartUpgrade, 99), state); + router.Handle( + AppEffect::Simple(AppEffectType::kStartFriendMode), state); + router.Handle( + AppEffect::Simple(AppEffectType::kSendAbortSpeaking), state); + router.Handle( + AppEffect::Simple(AppEffectType::kSendGoodbye), state); + router.Handle( + AppEffect::Simple(AppEffectType::kSendAcceptCall), state); + router.Handle( + AppEffect::Simple(AppEffectType::kSendHangupCall), state); + router.Handle( + AppEffect::Simple(AppEffectType::kSendButtonClick, 4), state); + router.Handle( + AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackStarted, + LocalPrompt::kSnoreLight), + state); + router.Handle( + AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackDone, + LocalPrompt::kSnoreLight), + state); + router.Handle( + AppEffect::RemotePlayback( + AppEffectType::kBeginRemotePlayback, + 77, + PlaybackPriority::kConversation), + state); + router.Handle( + AppEffect::RemotePlayback( + AppEffectType::kEndPlaybackInput, 77), + state); + router.Handle( + AppEffect::Prompt( + LocalPrompt::kBoot, PlaybackPriority::kSystem, 4), + state); + router.Handle( + AppEffect::DetachedPrompt(LocalPrompt::kWakeResponse), + state); + router.Handle( + AppEffect::Simple( + AppEffectType::kRequestConnectionErrorPrompt), + state); + + assert(connectivity.started); + assert(audio.started); + assert(audio.policy == AudioPolicy::kBargeInDuplex); + assert(audio.volume == 72); + assert(!audio.wake_word_enabled); + assert(audio.barge_in_enabled); + assert(platform.led == LedPattern::kSpeaking); + assert(platform.alert_duration_ms == 5000); + assert(ota.request_id == 99); + assert(friend_service.started); + assert(realtime.abort_speaking_count == 1); + assert(realtime.abort_source == + ConversationInterruptSource::kUserInitiated); + assert(realtime.goodbye_count == 1); + assert(realtime.accept_call_count == 1); + assert(realtime.hangup_call_count == 1); + assert(realtime.button_click_count == 4); + assert(realtime.local_state_count == 2); + assert(realtime.local_prompt == LocalPrompt::kSnoreLight); + assert(!realtime.local_started); + assert(audio.remote_session == 77); + assert(audio.ended_session == 77); + assert(audio.selector == 4); + assert(audio.prompt == LocalPrompt::kBoot); + assert(audio.priority == PlaybackPriority::kSystem); + // A detached prompt must reach the dedicated engine entry point, not the + // lifecycle-publishing one, and must not disturb the normal prompt slot. + assert(audio.detached_count == 1); + assert(audio.detached_prompt == LocalPrompt::kWakeResponse); + assert(audio.detached_priority == PlaybackPriority::kLocalPrompt); + assert(audio.prompt == LocalPrompt::kBoot); + assert(realtime.connection_error_prompt_count == 1); +} + +} // namespace + +int main() +{ + TestRoutesEffectsWithoutProductLogic(); + std::cout << "effect router tests passed\n"; + return 0; +} diff --git a/host_tests/friend_types_test.cc b/host_tests/friend_types_test.cc new file mode 100644 index 0000000..4e93131 --- /dev/null +++ b/host_tests/friend_types_test.cc @@ -0,0 +1,63 @@ +#include "friend/friend_types.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +void TestMacNormalizationAndAdvertisingName() +{ + char base[kFriendMacCapacity]{}; + // Uppercase input on purpose: parsing is case-insensitive, but the output + // must be lower case — it is the peer's device_id and the server matches + // device ids case-sensitively (same contract as the activation-loop fix). + assert(NormalizeBleMacToBaseMac( + "3C:DC:75:FA:73:0A", base, sizeof(base))); + assert(std::strcmp(base, "3c:dc:75:fa:73:08") == 0); + assert(!NormalizeBleMacToBaseMac( + "invalid", base, sizeof(base))); + + char name[kFriendAdvertisingNameCapacity]{}; + assert(BuildFriendAdvertisingName( + "3C:DC:75:FA:73:08", name, sizeof(name))); + assert(std::strcmp(name, "BorlaF-7308") == 0); +} + +void TestCandidateThresholdsAndStaleness() +{ + FriendCandidateSelector selector; + FriendPeer peer; + constexpr uint64_t kNow = 10000; + + assert(!selector.Observe( + "3C:DC:75:FA:73:0A", "Other-7308", -40, kNow)); + assert(selector.Observe( + "3C:DC:75:FA:73:0A", "BorlaF-7308", -70, kNow)); + assert(!selector.Select(kNow, &peer)); + assert(selector.Observe( + "3C:DC:75:FA:73:0A", "BorlaF-7308", -72, kNow + 100)); + assert(selector.Select(kNow + 100, &peer)); + assert(std::strcmp(peer.mac.data(), "3c:dc:75:fa:73:08") == 0); + assert(std::strcmp(peer.name.data(), "BorlaF-7308") == 0); + + selector.Reset(); + assert(selector.Observe( + "3C:DC:75:FA:73:0C", "BorlaF-730A", -55, kNow)); + assert(selector.Select(kNow, &peer)); + assert(!selector.Select( + kNow + FriendCandidateSelector::kStaleAfterMs + 1, + &peer)); +} + +} // namespace + +int main() +{ + TestMacNormalizationAndAdvertisingName(); + TestCandidateThresholdsAndStaleness(); + std::cout << "friend type tests passed\n"; + return 0; +} diff --git a/host_tests/ml307_at_parser_test.cc b/host_tests/ml307_at_parser_test.cc new file mode 100644 index 0000000..8c045bc --- /dev/null +++ b/host_tests/ml307_at_parser_test.cc @@ -0,0 +1,37 @@ +#include "connectivity/ml307_at_parser.h" + +#include +#include +#include + +using namespace borla; + +int main() +{ + CellularRegistration registration; + assert(ParseMl307Registration( + "\r\n+CEREG: 2,1,\"1234\"\r\nOK\r\n", + ®istration)); + assert(registration.mode == 2); + assert(registration.IsRegistered()); + assert(ParseMl307Registration( + "\r\n+CEREG: 5\r\nOK\r\n", ®istration)); + assert(registration.IsRegistered()); + assert(!ParseMl307Registration("ERROR", ®istration)); + + int8_t csq = 0; + assert(ParseMl307SignalQuality("+CSQ: 18,99\r\n", &csq)); + assert(csq == 18); + assert(ParseMl307SignalQuality("+CSQ: 99,99\r\n", &csq)); + assert(csq == -1); + assert(!ParseMl307SignalQuality("+CSQ: 55,0\r\n", &csq)); + + char value[32]{}; + assert(CopyMl307ResponseLine( + "\r\n460011234567890\r\nOK\r\n", "", value, sizeof(value))); + assert(std::strcmp(value, "460011234567890") == 0); + + std::cout << "ML307 AT parser tests passed\n"; + return 0; +} + diff --git a/host_tests/ota_endpoint_test.cc b/host_tests/ota_endpoint_test.cc new file mode 100644 index 0000000..8f91082 --- /dev/null +++ b/host_tests/ota_endpoint_test.cc @@ -0,0 +1,144 @@ +#include "ota/ota_endpoint.h" + +#include +#include +#include +#include + +namespace { + +using namespace borla; + +void TestRolloverEndpointDetection() +{ + // Build/staging defaults must be recognised so a device that once talked + // to a retired host recovers instead of retrying it forever. + assert(IsRolloverEndpoint("wss://borlaws.lkall.com/v1/ws")); + assert(IsRolloverEndpoint("wss://borla-dev.lkall.com/v1/ws")); + assert(IsRolloverEndpoint("wss://borla-moe.lkall.com/v1/ws")); + assert(IsRolloverEndpoint("https://borla-ota.lkall.com/xiaozhi/ota/")); + assert(IsRolloverEndpoint("ws://192.168.1.121:30001/v1/ws")); + assert(IsRolloverEndpoint("ws://117.50.44.247:8000/v1/ws")); + + // A genuinely provisioned production endpoint must be preserved. + assert(!IsRolloverEndpoint("wss://prod.example.com/v1/ws")); + // .lkall.com alone is not enough — only the listed staging hosts roll over. + assert(!IsRolloverEndpoint("wss://customer.lkall.com/v1/ws")); + assert(!IsRolloverEndpoint("")); + assert(!IsRolloverEndpoint(nullptr)); +} + +void TestWildcardHostSubstitution() +{ + std::array output{}; + assert(SubstituteWildcardHost( + "ws://0.0.0.0:8000/v1/ws", + "https://ota.example.com/xiaozhi/ota/", + output.data(), + output.size())); + assert(std::strcmp( + output.data(), "ws://ota.example.com:8000/v1/ws") == 0); + + // Host with an explicit port on the OTA side: only the host is taken. + output.fill('\0'); + assert(SubstituteWildcardHost( + "ws://0.0.0.0:8000/v1/ws", + "http://10.1.2.3:9000/ota/", + output.data(), + output.size())); + assert(std::strcmp(output.data(), "ws://10.1.2.3:8000/v1/ws") == 0); + + // No wildcard in the candidate → nothing to substitute. + assert(!SubstituteWildcardHost( + "wss://real.example.com/v1/ws", + "https://ota.example.com/ota/", + output.data(), + output.size())); + + // Unusable OTA URLs must not produce a half-rewritten endpoint. + assert(!SubstituteWildcardHost( + "ws://0.0.0.0:8000/v1/ws", "ota.example.com", + output.data(), output.size())); + assert(!SubstituteWildcardHost( + "ws://0.0.0.0:8000/v1/ws", "https://0.0.0.0/ota/", + output.data(), output.size())); + assert(!SubstituteWildcardHost( + "ws://0.0.0.0:8000/v1/ws", nullptr, + output.data(), output.size())); + + // Capacity is respected. + std::array tiny{}; + assert(!SubstituteWildcardHost( + "ws://0.0.0.0:8000/v1/ws", + "https://ota.example.com/ota/", + tiny.data(), + tiny.size())); +} + +void TestResolveRealtimeUrl() +{ + constexpr const char* kOtaUrl = "https://ota.example.com/xiaozhi/ota/"; + constexpr const char* kDefault = "wss://borlaws.lkall.com/v1/ws"; + std::array output{}; + + // A real production endpoint passes through untouched. + assert(ResolveRealtimeUrl( + "wss://prod.example.com/v1/ws", kOtaUrl, kDefault, + output.data(), output.size())); + assert(std::strcmp( + output.data(), "wss://prod.example.com/v1/ws") == 0); + + // A wildcard endpoint is rewritten to the reachable OTA host, and that + // result is NOT then treated as a rollover default. + output.fill('\0'); + assert(ResolveRealtimeUrl( + "ws://0.0.0.0:8000/v1/ws", kOtaUrl, kDefault, + output.data(), output.size())); + assert(std::strcmp( + output.data(), "ws://ota.example.com:8000/v1/ws") == 0); + + // A retired staging endpoint falls back to the current default. + output.fill('\0'); + assert(ResolveRealtimeUrl( + "wss://borla-dev.lkall.com/v1/ws", kOtaUrl, kDefault, + output.data(), output.size())); + assert(std::strcmp(output.data(), kDefault) == 0); + + // An unresolvable wildcard falls back rather than shipping "0.0.0.0". + output.fill('\0'); + assert(ResolveRealtimeUrl( + "ws://0.0.0.0:8000/v1/ws", "not-a-url", kDefault, + output.data(), output.size())); + assert(std::strcmp(output.data(), kDefault) == 0); + + // Empty/absent candidate falls back. + output.fill('\0'); + assert(ResolveRealtimeUrl( + "", kOtaUrl, kDefault, output.data(), output.size())); + assert(std::strcmp(output.data(), kDefault) == 0); + output.fill('\0'); + assert(ResolveRealtimeUrl( + nullptr, kOtaUrl, kDefault, output.data(), output.size())); + assert(std::strcmp(output.data(), kDefault) == 0); + + // No candidate and no default → nothing usable. + assert(!ResolveRealtimeUrl( + nullptr, kOtaUrl, "", output.data(), output.size())); + + // Too small an output buffer is a failure, not a truncation. + std::array tiny{}; + assert(!ResolveRealtimeUrl( + "wss://prod.example.com/v1/ws", kOtaUrl, kDefault, + tiny.data(), tiny.size())); +} + +} // namespace + +int main() +{ + TestRolloverEndpointDetection(); + TestWildcardHostSubstitution(); + TestResolveRealtimeUrl(); + std::cout << "ota endpoint tests passed" << std::endl; + return 0; +} diff --git a/host_tests/ota_response_parser_test.cc b/host_tests/ota_response_parser_test.cc new file mode 100644 index 0000000..9a26cc8 --- /dev/null +++ b/host_tests/ota_response_parser_test.cc @@ -0,0 +1,184 @@ +#include "ota/ota_response_parser.h" + +#include +#include +#include +#include + +namespace { + +using namespace borla; + +constexpr const char* kSha = + "0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef"; + +void TestPolicyParsing() +{ + OtaResponseParser parser; + OtaManifest manifest; + char json[1024]{}; + std::snprintf( + json, + sizeof(json), + "{\"firmware\":{\"version\":\"2.1.0\"," + "\"url\":\"https://cdn.example/fw.bin\"," + "\"size\":1048576,\"sha256\":\"%s\"}," + "\"auto_update\":true,\"force_upgrade\":false}", + kSha); + assert(parser.Parse( + json, std::strlen(json), "2.0.0", false, &manifest) == + OtaParseStatus::kOk); + assert(manifest.policy == OtaUpgradePolicy::kAutomatic); + assert(manifest.size == 1048576); + + std::snprintf( + json, + sizeof(json), + "{\"firmware\":{\"version\":\"2.2.0\"," + "\"url\":\"https://cdn.example/fw.bin\"," + "\"size\":100,\"sha256\":\"%s\"}," + "\"auto_update\":false,\"force_upgrade\":true}", + kSha); + assert(parser.Parse( + json, std::strlen(json), "2.0.0", false, &manifest) == + OtaParseStatus::kOk); + assert(manifest.policy == OtaUpgradePolicy::kForced); +} + +void TestNoUpdateAndStrictValidation() +{ + OtaResponseParser parser; + OtaManifest manifest; + constexpr char kNone[] = R"({"firmware":null})"; + assert(parser.Parse( + kNone, sizeof(kNone) - 1, "2.0.0", false, &manifest) == + OtaParseStatus::kOk); + assert(!manifest.HasUpdate()); + + char json[1024]{}; + std::snprintf( + json, + sizeof(json), + "{\"firmware\":{\"version\":\"2.1.0\"," + "\"url\":\"http://lan/fw.bin\"," + "\"size\":100,\"sha256\":\"%s\"}}", + kSha); + assert(parser.Parse( + json, std::strlen(json), "2.0.0", false, &manifest) == + OtaParseStatus::kUnsafeUrl); + assert(parser.Parse( + json, std::strlen(json), "2.0.0", true, &manifest) == + OtaParseStatus::kOk); + + std::memset(json, 0, sizeof(json)); + std::snprintf( + json, + sizeof(json), + "{\"firmware\":{\"version\":\"1.9.0\"," + "\"url\":\"https://cdn/fw.bin\"," + "\"size\":100,\"sha256\":\"%s\"}}", + kSha); + assert(parser.Parse( + json, std::strlen(json), "2.0.0-dev", false, &manifest) == + OtaParseStatus::kOk); + assert(!manifest.HasUpdate()); +} + +void TestVersionAndDigestHelpers() +{ + assert(OtaResponseParser::CompareVersions("v2.1.0", "2.0.9") > 0); + assert(OtaResponseParser::CompareVersions("2.0", "2.0.0") == 0); + assert(OtaResponseParser::CompareVersions("1.9.9", "2.0") < 0); + uint8_t digest[32]{}; + assert(OtaResponseParser::DecodeSha256(kSha, digest)); + assert(digest[0] == 0x01); + assert(digest[31] == 0xef); + assert(!OtaResponseParser::DecodeSha256("bad", digest)); +} + +void TestEndpointBlockSurvivesEveryFirmwareOutcome() +{ + OtaResponseParser parser; + OtaManifest manifest; + OtaEndpointConfig endpoint; + char json[1024]{}; + + // No firmware block at all — the websocket block must still come through, + // this is how a fielded device gets repointed at a new server. + const char* endpoint_only = + "{\"websocket\":{\"url\":\"wss://a.example/v1/ws\"," + "\"token\":\"tok-123\"}}"; + assert(parser.Parse( + endpoint_only, std::strlen(endpoint_only), "2.0.0", + false, &manifest, &endpoint) == OtaParseStatus::kOk); + assert(!manifest.HasUpdate()); + assert(endpoint.has_url); + assert(endpoint.has_token); + assert(std::strcmp( + endpoint.url.data(), + "wss://a.example/v1/ws") == 0); + assert(std::strcmp(endpoint.token.data(), "tok-123") == 0); + + // Firmware present but not newer — the "*manifest = {}" reset on that path + // must not wipe the endpoint. + std::snprintf( + json, + sizeof(json), + "{\"firmware\":{\"version\":\"2.0.0\"," + "\"url\":\"https://cdn.example/fw.bin\"," + "\"size\":100,\"sha256\":\"%s\"}," + "\"websocket\":{\"url\":\"wss://b.example/v1/ws\"}}", + kSha); + assert(parser.Parse( + json, std::strlen(json), "2.0.0", false, &manifest, + &endpoint) == OtaParseStatus::kOk); + assert(!manifest.HasUpdate()); + assert(endpoint.has_url); + assert(std::strcmp( + endpoint.url.data(), + "wss://b.example/v1/ws") == 0); + assert(!endpoint.has_token); + + // Firmware newer — endpoint travels alongside the upgrade. + std::snprintf( + json, + sizeof(json), + "{\"firmware\":{\"version\":\"2.5.0\"," + "\"url\":\"https://cdn.example/fw.bin\"," + "\"size\":100,\"sha256\":\"%s\"},\"auto_update\":true," + "\"websocket\":{\"url\":\"wss://c.example/v1/ws\"}}", + kSha); + assert(parser.Parse( + json, std::strlen(json), "2.0.0", false, &manifest, + &endpoint) == OtaParseStatus::kOk); + assert(manifest.policy == OtaUpgradePolicy::kAutomatic); + assert(std::strcmp( + endpoint.url.data(), + "wss://c.example/v1/ws") == 0); + + // Absent / malformed websocket block leaves the endpoint unset so the + // caller keeps whatever is already stored. + const char* no_ws = "{}"; + assert(parser.Parse( + no_ws, std::strlen(no_ws), "2.0.0", false, &manifest, + &endpoint) == OtaParseStatus::kOk); + assert(!endpoint.HasAny()); + const char* bad_ws = "{\"websocket\":{\"url\":42}}"; + assert(parser.Parse( + bad_ws, std::strlen(bad_ws), "2.0.0", false, &manifest, + &endpoint) == OtaParseStatus::kOk); + assert(!endpoint.HasAny()); +} + +} // namespace + +int main() +{ + TestPolicyParsing(); + TestNoUpdateAndStrictValidation(); + TestVersionAndDigestHelpers(); + TestEndpointBlockSurvivesEveryFirmwareOutcome(); + std::cout << "OTA response parser tests passed\n"; + return 0; +} diff --git a/host_tests/packed_opus_reader_test.cc b/host_tests/packed_opus_reader_test.cc new file mode 100644 index 0000000..2b0f2fa --- /dev/null +++ b/host_tests/packed_opus_reader_test.cc @@ -0,0 +1,76 @@ +#include "audio/packed_opus_reader.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +void TestReadsCompletePayload() +{ + const uint8_t packed[] = { + 0x02, 0x00, + 0x03, 0x00, 0x11, 0x22, 0x33, + 0x02, 0x00, 0x44, 0x55, + }; + PackedOpusReader reader(packed, sizeof(packed)); + assert(reader.valid()); + assert(reader.frame_count() == 2); + + const uint8_t* frame = nullptr; + size_t size = 0; + assert(reader.Next(&frame, &size)); + assert(size == 3); + assert(frame[0] == 0x11 && frame[2] == 0x33); + assert(reader.Next(&frame, &size)); + assert(size == 2); + assert(frame[0] == 0x44 && frame[1] == 0x55); + assert(!reader.Next(&frame, &size)); + assert(reader.complete()); +} + +void TestRejectsTruncatedFrame() +{ + const uint8_t packed[] = { + 0x01, 0x00, + 0x04, 0x00, 0x11, 0x22, + }; + PackedOpusReader reader(packed, sizeof(packed)); + const uint8_t* frame = nullptr; + size_t size = 0; + assert(!reader.Next(&frame, &size)); + assert(!reader.valid()); + assert(!reader.complete()); +} + +void TestRejectsZeroFramesAndTrailingBytes() +{ + const uint8_t empty[] = {0x00, 0x00}; + PackedOpusReader empty_reader(empty, sizeof(empty)); + assert(!empty_reader.valid()); + + const uint8_t trailing[] = { + 0x01, 0x00, + 0x01, 0x00, 0x77, + 0x99, + }; + PackedOpusReader trailing_reader(trailing, sizeof(trailing)); + const uint8_t* frame = nullptr; + size_t size = 0; + assert(trailing_reader.Next(&frame, &size)); + assert(!trailing_reader.complete()); +} + +} // namespace + +int main() +{ + TestReadsCompletePayload(); + TestRejectsTruncatedFrame(); + TestRejectsZeroFramesAndTrailingBytes(); + + std::cout << "packed Opus reader tests passed\n"; + return 0; +} diff --git a/host_tests/playback_controller_test.cc b/host_tests/playback_controller_test.cc new file mode 100644 index 0000000..7379b57 --- /dev/null +++ b/host_tests/playback_controller_test.cc @@ -0,0 +1,178 @@ +#include "audio/playback_controller.h" + +#include +#include + +namespace { + +using namespace borla; + +void TestPendingProducerCannotDrain() +{ + PlaybackController controller; + const PlaybackStartResult start = controller.StartSession( + PlaybackSource::kLocalPrompt, + PlaybackPriority::kSystem, + 0, + 100); + assert(start.status == PlaybackStartStatus::kStarted); + assert(controller.EndInput(start.session_id, 110)); + assert(controller.TryComplete() == 0); + assert(controller.snapshot().active); + assert(!controller.snapshot().producer_started); + + assert(controller.QueueFrame(start.session_id, 120)); + assert(controller.BeginFrame(start.session_id, 121)); + assert(controller.FinishFrame(start.session_id, true, 180)); + assert(controller.TryComplete() == start.session_id); + assert(!controller.snapshot().active); +} + +void TestOldProducerCannotRefillAfterPreemption() +{ + PlaybackController controller; + const PlaybackStartResult old_session = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 10, + 0); + assert(controller.QueueFrame(old_session.session_id, 10)); + + const PlaybackStartResult replacement = controller.StartSession( + PlaybackSource::kLocalPrompt, + PlaybackPriority::kSystem, + 20, + 20); + assert(replacement.status == PlaybackStartStatus::kStarted); + assert(replacement.preempted_session_id == old_session.session_id); + assert(!controller.QueueFrame(old_session.session_id, 30)); + assert(controller.QueueFrame(replacement.session_id, 30)); + assert(controller.metrics().sessions_preempted == 1); +} + +void TestStaleDrainCannotCompleteNewSession() +{ + PlaybackController controller; + const PlaybackStartResult old_session = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 31, + 0); + assert(controller.QueueFrame(old_session.session_id, 1)); + + const PlaybackStartResult current = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 32, + 2); + assert(!controller.EndInput(old_session.session_id, 3)); + assert(controller.TryComplete() == 0); + assert(controller.snapshot().id == current.session_id); + assert(controller.snapshot().active); +} + +void TestPriorityPreventsLocalRemoteMixing() +{ + PlaybackController controller; + const PlaybackStartResult remote = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 41, + 0); + const PlaybackStartResult local = controller.StartSession( + PlaybackSource::kLocalPrompt, + PlaybackPriority::kSystem, + 0, + 1); + assert(local.status == PlaybackStartStatus::kStarted); + assert(local.preempted_session_id == remote.session_id); + + const PlaybackStartResult rejected = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 42, + 2); + assert(rejected.status == + PlaybackStartStatus::kRejectedLowerPriority); + assert(controller.snapshot().id == local.session_id); + assert(controller.metrics().lower_priority_rejections == 1); +} + +void TestProducerAndStallTimeouts() +{ + PlaybackController controller; + PlaybackStartResult start = controller.StartSession( + PlaybackSource::kLocalPrompt, + PlaybackPriority::kSystem, + 0, + 100); + PlaybackTimeoutResult timeout = + controller.CheckTimeout(2099, 2000, 10000); + assert(timeout.reason == PlaybackTimeoutReason::kNone); + timeout = controller.CheckTimeout(2100, 2000, 10000); + assert(timeout.reason == PlaybackTimeoutReason::kProducerStart); + assert(timeout.session_id == start.session_id); + + start = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 52, + 3000); + assert(controller.QueueFrame(start.session_id, 3100)); + timeout = controller.CheckTimeout(13099, 2000, 10000); + assert(timeout.reason == PlaybackTimeoutReason::kNone); + timeout = controller.CheckTimeout(13100, 2000, 10000); + assert(timeout.reason == PlaybackTimeoutReason::kStalled); + assert(timeout.session_id == start.session_id); +} + +void TestSessionNamespacesAndIdempotency() +{ + PlaybackController controller; + const PlaybackStartResult invalid = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 0x80000000U, + 0); + assert(invalid.status == + PlaybackStartStatus::kRejectedInvalidSessionId); + + const PlaybackStartResult remote = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 7, + 1); + const PlaybackStartResult duplicate = controller.StartSession( + PlaybackSource::kRemoteTts, + PlaybackPriority::kConversation, + 7, + 2); + assert(duplicate.status == PlaybackStartStatus::kAlreadyActive); + assert(duplicate.session_id == remote.session_id); + assert(duplicate.generation == remote.generation); + assert(controller.metrics().sessions_started == 1); + + assert(controller.Cancel(remote.session_id) == remote.session_id); + const PlaybackStartResult local = controller.StartSession( + PlaybackSource::kLocalPrompt, + PlaybackPriority::kLocalPrompt, + 0, + 3); + assert(local.session_id >= 0x80000000U); + assert(local.generation != remote.generation); +} + +} // namespace + +int main() +{ + TestPendingProducerCannotDrain(); + TestOldProducerCannotRefillAfterPreemption(); + TestStaleDrainCannotCompleteNewSession(); + TestPriorityPreventsLocalRemoteMixing(); + TestProducerAndStallTimeouts(); + TestSessionNamespacesAndIdempotency(); + + std::cout << "playback controller tests passed\n"; + return 0; +} diff --git a/host_tests/realtime_codec_test.cc b/host_tests/realtime_codec_test.cc new file mode 100644 index 0000000..a98e111 --- /dev/null +++ b/host_tests/realtime_codec_test.cc @@ -0,0 +1,626 @@ +#include "protocol/protocol_message_builder.h" +#include "protocol/server_message_dispatcher.h" + +#include +#include +#include +#include + +#include + +namespace { + +using namespace borla; + +cJSON* BuildAndParse( + bool result, + const char* output, + size_t output_size) +{ + assert(result); + assert(output_size == std::strlen(output)); + cJSON* root = cJSON_ParseWithLength(output, output_size); + assert(cJSON_IsObject(root)); + return root; +} + +const char* StringField(const cJSON* root, const char* name) +{ + const cJSON* field = + cJSON_GetObjectItemCaseSensitive(root, name); + assert(cJSON_IsString(field)); + return field->valuestring; +} + +ServerCommand ParseCommand( + const ServerMessageDispatcher& dispatcher, + const char* json, + size_t size) +{ + ServerCommand command; + assert(dispatcher.ParseInto(json, size, &command)); + return command; +} + +void TestMessageBuilder() +{ + ProtocolMessageBuilder builder; + char output[768]{}; + size_t size = 0; + + cJSON* root = BuildAndParse( + builder.BuildHello( + 3, output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "hello") == 0); + assert(cJSON_GetObjectItem(root, "version")->valueint == 3); + const cJSON* audio = cJSON_GetObjectItem(root, "audio_params"); + assert(cJSON_IsObject(audio)); + assert(cJSON_GetObjectItem(audio, "sample_rate")->valueint == 16000); + assert(cJSON_GetObjectItem(audio, "frame_duration")->valueint == 60); + const cJSON* features = cJSON_GetObjectItem(root, "features"); + assert(cJSON_IsTrue(cJSON_GetObjectItem(features, "local_audio"))); + assert(cJSON_IsTrue( + cJSON_GetObjectItem(features, "play_local_sequence"))); + assert(cJSON_IsTrue( + cJSON_GetObjectItem(features, "barge_in_two_phase"))); + assert(cJSON_IsTrue(cJSON_GetObjectItem(features, "mcp"))); + cJSON_Delete(root); + + MemorySnapshot memory; + std::strcpy(memory.child_name.data(), "小明"); + std::strcpy(memory.brain_text.data(), "喜欢星星"); + memory.interaction_count = 42; + root = BuildAndParse( + builder.BuildHello( + 3, &memory, output, sizeof(output), &size), + output, + size); + const cJSON* cache = + cJSON_GetObjectItem(root, "memory_cache"); + assert(cJSON_IsObject(cache)); + assert(std::strcmp( + StringField(cache, "child_name"), "小明") == 0); + assert(cJSON_GetObjectItem( + cache, "interaction_count")->valueint == 42); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildStartListening( + "session-a", output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "session_id"), "session-a") == 0); + assert(std::strcmp(StringField(root, "type"), "listen") == 0); + assert(std::strcmp(StringField(root, "state"), "start") == 0); + assert(std::strcmp(StringField(root, "mode"), "auto") == 0); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildStatus( + 85, 3875, false, "2.0.0", 64, + output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "status") == 0); + assert(cJSON_GetObjectItem(root, "battery")->valueint == 85); + assert(cJSON_GetObjectItem( + root, "battery_voltage_mv")->valueint == 3875); + assert(cJSON_GetObjectItem(root, "volume")->valueint == 64); + cJSON_Delete(root); + + // A negative volume means "unknown": the field is omitted rather than + // reported as 0, which the parent app would render as muted. + root = BuildAndParse( + builder.BuildStatus( + 85, 3875, true, "2.0.0", -1, + output, sizeof(output), &size), + output, + size); + assert(cJSON_GetObjectItem(root, "volume") == nullptr); + assert(cJSON_IsTrue(cJSON_GetObjectItem(root, "charging"))); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildButton( + 3, output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "button") == 0); + assert(cJSON_GetObjectItem(root, "count")->valueint == 3); + cJSON_Delete(root); + assert(!builder.BuildButton( + 2, output, sizeof(output), &size)); + + root = BuildAndParse( + builder.BuildLocalPlaybackState( + "snore_light", true, + output, sizeof(output), &size), + output, + size); + assert(std::strcmp( + StringField(root, "type"), "play_local") == 0); + assert(std::strcmp( + StringField(root, "state"), "start") == 0); + assert(std::strcmp( + StringField(root, "group"), "snore_light") == 0); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildGoodbye( + output, sizeof(output), &size), + output, + size); + assert(std::strcmp( + StringField(root, "type"), "goodbye") == 0); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildLocalPlaybackState( + "snore_light", false, + output, sizeof(output), &size), + output, + size); + assert(std::strcmp( + StringField(root, "state"), "done") == 0); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildAlarmFired( + 42, 1744123460, + output, sizeof(output), &size), + output, + size); + assert(std::strcmp( + StringField(root, "type"), "alarm_fired") == 0); + assert(cJSON_GetObjectItem(root, "id")->valueint == 42); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildCallAction( + "accept", "call-42", + output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "call") == 0); + assert(std::strcmp(StringField(root, "state"), "accept") == 0); + assert(std::strcmp(StringField(root, "call_id"), "call-42") == 0); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildFriendAdd( + "3c:dc:75:fb:12:fc", + "黑马", + "3c:dc:75:fa:73:08", + "BorlaF-7308", + output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "friend_add") == 0); + assert(std::strcmp( + StringField(root, "remote_name"), + "BorlaF-7308") == 0); + cJSON_Delete(root); + + // A mandatory upgrade announcement must omit "optional" entirely: the + // server contract treats an absent field as "device is going to install". + root = BuildAndParse( + builder.BuildOtaNotify( + "当前有最新版本,即将开始升级!请耐心等候", + false, + output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "ota_notify") == 0); + assert(std::strcmp( + StringField(root, "text"), + "当前有最新版本,即将开始升级!请耐心等候") == 0); + assert(cJSON_GetObjectItem(root, "optional") == nullptr); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildOtaNotify( + "当前设备有最新版本,是否进行升级?", + true, + output, sizeof(output), &size), + output, + size); + assert(cJSON_IsTrue(cJSON_GetObjectItem(root, "optional"))); + cJSON_Delete(root); + + assert(!builder.BuildOtaNotify( + "", false, output, sizeof(output), &size)); + assert(!builder.BuildOtaNotify( + nullptr, false, output, sizeof(output), &size)); + + root = BuildAndParse( + builder.BuildStopListening( + "session-a", output, sizeof(output), &size), + output, + size); + assert(std::strcmp(StringField(root, "state"), "stop") == 0); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildAbort( + "session-a", + ConversationInterruptSource::kUserInitiated, + nullptr, + output, + sizeof(output), + &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "abort") == 0); + assert(std::strcmp( + StringField(root, "reason"), + "user_initiated") == 0); + // Nothing was playing, so the field must be absent rather than empty. + assert(cJSON_GetObjectItem(root, "playback_text") == nullptr); + cJSON_Delete(root); + + root = BuildAndParse( + builder.BuildAbort( + "session-a", + ConversationInterruptSource::kWakeWordDetected, + "在很久很久以前", + output, + sizeof(output), + &size), + output, + size); + assert(std::strcmp(StringField(root, "type"), "abort") == 0); + assert(std::strcmp( + StringField(root, "reason"), + "wake_word_detected") == 0); + assert(std::strcmp( + StringField(root, "playback_text"), + "在很久很久以前") == 0); + cJSON_Delete(root); + + // A sentence longer than the 100-byte cap must be cut on a character + // boundary. The previous firmware cut on a byte boundary here and the + // server closed the connection with 1007 (invalid frame payload data), + // which showed up as stories stopping halfway through. + { + std::string long_sentence; + while (long_sentence.size() < 300) { + long_sentence += "小"; // 3 bytes each + } + root = BuildAndParse( + builder.BuildAbort( + "session-a", + ConversationInterruptSource::kUserInitiated, + long_sentence.c_str(), + output, + sizeof(output), + &size), + output, + size); + const char* truncated = + StringField(root, "playback_text"); + const size_t truncated_size = std::strlen(truncated); + assert(truncated_size <= + ProtocolMessageBuilder::kPlaybackTextBytes); + // 100 / 3 = 33 whole characters, so 99 bytes — never 100, which would + // mean the last character was split. + assert(truncated_size % 3 == 0); + assert(std::strncmp( + truncated, + long_sentence.c_str(), + truncated_size) == 0); + cJSON_Delete(root); + } + + char too_small[4]{}; + assert(!builder.BuildPing( + too_small, sizeof(too_small), &size)); +} + +void TestServerHello() +{ + ServerMessageDispatcher dispatcher; + constexpr char kValid[] = + R"({"type":"hello","session_id":"session-a",)" + R"("transport":"websocket","audio_params":{)" + R"("sample_rate":24000,"channels":1,)" + R"("format":"opus","frame_duration":60},)" + R"("server_time":1744123456,"tz_offset":28800,)" + R"("button_map":{"3":"network_switch","4":"nothing"},)" + R"("connection_error_prompts":{)" + R"("server_unreachable":"error","no_network":"no_network"},)" + R"("device_name":"黑马"})"; + ServerCommand command = ParseCommand( + dispatcher, kValid, sizeof(kValid) - 1); + assert(command.type == ServerCommandType::kHello); + assert(std::strcmp(command.session_id.data(), "session-a") == 0); + assert(command.output_sample_rate == 24000); + assert(command.frame_duration_ms == 60); + assert(command.server_time_seconds == 1744123456); + assert(command.timezone_offset_seconds == 28800); + assert(std::strcmp(command.device_name.data(), "黑马") == 0); + assert(command.triple_click_action == + ButtonAction::kNetworkSwitch); + assert(command.quadruple_click_action == + ButtonAction::kNothing); + assert(command.has_server_unreachable_prompt); + assert(command.server_unreachable_prompt == LocalPrompt::kError); + assert(command.has_no_network_prompt); + assert(command.no_network_prompt == LocalPrompt::kNoNetwork); + + ServerCommand in_place; + assert(dispatcher.ParseInto( + kValid, sizeof(kValid) - 1, &in_place)); + assert(in_place.type == ServerCommandType::kHello); + assert(std::strcmp( + in_place.session_id.data(), "session-a") == 0); + assert(!dispatcher.ParseInto( + kValid, sizeof(kValid) - 1, nullptr)); + + constexpr char kWrongRate[] = + R"({"type":"hello","session_id":"x",)" + R"("audio_params":{"sample_rate":16000,)" + R"("frame_duration":60}})"; + command = ParseCommand( + dispatcher, kWrongRate, sizeof(kWrongRate) - 1); + assert(command.type == ServerCommandType::kInvalid); + + constexpr char kWrongVersion[] = + R"({"type":"hello","version":2,"session_id":"x",)" + R"("audio_params":{"sample_rate":24000,)" + R"("frame_duration":60}})"; + command = ParseCommand( + dispatcher, kWrongVersion, sizeof(kWrongVersion) - 1); + assert(command.type == ServerCommandType::kInvalid); +} + +void TestServerCommands() +{ + ServerMessageDispatcher dispatcher; + auto parse = [&dispatcher](const char* json) { + return ParseCommand(dispatcher, json, std::strlen(json)); + }; + + assert(parse("{").type == ServerCommandType::kInvalid); + assert(parse("{}").type == ServerCommandType::kInvalid); + assert(parse(R"({"type":"ping"})").type == + ServerCommandType::kPing); + assert(parse(R"({"type":"pong"})").type == + ServerCommandType::kPong); + assert(parse(R"({"type":"tts","state":"start"})").type == + ServerCommandType::kTtsStart); + assert(parse(R"({"type":"tts","state":"stop"})").type == + ServerCommandType::kTtsStop); + ServerCommand command = parse( + R"({"type":"stt","text":"今天天气怎么样"})"); + assert(command.type == ServerCommandType::kSttText); + assert(std::strcmp( + command.conversation_text.data(), + "今天天气怎么样") == 0); + ServerCommand reused; + assert(dispatcher.ParseInto( + R"({"type":"stt","text":"复用缓冲区"})", + std::strlen(R"({"type":"stt","text":"复用缓冲区"})"), + &reused)); + assert(reused.type == ServerCommandType::kSttText); + assert(dispatcher.ParseInto( + R"({"type":"ping"})", + std::strlen(R"({"type":"ping"})"), + &reused)); + assert(reused.type == ServerCommandType::kPing); + assert(reused.conversation_text[0] == '\0'); + command = parse( + R"({"type":"tts","state":"sentence_start",)" + R"("text":"今天是晴天"})"); + assert(command.type == ServerCommandType::kTtsSentenceStart); + assert(std::strcmp( + command.conversation_text.data(), + "今天是晴天") == 0); + assert(parse(R"({"type":"stt","text":""})").type == + ServerCommandType::kInvalid); + + // llm/emotion is advisory. It must be recognised (not counted as an + // unsupported message) and must survive a missing/blank emotion field. + command = parse(R"({"type":"llm","emotion":"happy"})"); + assert(command.type == ServerCommandType::kLlmEmotion); + assert(std::strcmp( + command.conversation_text.data(), "happy") == 0); + command = parse(R"({"type":"llm"})"); + assert(command.type == ServerCommandType::kLlmEmotion); + assert(command.conversation_text[0] == '\0'); + + assert(parse( + R"({"type":"tts","state":"sentence_start"})") + .type == ServerCommandType::kInvalid); + assert(parse(R"({"type":"future"})").type == + ServerCommandType::kUnsupported); + assert(parse(R"({"type":"wifi_config"})").type == + ServerCommandType::kEnterProvisioning); + + command = + parse(R"({"type":"control","action":"volume","volume":135})"); + assert(command.type == ServerCommandType::kControl); + assert(command.control_action == RemoteControlAction::kVolume); + assert(command.control_value == 100); + command = parse( + R"({"type":"control","action":"wake_word","enabled":false})"); + assert(command.type == ServerCommandType::kControl); + assert(command.control_action == RemoteControlAction::kWakeWord); + assert(command.control_value == 0); + command = parse( + R"({"type":"control","action":"barge_in","enabled":true})"); + assert(command.type == ServerCommandType::kControl); + assert(command.control_action == RemoteControlAction::kBargeIn); + assert(command.control_value == 1); + command = parse( + R"({"type":"control","action":"light_sleep",)" + R"("mode":"idle_sleep"})"); + assert(command.type == ServerCommandType::kControl); + assert(command.control_action == RemoteControlAction::kLightSleep); + command = parse( + R"({"type":"control","action":"led","state":"alert",)" + R"("color":"red","duration_ms":70000})"); + assert(command.type == ServerCommandType::kControl); + assert(command.control_action == RemoteControlAction::kLedAlert); + assert(command.control_value == 60000); + assert(parse( + R"({"type":"control","action":"future"})") + .type == ServerCommandType::kUnsupported); + assert(parse( + R"({"type":"control","action":"barge_in","enabled":1})") + .type == ServerCommandType::kInvalid); + + command = parse(R"({"type":"barge_in","state":"candidate"})"); + assert(command.type == ServerCommandType::kBargeIn); + assert(command.barge_in_state == BargeInDecisionState::kCandidate); + command = parse(R"({"type":"barge_in","state":"rejected"})"); + assert(command.barge_in_state == BargeInDecisionState::kRejected); + command = parse(R"({"type":"barge_in","state":"confirmed"})"); + assert(command.barge_in_state == BargeInDecisionState::kConfirmed); + assert(parse(R"({"type":"barge_in","state":"unknown"})").type == + ServerCommandType::kInvalid); + + command = + parse(R"({"type":"play_local","group":"alarm_wake",)" + R"("index":2})"); + assert(command.type == ServerCommandType::kPlayLocal); + assert(command.local_prompt == LocalPrompt::kAlarmWake); + assert(command.playback_priority == PlaybackPriority::kAlarm); + assert(command.prompt_index == 2); + assert(!command.soft_off_after_playback); + + command = parse( + R"({"type":"play_local","group":"snore_light"})"); + assert(command.type == ServerCommandType::kPlayLocal); + assert(command.local_prompt == LocalPrompt::kSnoreLight); + + command = parse( + R"({"type":"play_local","group":"shutdown"})"); + assert(command.type == ServerCommandType::kPlayLocal); + assert(command.soft_off_after_playback); + + command = parse( + R"({"type":"play_local","group":"shutdown",)" + R"("block_reconnect":false})"); + assert(command.type == ServerCommandType::kPlayLocal); + assert(!command.soft_off_after_playback); + + command = parse( + R"({"type":"play_local","group":"shutdown",)" + R"("post_action":"enter_soft_off"})"); + assert(command.soft_off_after_playback); + + command = parse( + R"({"type":"play_local","group":"not-installed"})"); + assert(command.type == ServerCommandType::kUnsupported); + + command = parse( + R"({"type":"play_local_sequence","sequence":[)" + R"({"group":"activation_prompt"},)" + R"({"group":"digit_4","index":0},)" + R"({"group":"unknown"}]})"); + assert(command.type == ServerCommandType::kPlayLocalSequence); + assert(command.local_sequence.count == 2); + assert(command.local_sequence.items[0].prompt == + LocalPrompt::kActivationDevice); + assert(command.local_sequence.items[1].prompt == + LocalPrompt::kDigit4); + assert(command.local_sequence.items[1].selector == 0); + assert(parse( + R"({"type":"play_local_sequence","sequence":[]})") + .type == ServerCommandType::kUnsupported); + + command = parse( + R"({"type":"memory_sync","child_name":"小明",)" + R"("brain_text":"喜欢星星","interaction_count":43})"); + assert(command.type == ServerCommandType::kMemorySync); + assert(std::strcmp( + command.memory.child_name.data(), "小明") == 0); + assert(command.memory.interaction_count == 43); + assert(parse( + R"({"type":"memory_sync","interaction_count":-1})") + .type == ServerCommandType::kInvalid); + + command = parse(R"({"type":"error","code":4512})"); + assert(command.type == ServerCommandType::kError); + assert(command.error_id == 4512); + + command = parse( + R"({"type":"set_timer","duration":300})"); + assert(command.type == ServerCommandType::kSetTimer); + assert(command.duration_seconds == 300); + assert(parse( + R"({"type":"set_timer","duration":0})") + .type == ServerCommandType::kInvalid); + + command = parse( + R"({"type":"cancel_timer","scope":"all"})"); + assert(command.type == ServerCommandType::kCancelTimer); + assert(command.timer_cancel_scope == TimerCancelScope::kAll); + + command = parse( + R"({"type":"set_alarm","alarm":{"id":42,)" + R"("hour":7,"minute":30,"repeat_mask":62,)" + R"("fire_epoch":0,"label":"wake","enabled":true}})"); + assert(command.type == ServerCommandType::kSetAlarm); + assert(command.alarm.id == 42); + assert(command.alarm.repeat_mask == 62); + + command = parse( + R"({"type":"sync_alarms","alarms":[)" + R"({"id":9,"hour":20,"minute":30,)" + R"("repeat_mask":127,"enabled":true}]})"); + assert(command.type == ServerCommandType::kSyncAlarms); + assert(command.alarms.count == 1); + + command = parse( + R"({"type":"delete_alarm","id":-203000})"); + assert(command.type == ServerCommandType::kDeleteAlarm); + assert(command.alarm_id == kBuiltInFirstDayAlarmId); + assert(parse( + R"({"type":"delete_alarm","id":-1})") + .type == ServerCommandType::kInvalid); + assert(parse( + R"({"type":"delete_alarm","id":0})") + .type == ServerCommandType::kInvalid); + + command = parse( + R"({"type":"alarm_config","set_tone_index":2,)" + R"("wake_tone_index":1})"); + assert(command.type == ServerCommandType::kAlarmConfig); + assert(command.wake_tone_index == 1); + + command = parse( + R"({"type":"call","state":"invite",)" + R"("call_id":"call-42","caller_name":"白马"})"); + assert(command.type == ServerCommandType::kCall); + assert(command.call_state == CallSignalState::kInvite); + assert(std::strcmp(command.call_id.data(), "call-42") == 0); + assert(std::strcmp(command.peer_name.data(), "白马") == 0); + + command = parse( + R"({"type":"call","state":"connected",)" + R"("call_id":"call-42","peer_name":"白马"})"); + assert(command.type == ServerCommandType::kCall); + assert(command.call_state == CallSignalState::kConnected); + + assert(parse( + R"({"type":"call","state":"invite"})") + .type == ServerCommandType::kInvalid); + assert(parse( + R"({"type":"call","state":"unknown",)" + R"("call_id":"call-42"})") + .type == ServerCommandType::kInvalid); +} + +} // namespace + +int main() +{ + TestMessageBuilder(); + TestServerHello(); + TestServerCommands(); + std::cout << "realtime codec tests passed\n"; + return 0; +} diff --git a/host_tests/schedule_test.cc b/host_tests/schedule_test.cc new file mode 100644 index 0000000..3e64112 --- /dev/null +++ b/host_tests/schedule_test.cc @@ -0,0 +1,90 @@ +#include "schedule/alarm_schedule.h" +#include "schedule/reminder_schedule.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +AlarmEntry Alarm( + int32_t id, + uint8_t hour, + uint8_t minute, + uint8_t repeat_mask, + int64_t fire_epoch = 0) +{ + AlarmEntry alarm; + alarm.id = id; + alarm.hour = hour; + alarm.minute = minute; + alarm.repeat_mask = repeat_mask; + alarm.fire_epoch = fire_epoch; + std::strcpy(alarm.label.data(), "test"); + return alarm; +} + +void TestReminderOrderingAndCancellation() +{ + ReminderSchedule schedule; + assert(schedule.Add(3000)); + assert(schedule.Add(1000)); + assert(schedule.Add(2000)); + assert(schedule.next_deadline_ms() == 1000); + assert(schedule.CancelNext()); + assert(schedule.next_deadline_ms() == 2000); + assert(schedule.PopDue(2500) == 1); + assert(schedule.count() == 1); + schedule.CancelAll(); + assert(schedule.count() == 0); +} + +void TestAlarmMatchingAndBuiltIn() +{ + AlarmSchedule schedule; + assert(schedule.EnsureBuiltInFirstDay(false)); + assert(schedule.list().count == 1); + assert(schedule.Upsert(Alarm(42, 7, 30, 1U << 2))); + + CalendarMinute calendar{ + .week_day = 2, + .hour = 7, + .minute = 30, + }; + AlarmFireBatch due = schedule.TakeDue(calendar, 1744126200); + assert(due.count == 1); + assert(due.ids[0] == 42); + assert(due.play_audio); + assert(schedule.TakeDue(calendar, 1744126220).count == 0); + + calendar.week_day = 3; + calendar.hour = 20; + due = schedule.TakeDue(calendar, 1744173000); + assert(due.built_in_first_day); + assert(!due.play_audio); + assert(schedule.first_day_consumed()); +} + +void TestOneShotWindowAndValidation() +{ + const AlarmEntry one_shot = Alarm(7, 8, 15, 0, 2000); + CalendarMinute calendar{.hour = 8, .minute = 15}; + assert(AlarmSchedule::Matches(one_shot, calendar, 2059)); + assert(!AlarmSchedule::Matches(one_shot, calendar, 2060)); + AlarmEntry invalid = one_shot; + invalid.hour = 24; + assert(!AlarmSchedule::Validate(invalid)); +} + +} // namespace + +int main() +{ + TestReminderOrderingAndCancellation(); + TestAlarmMatchingAndBuiltIn(); + TestOneShotWindowAndValidation(); + std::cout << "schedule tests passed\n"; + return 0; +} diff --git a/host_tests/sensor_pipeline_test.cc b/host_tests/sensor_pipeline_test.cc new file mode 100644 index 0000000..a3a9057 --- /dev/null +++ b/host_tests/sensor_pipeline_test.cc @@ -0,0 +1,219 @@ +#include "sensor/battery_estimator.h" +#include "sensor/imu_processor.h" +#include "sensor/sensor_message_codec.h" +#include "sensor/touch_channel.h" + +#include +#include +#include +#include + +namespace { + +using borla::GravityAction; +using borla::BatteryEstimator; +using borla::ImuBatch; +using borla::ImuProcessor; +using borla::ImuSample; +using borla::SensorMessageCodec; +using borla::TouchAction; +using borla::TouchChannel; +using borla::TouchEvent; +using borla::TouchTransition; +using borla::TouchZone; + +void TestTouchTransitionsArePaired() +{ + TouchChannel channel; + for (uint32_t value : + {1000U, 1010U, 990U, 1005U, 995U, 1000U, 1002U, 998U}) { + channel.AddCalibrationSample(value); + } + assert(channel.FinishCalibration()); + assert(channel.threshold() >= 1290.0F); + + TouchTransition transition{}; + bool down = false; + uint64_t down_at_ms = 0; + for (uint64_t now_ms = 0; now_ms <= 400; now_ms += 50) { + if (channel.Process(1800, now_ms, &transition)) { + down = true; + down_at_ms = now_ms; + break; + } + } + assert(down); + assert(transition.action == TouchAction::kDown); + assert(transition.timestamp_ms == down_at_ms); + assert(down_at_ms <= 400); + assert(channel.pressed()); + + assert(channel.Process(1000, down_at_ms + 500, &transition)); + assert(transition.action == TouchAction::kUp); + assert(transition.duration_ms == 500); + assert(!channel.pressed()); +} + +void TestImuBatchAndStillness() +{ + ImuProcessor processor; + size_t full_batches = 0; + size_t partial_batches = 0; + for (uint64_t i = 0; i < 50; ++i) { + const auto output = processor.Process( + ImuSample{0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F}, + i * 20); + if (output.has_batch) { + if (output.batch.count == 5) { + full_batches++; + } else { + partial_batches++; + } + } + } + assert(processor.still()); + assert(full_batches == 9); + assert(partial_batches == 1); + + const auto wake = processor.Process( + ImuSample{0.0F, 0.0F, 1.5F, 0.0F, 0.0F, 0.0F}, + 1000); + assert(!processor.still()); + assert(!wake.has_batch); + for (uint64_t i = 1; i <= 4; ++i) { + const auto output = processor.Process( + ImuSample{0.0F, 0.0F, 1.5F, 0.0F, 0.0F, 0.0F}, + 1000 + i * 20); + if (i < 4) { + assert(!output.has_batch); + } else { + assert(output.has_batch); + assert(output.batch.count == 5); + assert(output.batch.sample_rate_hz == 50); + } + } +} + +void TestGravityStateMachine() +{ + ImuProcessor processor; + processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1000); + processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1020); + processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1040); + const auto freefall = + processor.Process(ImuSample{0.0F, 0.0F, 0.1F}, 1060); + assert(freefall.has_gravity_event); + assert( + freefall.gravity_event.action == GravityAction::kFreefall); + assert(freefall.gravity_event.duration_ms == 60); + + const auto dropped = + processor.Process(ImuSample{0.0F, 0.0F, 5.0F}, 1080); + assert(dropped.has_gravity_event); + assert(dropped.gravity_event.action == GravityAction::kDropped); + assert(std::fabs(dropped.gravity_event.peak_g - 5.0F) < 0.001F); + + ImuProcessor impact_processor; + const auto impact = impact_processor.Process( + ImuSample{0.0F, 0.0F, 7.2F}, 3000); + assert(impact.has_gravity_event); + assert( + impact.gravity_event.action == + GravityAction::kSevereImpact); +} + +void TestProtocolMessages() +{ + char buffer[768]{}; + size_t size = 0; + const TouchEvent touch{ + .zone = TouchZone::kBelly, + .action = TouchAction::kUp, + .timestamp_ms = 123456, + .duration_ms = 800, + }; + assert(SensorMessageCodec::BuildTouch( + touch, buffer, sizeof(buffer), &size)); + assert(std::strstr(buffer, "\"event\":\"touch\"") != nullptr); + assert(std::strstr(buffer, "\"touch_zone\":\"touch_5\"") != nullptr); + assert(std::strstr(buffer, "\"duration_ms\":800") != nullptr); + + ImuBatch batch{}; + batch.sequence = 42; + batch.timestamp_ms_base = 9000; + batch.count = 5; + for (size_t i = 0; i < batch.count; ++i) { + batch.samples[i] = ImuSample{ + 0.1F * static_cast(i), + -0.2F, + 1.0F, + 2.0F, + 3.0F, + 4.0F, + }; + } + assert(SensorMessageCodec::BuildImu( + batch, buffer, sizeof(buffer), &size)); + assert(std::strstr(buffer, "\"event\":\"imu\"") != nullptr); + assert(std::strstr(buffer, "\"seq\":42") != nullptr); + assert(std::strstr(buffer, "\"hz\":50") != nullptr); + assert(!SensorMessageCodec::BuildImu( + batch, buffer, 32, &size)); + + const borla::GravityEvent gravity{ + .action = GravityAction::kFreefall, + .sequence = 12, + .timestamp_ms = 123500, + .duration_ms = 60, + .magnitude_g = 0.22F, + .peak_g = 0.22F, + }; + assert(SensorMessageCodec::BuildGravity( + gravity, buffer, sizeof(buffer), &size)); + assert(std::strstr(buffer, "\"seq\":12") != nullptr); + assert( + std::strstr( + buffer, + "\"gravity_action\":\"freefall\"") != nullptr); + assert(std::strstr(buffer, "\"gravity_zone\":\"body\"") != nullptr); +} + +void TestBatteryEstimator() +{ + assert(!BatteryEstimator::IsPlausibleVoltage(0)); + assert(!BatteryEstimator::IsPlausibleVoltage(39)); + assert(!BatteryEstimator::IsPlausibleVoltage(2499)); + assert(BatteryEstimator::IsPlausibleVoltage(2500)); + assert(BatteryEstimator::IsPlausibleVoltage(3700)); + assert(BatteryEstimator::IsPlausibleVoltage(4500)); + assert(!BatteryEstimator::IsPlausibleVoltage(4501)); + + assert(BatteryEstimator::VoltageToPercent(4090) == 100); + assert(BatteryEstimator::VoltageToPercent(3000) == 0); + assert(BatteryEstimator::VoltageToPercent(3570) == 20); + assert(BatteryEstimator::VoltageToPercent(3520) == 15); + + BatteryEstimator estimator; + estimator.Update(3700); + assert(estimator.initialized()); + assert(!estimator.charging()); + estimator.Update(3715); + estimator.Update(3730); + assert(estimator.charging()); + estimator.Update(3700); + estimator.Update(3670); + assert(!estimator.charging()); +} + +} // namespace + +int main() +{ + TestTouchTransitionsArePaired(); + TestImuBatchAndStillness(); + TestGravityStateMachine(); + TestProtocolMessages(); + TestBatteryEstimator(); + std::cout << "sensor_pipeline_test passed\n"; + return 0; +} diff --git a/host_tests/state_reducer_test.cc b/host_tests/state_reducer_test.cc new file mode 100644 index 0000000..7cbfa66 --- /dev/null +++ b/host_tests/state_reducer_test.cc @@ -0,0 +1,1017 @@ +#include "core/state_reducer.h" +#include "core/remote_behavior.h" + +#include +#include + +namespace { + +using namespace borla; + +RuntimeState BootToRunning() +{ + RuntimeState state; + state = ReduceState( + state, AppEvent::Make(AppEventType::kBootRequested)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kNetworkConnected)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kRealtimeConnected)).next; + return state; +} + +bool HasEffect(const TransitionResult& transition, AppEffectType type) +{ + for (size_t i = 0; i < transition.effect_count; ++i) { + if (transition.effects[i].type == type) { + return true; + } + } + return false; +} + +size_t EffectIndex( + const TransitionResult& transition, + AppEffectType type) +{ + for (size_t i = 0; i < transition.effect_count; ++i) { + if (transition.effects[i].type == type) { + return i; + } + } + return transition.effect_count; +} + +const AppEffect* FindEffect( + const TransitionResult& transition, + AppEffectType type) +{ + for (size_t i = 0; i < transition.effect_count; ++i) { + if (transition.effects[i].type == type) { + return &transition.effects[i]; + } + } + return nullptr; +} + +void TestBootSequence() +{ + const TransitionResult boot = ReduceState( + RuntimeState{}, AppEvent::Make(AppEventType::kBootRequested)); + assert(HasEffect(boot, AppEffectType::kStartAudio)); + const AppEffect* prompt = + FindEffect(boot, AppEffectType::kPlayLocalPrompt); + assert(prompt != nullptr); + assert(prompt->local_prompt == LocalPrompt::kBoot); + assert(prompt->playback_priority == PlaybackPriority::kSystem); + + const RuntimeState state = BootToRunning(); + assert(state.lifecycle == LifecycleState::kRunning); + assert(state.connectivity == ConnectivityState::kOnline); + assert(state.realtime == RealtimeState::kOpen); + assert(state.conversation == ConversationState::kIdle); + assert(ValidateRuntimeState(state).valid); +} + +void TestConversationPlaybackDrain() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + assert(state.conversation == ConversationState::kListening); + + constexpr uint32_t kSessionId = 42; + TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStarted, kSessionId)); + const AppEffect* begin = + FindEffect(transition, AppEffectType::kBeginRemotePlayback); + assert(begin != nullptr); + assert(begin->correlation_id == kSessionId); + assert(begin->playback_priority == PlaybackPriority::kConversation); + state = transition.next; + assert(state.conversation == ConversationState::kSpeaking); + assert(state.playback == PlaybackState::kStreaming); + + transition = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStreamEnded, kSessionId)); + const AppEffect* end = + FindEffect(transition, AppEffectType::kEndPlaybackInput); + assert(end != nullptr); + assert(end->correlation_id == kSessionId); + state = transition.next; + assert(state.playback == PlaybackState::kDraining); + assert(state.conversation == ConversationState::kSpeaking); + + const TransitionResult stale = ReduceState( + state, AppEvent::Make(AppEventType::kPlaybackDrained, 41)); + assert(stale.next.playback == PlaybackState::kDraining); + assert(stale.next.playback_session_id == kSessionId); + + state = ReduceState( + state, AppEvent::Make(AppEventType::kPlaybackDrained, kSessionId)).next; + assert(state.playback == PlaybackState::kIdle); + assert(state.conversation == ConversationState::kListening); + assert(ValidateRuntimeState(state).valid); +} + +void TestLocalPlaybackPreemptsConversationState() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStarted, 88)).next; + + const TransitionResult transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kPlaybackPreempted, + 88, + 0, + 0x80000000U)); + assert(transition.next.playback == PlaybackState::kIdle); + assert(transition.next.playback_session_id == 0); + assert(transition.next.conversation == ConversationState::kIdle); + assert(HasEffect(transition, AppEffectType::kSendAbortSpeaking)); + assert(HasEffect(transition, AppEffectType::kApplyAudioPolicy)); + assert(ValidateRuntimeState(transition.next).valid); +} + +void TestDisconnectRecovery() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + const TransitionResult disconnected = ReduceState( + state, AppEvent::Make(AppEventType::kNetworkDisconnected)); + state = disconnected.next; + + assert(state.connectivity == ConnectivityState::kConnecting); + assert(state.realtime == RealtimeState::kClosed); + assert(state.conversation == ConversationState::kIdle); + assert(state.playback == PlaybackState::kIdle); + assert(HasEffect(disconnected, AppEffectType::kCloseRealtime)); + assert(HasEffect(disconnected, AppEffectType::kStartConnectivity)); + assert(ValidateRuntimeState(state).valid); +} + +void TestExclusiveUpgradeState() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kUpgradeRequested, 7)).next; + + assert(state.lifecycle == LifecycleState::kUpgrading); + assert(state.connectivity == ConnectivityState::kOnline); + assert(state.realtime == RealtimeState::kClosed); + assert(state.conversation == ConversationState::kIdle); + assert(!HasEffect( + ReduceState( + BootToRunning(), + AppEvent::Make(AppEventType::kUpgradeRequested, 7)), + AppEffectType::kStopConnectivity)); + assert(ValidateRuntimeState(state).valid); +} + +void TestSingleClickControlsConversation() +{ + RuntimeState state = BootToRunning(); + + TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(transition.next.conversation == ConversationState::kListening); + assert(HasEffect(transition, AppEffectType::kSendStartListening)); + assert( + EffectIndex(transition, AppEffectType::kSendStartListening) < + EffectIndex(transition, AppEffectType::kApplyAudioPolicy)); + + state = transition.next; + transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(transition.next.conversation == ConversationState::kIdle); + assert(HasEffect(transition, AppEffectType::kSendStopListening)); + assert(HasEffect(transition, AppEffectType::kCancelPlayback)); + assert(ValidateRuntimeState(transition.next).valid); +} + +void TestSingleClickInterruptsSpeaking() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStarted, 88)).next; + + const TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(transition.next.conversation == ConversationState::kListening); + assert(transition.next.playback == PlaybackState::kIdle); + assert(transition.next.playback_session_id == 0); + assert(HasEffect(transition, AppEffectType::kCancelPlayback)); + assert(HasEffect(transition, AppEffectType::kSendAbortSpeaking)); + assert(HasEffect(transition, AppEffectType::kSendStartListening)); + const AppEffect* abort = FindEffect( + transition, AppEffectType::kSendAbortSpeaking); + assert(abort != nullptr); + assert(abort->interrupt_source == + ConversationInterruptSource::kUserInitiated); + assert(ValidateRuntimeState(transition.next).valid); +} + +void TestServerArbitratesNaturalBargeIn() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStarted, 100)).next; + + const TransitionResult candidate = ReduceState( + state, + AppEvent::Make(AppEventType::kBargeInCandidate)); + assert(candidate.next.conversation == ConversationState::kSpeaking); + assert(candidate.next.playback == PlaybackState::kStreaming); + assert(HasEffect(candidate, AppEffectType::kPausePlayback)); + assert(!HasEffect(candidate, AppEffectType::kCancelPlayback)); + assert(!HasEffect(candidate, AppEffectType::kSendAbortSpeaking)); + assert(!HasEffect(candidate, AppEffectType::kSendStartListening)); + assert(ValidateRuntimeState(candidate.next).valid); + + const TransitionResult rejected = ReduceState( + candidate.next, + AppEvent::Make(AppEventType::kBargeInRejected)); + assert(rejected.next.conversation == ConversationState::kSpeaking); + assert(HasEffect(rejected, AppEffectType::kResumePlayback)); + assert(!HasEffect(rejected, AppEffectType::kCancelPlayback)); + + const TransitionResult confirmed = ReduceState( + candidate.next, + AppEvent::Make(AppEventType::kBargeInConfirmed)); + assert(confirmed.next.conversation == ConversationState::kIdle); + assert(confirmed.next.playback == PlaybackState::kIdle); + assert(HasEffect(confirmed, AppEffectType::kResumePlayback)); + assert(HasEffect(confirmed, AppEffectType::kCancelPlayback)); + assert(!HasEffect(confirmed, AppEffectType::kSendAbortSpeaking)); + assert(!HasEffect(confirmed, AppEffectType::kSendStartListening)); + assert(ValidateRuntimeState(confirmed.next).valid); + + const RuntimeState draining = ReduceState( + state, + AppEvent::Make(AppEventType::kTtsStreamEnded, 100)).next; + assert(draining.playback == PlaybackState::kDraining); + const TransitionResult tail_candidate = ReduceState( + draining, + AppEvent::Make(AppEventType::kBargeInCandidate)); + assert(HasEffect(tail_candidate, AppEffectType::kPausePlayback)); + assert(!HasEffect(tail_candidate, AppEffectType::kCancelPlayback)); + + state = BootToRunning(); + const TransitionResult ignored = ReduceState( + state, + AppEvent::Make(AppEventType::kBargeInCandidate)); + assert(ignored.next.conversation == ConversationState::kIdle); + assert(!HasEffect(ignored, AppEffectType::kPausePlayback)); +} + +void TestWakeWordInterruptsSpeaking() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStarted, 99)).next; + + const TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)); + assert(transition.next.conversation == ConversationState::kListening); + assert(transition.next.playback == PlaybackState::kIdle); + assert(HasEffect(transition, AppEffectType::kCancelPlayback)); + assert(HasEffect(transition, AppEffectType::kSendAbortSpeaking)); + assert(HasEffect(transition, AppEffectType::kSendStartListening)); + const AppEffect* abort = FindEffect( + transition, AppEffectType::kSendAbortSpeaking); + assert(abort != nullptr); + assert(abort->interrupt_source == + ConversationInterruptSource::kWakeWordDetected); + // The wake word always answers "我在" out loud — including when it cuts a + // playing reply. A button press through the same path stays silent. + assert(HasEffect(transition, AppEffectType::kPlayDetachedPrompt)); + assert(ValidateRuntimeState(transition.next).valid); + + state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStarted, 101)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kTtsStreamEnded, 101)).next; + assert(state.playback == PlaybackState::kDraining); + + const TransitionResult tail_transition = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)); + assert(tail_transition.next.conversation == + ConversationState::kListening); + assert(tail_transition.next.playback == PlaybackState::kIdle); + assert(HasEffect(tail_transition, AppEffectType::kCancelPlayback)); + assert(HasEffect(tail_transition, AppEffectType::kSendAbortSpeaking)); + assert(HasEffect(tail_transition, AppEffectType::kSendStartListening)); + assert(ValidateRuntimeState(tail_transition.next).valid); +} + +// Entering provisioning must be audible, and finishing it must be audible. +// Both prompts existed in the previous firmware and were embedded in this one +// but never played, leaving a first-boot device completely silent. +void TestProvisioningIsAudible() +{ + RuntimeState state = BootToRunning(); + TransitionResult entered = ReduceState( + state, AppEvent::Make(AppEventType::kProvisioningRequested)); + assert(entered.next.lifecycle == LifecycleState::kProvisioning); + assert(HasEffect(entered, AppEffectType::kPlayDetachedPrompt)); + const size_t prompt_index = + EffectIndex(entered, AppEffectType::kPlayDetachedPrompt); + assert(entered.effects[prompt_index].local_prompt == + LocalPrompt::kProvisioning); + assert(entered.effects[prompt_index].playback_priority == + PlaybackPriority::kSystem); + // The prompt must survive the teardown that happens in the same + // transition, so it has to be ordered after the playback cancellation. + assert(prompt_index > + EffectIndex(entered, AppEffectType::kCancelPlayback)); + // Detached on purpose: provisioning is an exclusive lifecycle and the + // invariant checker requires playback to stay idle inside it. + assert(entered.next.playback == PlaybackState::kIdle); + assert(ValidateRuntimeState(entered.next).valid); + + TransitionResult saved = ReduceState( + entered.next, + AppEvent::Make(AppEventType::kProvisioningWifiSaved)); + assert(HasEffect(saved, AppEffectType::kPlayDetachedPrompt)); + assert(saved.effects[EffectIndex(saved, AppEffectType::kPlayDetachedPrompt)] + .local_prompt == LocalPrompt::kWifiSuccess); + // Credentials being saved does not itself leave provisioning; the + // miniprogram still drives the reboot, as the previous firmware did. + assert(saved.next.lifecycle == LifecycleState::kProvisioning); + assert(ValidateRuntimeState(saved.next).valid); + + // Outside provisioning the event is inert rather than producing a stray + // "配网成功啦" in the middle of a conversation. + TransitionResult stray = ReduceState( + BootToRunning(), + AppEvent::Make(AppEventType::kProvisioningWifiSaved)); + assert(!HasEffect(stray, AppEffectType::kPlayDetachedPrompt)); + assert(stray.next.lifecycle == LifecycleState::kRunning); +} + +void TestButtonLifecycleRequests() +{ + RuntimeState state = BootToRunning(); + TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 2)); + assert(transition.next.lifecycle == LifecycleState::kProvisioning); + assert(HasEffect(transition, AppEffectType::kEnterProvisioning)); + assert(HasEffect(transition, AppEffectType::kSendGoodbye)); + assert(ValidateRuntimeState(transition.next).valid); + + // Long press plays the shutdown prompt first and only powers down once it + // has drained, matching the previous firmware. Going straight to + // kEnterSoftOff left the device silent on shutdown. + state = BootToRunning(); + transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonLongPressed)); + assert(transition.next.lifecycle == LifecycleState::kShuttingDown); + assert(!HasEffect(transition, AppEffectType::kEnterSoftOff)); + assert(HasEffect(transition, AppEffectType::kPlayLocalPrompt)); + assert(transition.effects[ + EffectIndex(transition, AppEffectType::kPlayLocalPrompt)] + .local_prompt == LocalPrompt::kShutdown); + assert(transition.next.pending_soft_off_after_playback); + assert(HasEffect(transition, AppEffectType::kSendGoodbye)); + assert(ValidateRuntimeState(transition.next).valid); + + const TransitionResult drained = ReduceState( + transition.next, + AppEvent::Make( + AppEventType::kPlaybackDrained, + transition.next.playback_session_id)); + assert(drained.next.lifecycle == LifecycleState::kSoftOff); + assert(HasEffect(drained, AppEffectType::kEnterSoftOff)); + assert(ValidateRuntimeState(drained.next).valid); +} + +void TestServerLocalPromptAndShutdownDrain() +{ + RuntimeState state = BootToRunning(); + TransitionResult transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalPromptRequested, + 3, + static_cast(LocalPrompt::kWelcome), + static_cast(PlaybackPriority::kLocalPrompt))); + const AppEffect* prompt = + FindEffect(transition, AppEffectType::kPlayLocalPrompt); + assert(prompt != nullptr); + assert(prompt->local_prompt == LocalPrompt::kWelcome); + assert(prompt->prompt_selector == 2); + state = transition.next; + assert(state.conversation == ConversationState::kIdle); + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalPromptStarted, + 301, + static_cast(LocalPrompt::kWelcome))); + state = transition.next; + assert(state.local_prompt_active); + assert(state.active_local_prompt == LocalPrompt::kWelcome); + assert(state.playback_session_id == 301); + assert(HasEffect( + transition, AppEffectType::kSendLocalPlaybackStarted)); + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kPlaybackDrained, 301)); + state = transition.next; + assert(!state.local_prompt_active); + assert(HasEffect( + transition, AppEffectType::kSendLocalPlaybackDone)); + assert(state.conversation == ConversationState::kListening); + assert(ValidateRuntimeState(state).valid); + + RuntimeState alert_state = state; + alert_state.alert_ringing = true; + transition = ReduceState( + alert_state, + AppEvent::Make( + AppEventType::kLocalPromptRequested, + 0, + static_cast(LocalPrompt::kWelcome), + static_cast(PlaybackPriority::kLocalPrompt))); + assert(!HasEffect( + transition, AppEffectType::kPlayLocalPrompt)); + assert(transition.next.alert_ringing); + + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kShutdownPromptRequested)); + state = transition.next; + assert(state.lifecycle == LifecycleState::kShuttingDown); + assert(state.playback == PlaybackState::kDraining); + assert(state.playback_session_id == 0); + assert(state.pending_soft_off_after_playback); + prompt = FindEffect(transition, AppEffectType::kPlayLocalPrompt); + assert(prompt != nullptr); + assert(prompt->local_prompt == LocalPrompt::kShutdown); + assert(HasEffect(transition, AppEffectType::kSendGoodbye)); + assert(HasEffect(transition, AppEffectType::kCloseRealtime)); + assert(HasEffect(transition, AppEffectType::kStopConnectivity)); + assert(ValidateRuntimeState(state).valid); + + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kPlaybackDrained, 0x80000001U)); + assert(transition.next.lifecycle == LifecycleState::kSoftOff); + assert(transition.next.playback == PlaybackState::kIdle); + assert(!transition.next.pending_soft_off_after_playback); + assert(HasEffect(transition, AppEffectType::kEnterSoftOff)); + assert(ValidateRuntimeState(transition.next).valid); +} + +void TestConfiguredMultiClickActions() +{ + RuntimeState state = BootToRunning(); + TransitionResult transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kButtonClicked, + 0, + 3, + static_cast( + ButtonAction::kNetworkSwitch))); + assert(HasEffect( + transition, AppEffectType::kSwitchNetwork)); + assert(!transition.next.friend_mode); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kButtonClicked, + 0, + 4, + static_cast( + ButtonAction::kFriendMode))); + assert(HasEffect( + transition, AppEffectType::kStartFriendMode)); + assert(transition.next.friend_mode); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kButtonClicked, + 0, + 3, + static_cast( + ButtonAction::kNothing))); + assert(HasEffect( + transition, AppEffectType::kSendButtonClick)); + assert(!HasEffect( + transition, AppEffectType::kStartFriendMode)); + assert(!HasEffect( + transition, AppEffectType::kSwitchNetwork)); + assert(!transition.next.friend_mode); +} + +void TestSingleClickControlsCalls() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kIncomingCall)).next; + + TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(transition.next.call == CallState::kRinging); + assert(HasEffect(transition, AppEffectType::kCancelPlayback)); + assert(HasEffect(transition, AppEffectType::kSendAcceptCall)); + + constexpr uint32_t kCallSession = 0x80000012U; + state = ReduceState( + state, + AppEvent::Make( + AppEventType::kCallConnected, + kCallSession)).next; + assert(state.playback == PlaybackState::kStreaming); + assert(state.playback_session_id == kCallSession); + transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(transition.next.call == CallState::kActive); + assert(HasEffect(transition, AppEffectType::kSendHangupCall)); + assert(ValidateRuntimeState(transition.next).valid); + + state = BootToRunning(); + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kOutgoingCall, + kCallSession)); + assert(transition.next.call == CallState::kCalling); + const AppEffect* wait_prompt = + FindEffect(transition, AppEffectType::kPlayLocalPrompt); + assert(wait_prompt != nullptr); + assert(wait_prompt->local_prompt == LocalPrompt::kCallWait); + state = transition.next; + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kCallConnected, + kCallSession)); + assert(transition.next.call == CallState::kActive); + const AppEffect* playback = + FindEffect(transition, AppEffectType::kBeginRemotePlayback); + assert(playback != nullptr); + assert(playback->playback_priority == PlaybackPriority::kCall); + assert(ValidateRuntimeState(transition.next).valid); + + transition = ReduceState( + transition.next, + AppEvent::Make( + AppEventType::kCallEnded, + kCallSession)); + assert(transition.next.call == CallState::kInactive); + assert(transition.next.playback == PlaybackState::kIdle); + assert(HasEffect(transition, AppEffectType::kCancelPlayback)); + assert(ValidateRuntimeState(transition.next).valid); +} + +void TestIdleSleepAndAlertFlow() +{ + RuntimeState state = BootToRunning(); + TransitionResult transition = ReduceState( + state, AppEvent::Make(AppEventType::kIdleCheckDue)); + state = transition.next; + assert(state.idle_check_prompt); + assert(state.playback == PlaybackState::kDraining); + assert(FindEffect( + transition, AppEffectType::kPlayLocalPrompt) + ->local_prompt == LocalPrompt::kIdleCheck); + assert(ValidateRuntimeState(state).valid); + + state = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalPromptStarted, + 501, + static_cast(LocalPrompt::kIdleCheck))) + .next; + assert(state.playback_session_id == 501); + state = ReduceState( + state, + AppEvent::Make(AppEventType::kPlaybackDrained, 501)) + .next; + assert(!state.idle_check_prompt); + assert(state.conversation == ConversationState::kListening); + + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kIdleResponseExpired)); + state = transition.next; + assert(state.idle_sleeping); + assert(state.realtime == RealtimeState::kClosed); + assert(HasEffect(transition, AppEffectType::kCloseRealtime)); + assert(ValidateRuntimeState(state).valid); + + transition = ReduceState( + state, AppEvent::Make(AppEventType::kAlarmDue)); + state = transition.next; + assert(state.alert_ringing); + assert(!state.idle_sleeping); + assert(state.realtime == RealtimeState::kOpening); + assert(HasEffect(transition, AppEffectType::kStartAlert)); + assert(HasEffect(transition, AppEffectType::kOpenRealtime)); + assert(ValidateRuntimeState(state).valid); + + transition = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(!transition.next.alert_ringing); + assert(HasEffect(transition, AppEffectType::kStopAlert)); +} + +void TestAlertDeferredUntilStartupCompletes() +{ + RuntimeState state; + state = ReduceState( + state, AppEvent::Make(AppEventType::kBootRequested)).next; + state = ReduceState( + state, AppEvent::Make(AppEventType::kAlarmDue)).next; + assert(state.pending_alert); + state = ReduceState( + state, AppEvent::Make(AppEventType::kNetworkConnected)).next; + const TransitionResult connected = ReduceState( + state, AppEvent::Make(AppEventType::kRealtimeConnected)); + assert(connected.next.lifecycle == LifecycleState::kRunning); + assert(connected.next.alert_ringing); + assert(!connected.next.pending_alert); + assert(HasEffect(connected, AppEffectType::kStartAlert)); + assert(ValidateRuntimeState(connected.next).valid); +} + +void TestFourClicksRequestNetworkSwitch() +{ + RuntimeState state = BootToRunning(); + const TransitionResult transition = ReduceState( + state, + AppEvent::Make(AppEventType::kButtonClicked, 0, 4)); + assert(HasEffect(transition, AppEffectType::kSwitchNetwork)); + + state.lifecycle = LifecycleState::kUpgrading; + const TransitionResult upgrading = ReduceState( + state, + AppEvent::Make(AppEventType::kButtonClicked, 0, 4)); + assert(!HasEffect(upgrading, AppEffectType::kSwitchNetwork)); +} + +void TestTripleClickFriendMode() +{ + RuntimeState state = BootToRunning(); + TransitionResult transition = ReduceState( + state, + AppEvent::Make(AppEventType::kButtonClicked, 0, 3)); + state = transition.next; + assert(state.friend_mode); + assert(state.realtime == RealtimeState::kClosed); + assert(HasEffect(transition, AppEffectType::kCloseRealtime)); + assert(HasEffect(transition, AppEffectType::kStartFriendMode)); + assert(ValidateRuntimeState(state).valid); + + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kButtonClicked, 0, 3)); + state = transition.next; + assert(state.friend_mode); + assert(state.realtime == RealtimeState::kClosed); + assert(HasEffect(transition, AppEffectType::kStopFriendMode)); + assert(!HasEffect(transition, AppEffectType::kOpenRealtime)); + assert(ValidateRuntimeState(state).valid); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kFriendModeEnded, + 0, + 0, + 1)); + state = transition.next; + assert(!state.friend_mode); + assert(state.realtime == RealtimeState::kOpening); + assert(HasEffect(transition, AppEffectType::kOpenRealtime)); + assert(ValidateRuntimeState(state).valid); + + state = BootToRunning(); + state.call = CallState::kActive; + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kButtonClicked, 0, 3)); + assert(!transition.next.friend_mode); + assert(!HasEffect( + transition, AppEffectType::kStartFriendMode)); +} + +void TestLocalSequenceLifecycle() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, + AppEvent::Make(AppEventType::kWakeWordDetected)).next; + TransitionResult transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalSequenceRequested, 7)); + state = transition.next; + assert(state.conversation == ConversationState::kIdle); + assert(state.playback == PlaybackState::kIdle); + assert(HasEffect( + transition, AppEffectType::kSendStopListening)); + assert(HasEffect( + transition, AppEffectType::kCancelPlayback)); + assert(ValidateRuntimeState(state).valid); + + state = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalSequenceStarted, 701)) + .next; + assert(state.conversation == ConversationState::kSpeaking); + assert(state.playback == PlaybackState::kDraining); + assert(state.playback_session_id == 701); + assert(ValidateRuntimeState(state).valid); + + state = ReduceState( + state, + AppEvent::Make(AppEventType::kPlaybackDrained, 701)) + .next; + assert(state.conversation == ConversationState::kListening); + assert(state.playback == PlaybackState::kIdle); + assert(ValidateRuntimeState(state).valid); + + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kActivationReplayDue, 7)); + assert(transition.next.conversation == ConversationState::kIdle); + assert(HasEffect( + transition, AppEffectType::kSendStopListening)); + + state = BootToRunning(); + state.call = CallState::kActive; + transition = ReduceState( + state, + AppEvent::Make(AppEventType::kActivationReplayDue, 7)); + assert(transition.next.call == CallState::kActive); + assert(transition.effect_count == 0); +} + +void TestRemoteRuntimeControls() +{ + RuntimeState state = BootToRunning(); + TransitionResult transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kAudioVolumeRequested, 0, 72)); + const AppEffect* volume = + FindEffect(transition, AppEffectType::kSetAudioVolume); + assert(volume != nullptr); + assert(volume->correlation_id == 72); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kWakeWordControlRequested, 0, 0)); + const AppEffect* wake = FindEffect( + transition, AppEffectType::kSetWakeWordEnabled); + assert(wake != nullptr); + assert(wake->correlation_id == 0); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kBargeInControlRequested, 0, 1)); + const AppEffect* barge = FindEffect( + transition, AppEffectType::kSetBargeInEnabled); + assert(barge != nullptr); + assert(barge->correlation_id == 1); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kRemoteIdleSleepRequested)); + assert(transition.next.idle_sleeping); + assert(transition.next.realtime == RealtimeState::kClosed); + assert(HasEffect( + transition, AppEffectType::kSendGoodbye)); + assert(HasEffect( + transition, AppEffectType::kCloseRealtime)); + wake = FindEffect( + transition, AppEffectType::kSetWakeWordEnabled); + assert(wake != nullptr); + assert(wake->correlation_id == 1); + assert(ValidateRuntimeState(transition.next).valid); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kLedAlertRequested, 0, 5000)); + const AppEffect* led_alert = FindEffect( + transition, AppEffectType::kShowTemporaryLedAlert); + assert(led_alert != nullptr); + assert(led_alert->correlation_id == 5000); + + transition = ReduceState( + state, + AppEvent::Make( + AppEventType::kAudioVolumeRequested, 0, 101)); + assert(!HasEffect( + transition, AppEffectType::kSetAudioVolume)); +} + +} // namespace + +void TestInterruptedReplyPlaysErrorPrompt() +{ + RuntimeState state = BootToRunning(); + state = ReduceState( + state, + AppEvent::Make(AppEventType::kTtsStarted, 900)) + .next; + assert(state.conversation == ConversationState::kSpeaking); + + // Playback of a server reply dies (stall timeout / decode failure). + const TransitionResult failed = ReduceState( + state, AppEvent::Make(AppEventType::kPlaybackFailed, 900)); + assert(HasEffect( + failed, AppEffectType::kRequestConnectionErrorPrompt)); + assert(HasEffect(failed, AppEffectType::kReportError)); + assert(failed.next.conversation == ConversationState::kIdle); + assert(ValidateRuntimeState(failed.next).valid); + + // A failing local prompt already has its own feedback path and must not + // stack a second error prompt on top. + RuntimeState local = BootToRunning(); + local = ReduceState( + local, + AppEvent::Make( + AppEventType::kLocalPromptStarted, + 901, + static_cast(LocalPrompt::kStoryExpired))) + .next; + assert(local.local_prompt_active); + const TransitionResult local_failed = ReduceState( + local, AppEvent::Make(AppEventType::kPlaybackFailed, 901)); + assert(!HasEffect( + local_failed, AppEffectType::kRequestConnectionErrorPrompt)); + + // Idle playback failure (nothing was being spoken) stays silent too. + RuntimeState idle = BootToRunning(); + const TransitionResult idle_failed = ReduceState( + idle, AppEvent::Make(AppEventType::kPlaybackFailed, 0)); + assert(!HasEffect( + idle_failed, AppEffectType::kRequestConnectionErrorPrompt)); +} + +void TestWakeWordPlaysAcknowledgement() +{ + RuntimeState state = BootToRunning(); + assert(state.conversation == ConversationState::kIdle); + + const TransitionResult woken = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)); + // The acknowledgement must be detached: the device is already listening + // and must stay there, so no kPlayLocalPrompt / kSpeaking transition. + assert(woken.next.conversation == ConversationState::kListening); + assert(HasEffect(woken, AppEffectType::kPlayDetachedPrompt)); + assert(!HasEffect(woken, AppEffectType::kPlayLocalPrompt)); + assert(HasEffect(woken, AppEffectType::kSendStartListening)); + assert(ValidateRuntimeState(woken.next).valid); + for (size_t i = 0; i < woken.effect_count; ++i) { + if (woken.effects[i].type == + AppEffectType::kPlayDetachedPrompt) { + assert(woken.effects[i].local_prompt == + LocalPrompt::kWakeResponse); + } + } + + // A button press is not a wake word and stays silent. + const TransitionResult clicked = ReduceState( + state, AppEvent::Make(AppEventType::kButtonClicked, 0, 1)); + assert(clicked.next.conversation == ConversationState::kListening); + assert(!HasEffect(clicked, AppEffectType::kPlayDetachedPrompt)); +} + +void TestServerWelcomeSkippedWhileListening() +{ + // Wake word opens the session: "我在" plays, microphone is live. + RuntimeState state = BootToRunning(); + state = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)) + .next; + assert(state.conversation == ConversationState::kListening); + + // The server greets the new session with play_local welcome. It must be + // acked (started + done) but NOT played: no playback teardown, no + // stop-listening, and the turn stays open. + const TransitionResult greeted = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalPromptRequested, + 0, + static_cast(LocalPrompt::kWelcome), + static_cast(PlaybackPriority::kLocalPrompt))); + assert(greeted.next.conversation == ConversationState::kListening); + assert(!HasEffect(greeted, AppEffectType::kPlayLocalPrompt)); + assert(!HasEffect(greeted, AppEffectType::kCancelPlayback)); + assert(!HasEffect(greeted, AppEffectType::kSendStopListening)); + assert(HasEffect(greeted, AppEffectType::kSendLocalPlaybackStarted)); + assert(HasEffect(greeted, AppEffectType::kSendLocalPlaybackDone)); + + // Outside a live turn the welcome still plays normally. + RuntimeState idle = BootToRunning(); + const TransitionResult played = ReduceState( + idle, + AppEvent::Make( + AppEventType::kLocalPromptRequested, + 0, + static_cast(LocalPrompt::kWelcome), + static_cast(PlaybackPriority::kLocalPrompt))); + assert(HasEffect(played, AppEffectType::kPlayLocalPrompt)); +} + +void TestWakeAcknowledgedEvenAfterWelcome() +{ + RuntimeState state = BootToRunning(); + + // Welcome greeting plays and drains into listening, then the turn ends. + state = ReduceState( + state, + AppEvent::Make( + AppEventType::kLocalPromptStarted, + 501, + static_cast(LocalPrompt::kWelcome))) + .next; + state = ReduceState( + state, + AppEvent::Make(AppEventType::kPlaybackDrained, 501)) + .next; + assert(state.conversation == ConversationState::kListening); + state = ReduceState( + state, + AppEvent::Make( + AppEventType::kConversationStopRequested)) + .next; + assert(state.conversation == ConversationState::kIdle); + + // Every wake word answers "我在" out loud — including the first one right + // after the welcome greeting. Product decision: the acknowledgement is + // unconditional. + const TransitionResult first = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)); + assert(first.next.conversation == ConversationState::kListening); + assert(HasEffect(first, AppEffectType::kPlayDetachedPrompt)); + state = first.next; + + state = ReduceState( + state, + AppEvent::Make( + AppEventType::kConversationStopRequested)) + .next; + const TransitionResult second = ReduceState( + state, AppEvent::Make(AppEventType::kWakeWordDetected)); + assert(HasEffect(second, AppEffectType::kPlayDetachedPrompt)); +} + +int main() +{ + TestBootSequence(); + TestConversationPlaybackDrain(); + TestLocalPlaybackPreemptsConversationState(); + TestDisconnectRecovery(); + TestExclusiveUpgradeState(); + TestSingleClickControlsConversation(); + TestSingleClickInterruptsSpeaking(); + TestWakeWordInterruptsSpeaking(); + TestServerArbitratesNaturalBargeIn(); + TestButtonLifecycleRequests(); + TestProvisioningIsAudible(); + TestServerLocalPromptAndShutdownDrain(); + TestConfiguredMultiClickActions(); + TestSingleClickControlsCalls(); + TestIdleSleepAndAlertFlow(); + TestAlertDeferredUntilStartupCompletes(); + TestFourClicksRequestNetworkSwitch(); + TestTripleClickFriendMode(); + TestLocalSequenceLifecycle(); + TestRemoteRuntimeControls(); + TestInterruptedReplyPlaysErrorPrompt(); + TestWakeWordPlaysAcknowledgement(); + TestServerWelcomeSkippedWhileListening(); + TestWakeAcknowledgedEvenAfterWelcome(); + + std::cout << "state reducer tests passed\n"; + return 0; +} diff --git a/host_tests/task_stack_budget_test.cc b/host_tests/task_stack_budget_test.cc new file mode 100644 index 0000000..54b2549 --- /dev/null +++ b/host_tests/task_stack_budget_test.cc @@ -0,0 +1,59 @@ +#include "core/task_stack_budget.h" + +#include +#include + +int main() +{ + using namespace borla::task_stack_budget; + + // Regression floors. Floors below must always be <= the budgets in + // core/task_stack_budget.h; they exist to stop an accidental edit from + // silently shrinking a stack below the last field-validated size. + // + // Connectivity-class budgets were re-derived from device high-water marks + // taken after a full TLS + OTA + BLE provisioning cycle, because every + // byte of those stacks is .bss and therefore comes off the front of the + // main internal heap — the pool BLE provisioning exhausts when it re-inits + // the WiFi driver next to the BT controller. Measured peak usage / floor + // connectivity2 2492 / 5120 dual_network2 3136 / 4096 + // friend_service2 960 / 3072 alarm2 1172 / 3072 + // websocket2 5964 / 10240 (TLS handshake headroom) + // capture2 ~6.3 KB measured / 10 KB budget (internal RAM) + // + // kCaptureEncoderBytes is NOT lowered with them: the 24 KB trim tripped + // the stack canary inside silk_NSQ_del_dec_c (the opus_encode() chain + // alone walked 24,240 bytes), so the floor stays at the last + // field-validated 32 KB. That stack is PSRAM; headroom there is free. + static_assert(kPlaybackBytes >= 36 * 1024); + static_assert(kCaptureBytes >= 10 * 1024); + static_assert(kConnectivityManagerBytes >= 5 * 1024); + static_assert(kDualNetworkBytes >= 4 * 1024); + static_assert(kWebsocketTransportBytes >= 10 * 1024); + static_assert(kFriendServiceBytes >= 3 * 1024); + static_assert(kAlarmServiceBytes >= 3 * 1024); + static_assert(kRuntimeDiagnosticsBytes >= 8 * 1024); + static_assert(kLocalPromptProducerBytes >= 6 * 1024); + static_assert(kCaptureEncoderBytes >= 32 * 1024); + + // The real-time ordering is the point, not the absolute numbers: the two + // deadline-bound loops must outrank the codec, and capture must outrank + // playback because it is the one that cannot be late without corrupting + // the AEC's alignment. + using namespace borla::task_priority; + static_assert(kCaptureLoop > kPlaybackLoop); + static_assert(kPlaybackLoop > kAudioCodec); + + assert(kPlaybackBytes % 1024 == 0); + assert(kCaptureBytes % 1024 == 0); + assert(kConnectivityManagerBytes % 1024 == 0); + assert(kDualNetworkBytes % 1024 == 0); + assert(kWebsocketTransportBytes % 1024 == 0); + assert(kFriendServiceBytes % 1024 == 0); + assert(kAlarmServiceBytes % 1024 == 0); + assert(kRuntimeDiagnosticsBytes % 1024 == 0); + assert(kLocalPromptProducerBytes % 1024 == 0); + + std::cout << "task stack budgets passed\n"; + return 0; +} diff --git a/host_tests/trace_context_test.cc b/host_tests/trace_context_test.cc new file mode 100644 index 0000000..1ea3a8c --- /dev/null +++ b/host_tests/trace_context_test.cc @@ -0,0 +1,107 @@ +#include "diagnostics/trace_context.h" + +#include +#include +#include +#include + +namespace { + +using namespace borla; + +void TestFormatIdShape() +{ + std::array output{}; + const size_t size = TraceContext::FormatId( + "turn", "AA-BB-CC-DD-EE-FF", 123456, + output.data(), output.size()); + assert(std::strcmp( + output.data(), "turn-AA-BB-CC-DD-EE-FF-123456") == 0); + assert(size == std::strlen(output.data())); +} + +void TestFormatIdDefaultsAndTruncation() +{ + std::array output{}; + + // Missing inputs must still produce a greppable id, never an empty one. + TraceContext::FormatId( + nullptr, nullptr, 7, output.data(), output.size()); + assert(std::strcmp(output.data(), "dev-dev-7") == 0); + TraceContext::FormatId("", "", 7, output.data(), output.size()); + assert(std::strcmp(output.data(), "dev-dev-7") == 0); + + // A short buffer truncates and stays NUL-terminated, and the reported + // length never points past the buffer. + std::array tiny{}; + const size_t size = TraceContext::FormatId( + "turn", "AA-BB-CC", 999999, tiny.data(), tiny.size()); + assert(tiny[tiny.size() - 1] == '\0'); + assert(size == std::strlen(tiny.data())); + assert(size < tiny.size()); + + // Zero capacity must not write anything. + assert(TraceContext::FormatId( + "turn", "AA", 1, output.data(), 0) == 0); + assert(TraceContext::FormatId( + "turn", "AA", 1, nullptr, 16) == 0); +} + +void TestScopeLifecycle() +{ + // Before anything is set, ids read as "-" rather than null. + assert(TraceContext::TraceId() != nullptr); + assert(TraceContext::SessionId() != nullptr); + assert(TraceContext::RequestId() != nullptr); + + TraceContext::Initialize("3C:DC:75:FB:12:FC"); + + // Colons are folded so ids stay safe inside "field=value" log grammar. + TraceContext::RefreshTrace("ws"); + assert(std::strstr(TraceContext::TraceId(), "3C-DC-75-FB-12-FC") != + nullptr); + assert(std::strchr(TraceContext::TraceId(), ':') == nullptr); + assert(std::strncmp(TraceContext::TraceId(), "ws-", 3) == 0); + + // The server owns the session scope; the device adopts it verbatim. + TraceContext::SetSession("srv-session-42"); + assert(std::strcmp( + TraceContext::SessionId(), "srv-session-42") == 0); + TraceContext::SetSession(""); + assert(std::strcmp(TraceContext::SessionId(), "-") == 0); + TraceContext::SetSession(nullptr); + assert(std::strcmp(TraceContext::SessionId(), "-") == 0); + + // ...but the device proposes one per connect, so the handshake never sends + // the unset "-" (which the server would adopt verbatim) nor the previous + // connection's id. + const char* proposed = TraceContext::RefreshSession(); + assert(std::strncmp(proposed, "s-", 2) == 0); + assert(std::strcmp(proposed, "-") != 0); + assert(std::strcmp(proposed, TraceContext::SessionId()) == 0); + assert(std::strstr(proposed, "3C-DC-75-FB-12-FC") != nullptr); + // A server-supplied id still wins over the proposal. + TraceContext::SetSession("srv-session-7"); + assert(std::strcmp( + TraceContext::SessionId(), "srv-session-7") == 0); + + // Each HTTP call gets a fresh request id, returned for the header. + const char* first = TraceContext::NewRequestId(); + assert(std::strncmp(first, "req-", 4) == 0); + assert(std::strcmp(first, TraceContext::RequestId()) == 0); + + // A trace id pushed down from the server replaces the generated one. + TraceContext::SetTrace("srv-trace-7"); + assert(std::strcmp(TraceContext::TraceId(), "srv-trace-7") == 0); +} + +} // namespace + +int main() +{ + TestFormatIdShape(); + TestFormatIdDefaultsAndTruncation(); + TestScopeLifecycle(); + std::cout << "trace context tests passed" << std::endl; + return 0; +} diff --git a/host_tests/voice_activity_detector_test.cc b/host_tests/voice_activity_detector_test.cc new file mode 100644 index 0000000..9283beb --- /dev/null +++ b/host_tests/voice_activity_detector_test.cc @@ -0,0 +1,54 @@ +#include "audio/voice_activity_detector.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +void TestHysteresis() +{ + VoiceActivityDetector detector( + VoiceActivityConfig{500, 2, 3}); + std::array loud{}; + std::array quiet{}; + loud.fill(1000); + + assert(detector.Process(loud.data(), loud.size()) == + VoiceActivityResult::kSilence); + assert(detector.Process(loud.data(), loud.size()) == + VoiceActivityResult::kSpeechStarted); + assert(detector.speech_active()); + assert(detector.Process(quiet.data(), quiet.size()) == + VoiceActivityResult::kSpeech); + assert(detector.Process(quiet.data(), quiet.size()) == + VoiceActivityResult::kSpeech); + assert(detector.Process(quiet.data(), quiet.size()) == + VoiceActivityResult::kSpeechEnded); + assert(!detector.speech_active()); +} + +void TestNoiseDoesNotStartSpeech() +{ + VoiceActivityDetector detector( + VoiceActivityConfig{500, 2, 3}); + std::array noise{}; + noise.fill(300); + for (int index = 0; index < 20; ++index) { + assert(detector.Process(noise.data(), noise.size()) == + VoiceActivityResult::kSilence); + } + assert(detector.LastRms() == 300); +} + +} // namespace + +int main() +{ + TestHysteresis(); + TestNoiseDoesNotStartSpeech(); + std::cout << "voice activity detector tests passed\n"; + return 0; +} diff --git a/host_tests/websocket_uri_test.cc b/host_tests/websocket_uri_test.cc new file mode 100644 index 0000000..6e5f47c --- /dev/null +++ b/host_tests/websocket_uri_test.cc @@ -0,0 +1,61 @@ +#include "protocol/websocket_uri.h" + +#include +#include +#include + +namespace { + +using namespace borla; + +void TestDefaultsAndExplicitPort() +{ + WebsocketUri uri; + assert(ParseWebsocketUri("wss://example.com/v1/ws", &uri)); + assert(uri.secure); + assert(uri.port == 443); + assert(std::strcmp(uri.host.data(), "example.com") == 0); + assert(std::strcmp(uri.path.data(), "/v1/ws") == 0); + + assert(ParseWebsocketUri("ws://10.0.0.2:8000", &uri)); + assert(!uri.secure); + assert(uri.port == 8000); + assert(std::strcmp(uri.host.data(), "10.0.0.2") == 0); + assert(std::strcmp(uri.path.data(), "/") == 0); +} + +void TestIpv6() +{ + WebsocketUri uri; + assert(ParseWebsocketUri( + "wss://[2001:db8::1]:9443/socket", &uri)); + assert(uri.secure); + assert(uri.port == 9443); + assert(std::strcmp(uri.host.data(), "2001:db8::1") == 0); + assert(std::strcmp(uri.path.data(), "/socket") == 0); +} + +void TestRejectsMalformedUris() +{ + WebsocketUri uri; + assert(!ParseWebsocketUri(nullptr, &uri)); + assert(!ParseWebsocketUri("", &uri)); + assert(!ParseWebsocketUri("http://example.com", &uri)); + assert(!ParseWebsocketUri("wss://", &uri)); + assert(!ParseWebsocketUri("wss://host:0/ws", &uri)); + assert(!ParseWebsocketUri("wss://host:65536/ws", &uri)); + assert(!ParseWebsocketUri("wss://host:abc/ws", &uri)); + assert(!ParseWebsocketUri("wss://[2001:db8::1/ws", &uri)); + assert(!ParseWebsocketUri("wss://a:b:c/ws", &uri)); +} + +} // namespace + +int main() +{ + TestDefaultsAndExplicitPort(); + TestIpv6(); + TestRejectsMalformedUris(); + std::cout << "websocket URI tests passed\n"; + return 0; +} diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt new file mode 100644 index 0000000..e31bb9f --- /dev/null +++ b/main/CMakeLists.txt @@ -0,0 +1,183 @@ +set(SRCS + "main.cc" + "activation/activation_replay_service.cc" + "app/application.cc" + "app/composition_root.cc" + "audio/capture_pipeline.cc" + "audio/embedded_prompt_catalog.cc" + "audio/local_prompt_player.cc" + "audio/packed_opus_reader.cc" + "audio/playback_controller.cc" + "audio/playback_pipeline.cc" + "audio/opus_frame_decoder.cc" + "audio/opus_frame_encoder.cc" + "audio/pcm_rate_converter.cc" + "audio/voice_activity_detector.cc" + "audio/voice_dsp.cc" + "audio/voice_frontend.cc" + "audio/wake_word_detector.cc" + "connectivity/connectivity_manager.cc" + "connectivity/connectivity_policy.cc" + "connectivity/dual_network_policy.cc" + "connectivity/dual_network_transport.cc" + "connectivity/ml307_at_parser.cc" + "connectivity/reconnect_backoff.cc" + "connectivity/wifi_credential_store.cc" + "configuration/remote_behavior_config.cc" + "diagnostics/audio_tap.cc" + "diagnostics/runtime_diagnostics_service.cc" + "diagnostics/device_log_formatter.cc" + "diagnostics/trace_context.cc" + "core/app_effect.cc" + "core/app_event.cc" + "core/playback_types.cc" + "core/remote_behavior.cc" + "core/runtime_state.cc" + "core/state_reducer.cc" + "friend/friend_service.cc" + "friend/friend_store.cc" + "friend/friend_types.cc" + "memory/memory_cache.cc" + "memory/memory_types.cc" + "adapters/effect_router.cc" + "adapters/esp_audio_engine.cc" + "platform/borla_s3/borla_s3_platform.cc" + "platform/borla_s3/battery_monitor.cc" + "platform/borla_s3/ble_friend_exchange.cc" + "platform/borla_s3/ble_provisioning_gatt.cc" + "platform/borla_s3/bmi270_sensor.cc" + "platform/borla_s3/button_input.cc" + "platform/borla_s3/capacitive_touch_input.cc" + "platform/borla_s3/es8311_audio_output.cc" + "platform/borla_s3/esp_websocket_transport.cc" + "platform/borla_s3/esp_wifi_transport.cc" + "platform/borla_s3/i2c_bus.cc" + "platform/borla_s3/ml307_transport.cc" + "platform/borla_s3/ws2812_led.cc" + "ota/ota_endpoint.cc" + "ota/ota_response_parser.cc" + "ota/ota_service.cc" + "ota/ota_types.cc" + "protocol/binary_audio_protocol.cc" + "protocol/protocol_message_builder.cc" + "protocol/realtime_config.cc" + "protocol/realtime_protocol.cc" + "protocol/server_message_dispatcher.cc" + "protocol/websocket_uri.cc" + "provisioning/ble_provisioning_codec.cc" + "provisioning/ble_provisioning_service.cc" + "power/idle_service.cc" + "power/power_service.cc" + "schedule/alarm_schedule.cc" + "schedule/alarm_service.cc" + "schedule/alarm_store.cc" + "schedule/alert_ringer.cc" + "schedule/reminder_schedule.cc" + "schedule/reminder_service.cc" + "schedule/schedule_coordinator.cc" + "sensor/battery_estimator.cc" + "sensor/imu_processor.cc" + "sensor/sensor_message_codec.cc" + "sensor/sensor_service.cc" + "sensor/sensor_types.cc" + "sensor/touch_channel.cc" + "platform/borla_s3/tca9555.cc" +) + +idf_component_register( + SRCS ${SRCS} + INCLUDE_DIRS "." + REQUIRES + button + bt + driver + app_update + esp-opus + espressif__esp-dsp + esp_adc + esp_app_format + esp_codec_dev + esp_driver_gpio + esp_driver_i2c + esp_driver_i2s + esp_event + esp_http_client + esp_hw_support + esp_netif + esp_system + esp_timer + esp_wifi + esp-sr + freertos + json + led_strip + mbedtls + nvs_flash + tcp_transport +) + +# Reuse Espressif's Apache-2.0 BMI270 context image from the explicitly +# versioned esp-dsp component. Only the immutable sensor configuration blob is +# compiled here; firmware2 has its own I2C driver and does not link old code. +idf_component_get_property( + ESP_DSP_COMPONENT_DIR espressif__esp-dsp COMPONENT_DIR) +target_sources( + ${COMPONENT_LIB} + PRIVATE + "${ESP_DSP_COMPONENT_DIR}/applications/m5stack_core_s3/apps/kalman_filter/main/bmi270_context.c" +) + +if(NOT CMAKE_BUILD_EARLY_EXPANSION) + idf_build_get_property(python PYTHON) + set(PROMPT_GENERATOR + "${CMAKE_CURRENT_LIST_DIR}/../assets/gen_audio_prompts.py") + set(PROMPT_ASSET_DIR + "${CMAKE_CURRENT_LIST_DIR}/../assets/prompts") + file( + GLOB PROMPT_ASSETS + "${PROMPT_ASSET_DIR}/*.ogg" + "${PROMPT_ASSET_DIR}/*.opus" + ) + set(GENERATED_PROMPT_DIR + "${CMAKE_CURRENT_BINARY_DIR}/generated") + set(GENERATED_PROMPT_HEADER + "${GENERATED_PROMPT_DIR}/audio_prompts_data.h") + + add_custom_command( + OUTPUT "${GENERATED_PROMPT_HEADER}" + COMMAND + "${python}" "${PROMPT_GENERATOR}" + "${PROMPT_ASSET_DIR}" "${GENERATED_PROMPT_HEADER}" + DEPENDS + "${PROMPT_GENERATOR}" + ${PROMPT_ASSETS} + COMMENT "Validating and packing local Ogg/Opus prompts" + VERBATIM + ) + add_custom_target( + firmware2_prompt_data + DEPENDS "${GENERATED_PROMPT_HEADER}" + ) + add_dependencies(${COMPONENT_LIB} firmware2_prompt_data) + target_include_directories( + ${COMPONENT_LIB} + PRIVATE "${GENERATED_PROMPT_DIR}" + ) +endif() + +# ESP-IDF 5.4 defaults chip targets to its newest supported C++ dialect. +# Keep firmware2 on the project-wide C++17 contract explicitly. +target_compile_options( + ${COMPONENT_LIB} + PRIVATE + $<$:-std=gnu++17> +) + +# ServerCommand intentionally lives in PSRAM and is currently several KB. +# Keep every production parser frame small so a future field cannot silently +# recreate a task-stack copy of the whole command. +set_source_files_properties( + "protocol/server_message_dispatcher.cc" + PROPERTIES + COMPILE_OPTIONS "-Wframe-larger-than=1024;-Werror" +) diff --git a/main/Kconfig.projbuild b/main/Kconfig.projbuild new file mode 100644 index 0000000..f80b3ef --- /dev/null +++ b/main/Kconfig.projbuild @@ -0,0 +1,38 @@ +menu "Borla firmware2" + +config BORLA_OTA_URL + string "OTA version-check URL" + default "https://borla-ota.lkall.com/xiaozhi/ota/" + help + HTTPS endpoint implementing protocols/ota_protocol.md. + +config BORLA_OTA_ALLOW_INSECURE_HTTP + bool "Allow insecure HTTP for OTA development" + default n + help + Development-only escape hatch for isolated LAN testing. Production + builds must keep this disabled so manifests and binaries require HTTPS. + +config BORLA_ML307_APN + string "ML307 cellular APN" + default "" + help + SIM operator APN. Empty lets the operator/modem select its default. + +config BORLA_ML307_DIAL_COMMAND + string "ML307 PPP dial command" + default "ATD*99#" + help + Command used after LTE registration to enter PPP data mode. + +config BORLA_AUDIO_TAP + bool "Debug audio tap (stream mic + speaker PCM over TCP)" + default n + help + Streams everything the microphone captured and everything the DAC + played (24 kHz mono s16, boot to shutdown) over an unauthenticated + TCP socket on port 3401, so tools/audio_tap_dump.py on the same LAN + can write the pair of timestamped WAV files. This is an open + microphone: debugging builds only, never ship with it enabled. + +endmenu diff --git a/main/activation/activation_replay_service.cc b/main/activation/activation_replay_service.cc new file mode 100644 index 0000000..9abddee --- /dev/null +++ b/main/activation/activation_replay_service.cc @@ -0,0 +1,241 @@ +#include "activation/activation_replay_service.h" + +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "ActivationReplay2"; + +} // namespace + +bool ActivationReplayService::Initialize(IEventPublisher& publisher) +{ + if (timer_ != nullptr) { + publisher_ = &publisher; + return true; + } + const esp_timer_create_args_t arguments = { + .callback = &ActivationReplayService::TimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "activation2", + .skip_unhandled_events = true, + }; + if (esp_timer_create(&arguments, &timer_) != ESP_OK) { + return false; + } + publisher_ = &publisher; + return true; +} + +bool ActivationReplayService::StartLocalSequence( + const LocalPromptSequence& sequence) +{ + if (publisher_ == nullptr || sequence.Empty() || + sequence.count > kMaxLocalPromptSequenceItems) { + return false; + } + uint32_t generation = 0; + PlaybackSessionId previous_session = 0; + bool repeating = false; + { + std::lock_guard lock(mutex_); + esp_timer_stop(timer_); + previous_session = current_session_; + sequence_ = sequence; + current_session_ = 0; + repeating_ = + sequence.Contains(LocalPrompt::kActivationDevice); + repeating = repeating_; + active_ = true; + if (++generation_ == 0) { + ++generation_; + } + generation = generation_; + } + if (previous_session != 0) { + audio_.CancelPlayback(previous_session); + } + if (!publisher_->Publish(AppEvent::Make( + AppEventType::kLocalSequenceRequested, + generation))) { + StopLocalSequence(); + return false; + } + ESP_LOGI(kTag, "sequence queued items=%u repeat=%d generation=%lu", + static_cast(sequence.count), + repeating ? 1 : 0, + static_cast(generation)); + return true; +} + +void ActivationReplayService::StopLocalSequence() +{ + StopWithReason("handler request"); +} + +void ActivationReplayService::StopWithReason(const char* reason) +{ + PlaybackSessionId session = 0; + bool was_active = false; + { + std::lock_guard lock(mutex_); + was_active = active_; + StopLocked(&session); + } + if (session != 0) { + audio_.CancelPlayback(session); + } + if (was_active) { + ESP_LOGI(kTag, "replay stopped (%s)", reason); + } +} + +void ActivationReplayService::OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) +{ + if (event.type == AppEventType::kLocalSequenceRequested || + event.type == AppEventType::kActivationReplayDue) { + PlayCurrent(state, event.correlation_id); + return; + } + + PlaybackSessionId current_session = 0; + bool active = false; + { + std::lock_guard lock(mutex_); + current_session = current_session_; + active = active_; + } + if (!active) { + return; + } + + if (event.type == AppEventType::kPlaybackDrained && + event.correlation_id == current_session) { + std::lock_guard lock(mutex_); + current_session_ = 0; + if (active_ && repeating_ && CanPlay(state)) { + esp_timer_stop(timer_); + if (esp_timer_start_once(timer_, kReplayDelayUs) == ESP_OK) { + ESP_LOGI(kTag, "next activation replay in 6000 ms"); + return; + } + } + active_ = false; + repeating_ = false; + sequence_ = {}; + return; + } + + if ((event.type == AppEventType::kPlaybackFailed && + (event.correlation_id == 0 || + event.correlation_id == current_session)) || + (event.type == AppEventType::kPlaybackPreempted && + event.correlation_id == current_session) || + event.type == AppEventType::kTtsStarted || + event.type == AppEventType::kLocalPromptRequested || + event.type == AppEventType::kShutdownPromptRequested) { + StopWithReason(ToString(event.type)); + } else if (!CanPlay(state)) { + StopWithReason("state no longer allows playback"); + } +} + +void ActivationReplayService::TimerCallback(void* context) +{ + static_cast(context)->OnTimer(); +} + +void ActivationReplayService::OnTimer() +{ + IEventPublisher* publisher = nullptr; + uint32_t generation = 0; + { + std::lock_guard lock(mutex_); + if (!active_ || !repeating_) { + return; + } + publisher = publisher_; + generation = generation_; + } + if (publisher != nullptr) { + publisher->Publish(AppEvent::Make( + AppEventType::kActivationReplayDue, + generation)); + } +} + +void ActivationReplayService::PlayCurrent( + const RuntimeState& state, + uint32_t generation) +{ + LocalPromptSequence sequence; + bool should_stop = false; + { + std::lock_guard lock(mutex_); + if (!active_ || generation != generation_) { + return; + } + if (!CanPlay(state)) { + should_stop = true; + } else { + sequence = sequence_; + } + } + if (should_stop) { + StopLocalSequence(); + return; + } + ESP_LOGI(kTag, "replay cycle items=%u generation=%lu", + static_cast(sequence.count), + static_cast(generation)); + const PlaybackSessionId session = audio_.PlayLocalSequence( + sequence, PlaybackPriority::kLocalPrompt); + bool cancel_stale_session = false; + { + std::lock_guard lock(mutex_); + if (!active_ || generation != generation_) { + cancel_stale_session = session != 0; + } else { + current_session_ = session; + if (session == 0) { + active_ = false; + repeating_ = false; + sequence_ = {}; + } + } + } + if (cancel_stale_session) { + audio_.CancelPlayback(session); + } +} + +bool ActivationReplayService::CanPlay( + const RuntimeState& state) const +{ + return state.lifecycle == LifecycleState::kRunning && + state.realtime == RealtimeState::kOpen && + state.call == CallState::kInactive && + !state.friend_mode && + !state.alert_ringing && + !state.idle_sleeping; +} + +void ActivationReplayService::StopLocked( + PlaybackSessionId* session_to_cancel) +{ + esp_timer_stop(timer_); + *session_to_cancel = current_session_; + current_session_ = 0; + active_ = false; + repeating_ = false; + sequence_ = {}; + if (++generation_ == 0) { + ++generation_; + } +} + +} // namespace borla diff --git a/main/activation/activation_replay_service.h b/main/activation/activation_replay_service.h new file mode 100644 index 0000000..8764b34 --- /dev/null +++ b/main/activation/activation_replay_service.h @@ -0,0 +1,60 @@ +#pragma once + +#include "ports/application_observer.h" +#include "ports/audio_engine.h" +#include "ports/event_publisher.h" +#include "ports/local_sequence_handler.h" + +#include +#include + +#include + +namespace borla { + +class ActivationReplayService final + : public ILocalSequenceHandler, + public IApplicationObserver { +public: + explicit ActivationReplayService(IAudioEngine& audio) + : audio_(audio) + { + } + + bool Initialize(IEventPublisher& publisher); + bool StartLocalSequence( + const LocalPromptSequence& sequence) override; + void StopLocalSequence() override; + void OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) override; + +private: + static constexpr uint64_t kReplayDelayUs = + 6000ULL * 1000ULL; + + static void TimerCallback(void* context); + void OnTimer(); + void PlayCurrent(const RuntimeState& state, uint32_t generation); + bool CanPlay(const RuntimeState& state) const; + void StopLocked(PlaybackSessionId* session_to_cancel); + // The previous firmware logged every stop with its trigger + // (StopActivationReplay(reason)). Without it a device stuck reading + // the activation code cannot be told apart from one that simply never + // received the server's stop signal, which is the only thing that ends + // this loop — there is no device-side activation check in either + // firmware. + void StopWithReason(const char* reason); + + IAudioEngine& audio_; + IEventPublisher* publisher_ = nullptr; + esp_timer_handle_t timer_ = nullptr; + mutable std::mutex mutex_; + LocalPromptSequence sequence_{}; + PlaybackSessionId current_session_ = 0; + uint32_t generation_ = 0; + bool active_ = false; + bool repeating_ = false; +}; + +} // namespace borla diff --git a/main/adapters/effect_router.cc b/main/adapters/effect_router.cc new file mode 100644 index 0000000..237c95a --- /dev/null +++ b/main/adapters/effect_router.cc @@ -0,0 +1,164 @@ +#include "adapters/effect_router.h" + +namespace borla { + +EffectRouter::EffectRouter( + IAudioEngine& audio, + IConnectivityManager& connectivity, + IRealtimeProtocol& realtime, + IDevicePlatform& platform, + IFriendService& friend_service, + IProvisioningService& provisioning, + IOtaService& ota, + IAlertRinger& alert_ringer, + IPowerService& power) + : audio_(audio), + connectivity_(connectivity), + realtime_(realtime), + platform_(platform), + friend_service_(friend_service), + provisioning_(provisioning), + ota_(ota), + alert_ringer_(alert_ringer), + power_(power) +{ +} + +void EffectRouter::Handle(const AppEffect& effect, const RuntimeState&) +{ + switch (effect.type) { + case AppEffectType::kStartAudio: + audio_.Start(); + return; + case AppEffectType::kStopAudio: + audio_.Stop(); + return; + case AppEffectType::kStartConnectivity: + connectivity_.Start(); + return; + case AppEffectType::kStopConnectivity: + connectivity_.Stop(); + return; + case AppEffectType::kSwitchNetwork: + connectivity_.SwitchNetwork(); + return; + case AppEffectType::kOpenRealtime: + realtime_.Open(); + return; + case AppEffectType::kCloseRealtime: + realtime_.Close(); + return; + case AppEffectType::kSendStartListening: + realtime_.SendStartListening(); + return; + case AppEffectType::kSendStopListening: + realtime_.SendStopListening(); + return; + case AppEffectType::kSendAbortSpeaking: + realtime_.SendAbortSpeaking(effect.interrupt_source); + return; + case AppEffectType::kSendGoodbye: + realtime_.SendGoodbye(); + return; + case AppEffectType::kSendAcceptCall: + realtime_.SendAcceptCall(); + return; + case AppEffectType::kSendHangupCall: + realtime_.SendHangupCall(); + return; + case AppEffectType::kSendButtonClick: + realtime_.SendButtonClick( + static_cast(effect.correlation_id)); + return; + case AppEffectType::kSendLocalPlaybackStarted: + realtime_.SendLocalPlaybackState( + effect.local_prompt, true); + return; + case AppEffectType::kSendLocalPlaybackDone: + realtime_.SendLocalPlaybackState( + effect.local_prompt, false); + return; + case AppEffectType::kBeginRemotePlayback: + audio_.BeginRemotePlayback( + effect.correlation_id, effect.playback_priority); + return; + case AppEffectType::kEndPlaybackInput: + audio_.EndPlaybackInput(effect.correlation_id); + return; + case AppEffectType::kPlayLocalPrompt: + audio_.PlayLocalPrompt( + effect.local_prompt, + effect.playback_priority, + effect.prompt_selector); + return; + case AppEffectType::kPlayDetachedPrompt: + audio_.PlayDetachedPrompt( + effect.local_prompt, effect.playback_priority); + return; + case AppEffectType::kApplyAudioPolicy: + audio_.ApplyPolicy(effect.audio_policy); + return; + case AppEffectType::kSetAudioVolume: + audio_.SetVolume( + static_cast(effect.correlation_id)); + return; + case AppEffectType::kSetWakeWordEnabled: + audio_.SetWakeWordEnabled(effect.correlation_id != 0); + return; + case AppEffectType::kSetBargeInEnabled: + audio_.SetBargeInEnabled(effect.correlation_id != 0); + return; + case AppEffectType::kPausePlayback: + audio_.SetPlaybackPaused(true); + return; + case AppEffectType::kResumePlayback: + audio_.SetPlaybackPaused(false); + return; + case AppEffectType::kCancelPlayback: + audio_.CancelPlayback(effect.correlation_id); + return; + case AppEffectType::kSetLed: + platform_.SetLed(effect.led_pattern); + return; + case AppEffectType::kShowTemporaryLedAlert: + platform_.ShowTemporaryLedAlert(effect.correlation_id); + return; + case AppEffectType::kStartFriendMode: + friend_service_.Start(); + return; + case AppEffectType::kStopFriendMode: + friend_service_.Stop(); + return; + case AppEffectType::kEnterProvisioning: + // Free the WakeNet instance before NimBLE starts. The wake word is + // unused in provisioning and the device reboots out of it, while the + // BT controller needs ~53 KB of internal RAM. The previous firmware + // did the same thing (wifi_board.cc EnterBleConfigMode). + audio_.ReleaseWakeWord(); + provisioning_.Start(); + return; + case AppEffectType::kStartUpgrade: + ota_.StartUpgrade(effect.correlation_id); + return; + case AppEffectType::kReboot: + platform_.Reboot(); + return; + case AppEffectType::kEnterSoftOff: + power_.EnterSoftOff(); + return; + case AppEffectType::kStartAlert: + alert_ringer_.Start(effect.alert_kind); + return; + case AppEffectType::kStopAlert: + alert_ringer_.Stop(); + return; + case AppEffectType::kRequestConnectionErrorPrompt: + realtime_.RequestConnectionErrorPrompt(); + return; + case AppEffectType::kReportError: + platform_.ReportError(effect.correlation_id); + return; + } +} + +} // namespace borla diff --git a/main/adapters/effect_router.h b/main/adapters/effect_router.h new file mode 100644 index 0000000..1d7686c --- /dev/null +++ b/main/adapters/effect_router.h @@ -0,0 +1,47 @@ +#pragma once + +#include "ports/audio_engine.h" +#include "ports/alert_ringer.h" +#include "ports/connectivity_manager.h" +#include "ports/device_platform.h" +#include "ports/effect_sink.h" +#include "ports/friend_service.h" +#include "ports/ota_service.h" +#include "ports/provisioning_service.h" +#include "ports/power_service.h" +#include "ports/realtime_protocol.h" + +namespace borla { + +// Composition boundary between the pure state machine and concrete drivers. +// It intentionally contains no product decisions: every operation here must +// be the direct execution of an AppEffect already decided by ReduceState. +class EffectRouter final : public IEffectSink { +public: + EffectRouter( + IAudioEngine& audio, + IConnectivityManager& connectivity, + IRealtimeProtocol& realtime, + IDevicePlatform& platform, + IFriendService& friend_service, + IProvisioningService& provisioning, + IOtaService& ota, + IAlertRinger& alert_ringer, + IPowerService& power); + + void Handle(const AppEffect& effect, + const RuntimeState& resulting_state) override; + +private: + IAudioEngine& audio_; + IConnectivityManager& connectivity_; + IRealtimeProtocol& realtime_; + IDevicePlatform& platform_; + IFriendService& friend_service_; + IProvisioningService& provisioning_; + IOtaService& ota_; + IAlertRinger& alert_ringer_; + IPowerService& power_; +}; + +} // namespace borla diff --git a/main/adapters/esp_audio_engine.cc b/main/adapters/esp_audio_engine.cc new file mode 100644 index 0000000..b854291 --- /dev/null +++ b/main/adapters/esp_audio_engine.cc @@ -0,0 +1,492 @@ +#include "adapters/esp_audio_engine.h" + +#include + +#include + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "EspAudioEngine2"; +constexpr uint32_t kAudioOutputInitializationError = 2001; +constexpr uint32_t kPlaybackPipelineInitializationError = 2002; +constexpr uint32_t kPrerollAllocationError = 2003; + +} // namespace + +EspAudioEngine::EspAudioEngine( + IAudioOutput& output, + IAudioInput& input) + : output_(output), + input_(input), + playback_(output), + prompts_(playback_), + capture_(input) +{ + capture_.SetProcessor(&voice_frontend_); + playback_.SetReferenceSink(&voice_frontend_); +} + +void EspAudioEngine::SetUplinkSink(IEncodedAudioSink* sink) +{ + capture_.SetSink(sink); +} + +EspAudioEngine::~EspAudioEngine() +{ + Stop(); + if (preroll_ != nullptr) { + preroll_->~DownlinkPrerollBuffer(); + heap_caps_free(preroll_); + preroll_ = nullptr; + } +} + +void EspAudioEngine::SetEventPublisher(IEventPublisher* publisher) +{ + publisher_ = publisher; + playback_.SetEventPublisher(publisher); + voice_frontend_.SetEventPublisher(publisher); +} + +bool EspAudioEngine::Start() +{ + if (started_) { + return true; + } + if (preroll_ == nullptr) { + void* storage = heap_caps_malloc( + sizeof(DownlinkPrerollBuffer), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (storage == nullptr) { + PublishFatalError(kPrerollAllocationError); + return false; + } + preroll_ = new (storage) DownlinkPrerollBuffer(); + } + if (!output_.Initialize()) { + PublishFatalError(kAudioOutputInitializationError); + return false; + } + if (!playback_.Initialize() || !prompts_.Initialize() || + !voice_frontend_.Initialize() || + !capture_.Initialize() || !playback_.Start() || + !capture_.Start()) { + capture_.Stop(); + playback_.Stop(); + output_.Shutdown(); + PublishFatalError(kPlaybackPipelineInitializationError); + return false; + } + + started_ = true; + ESP_LOGI(kTag, "audio output and playback pipeline started"); + return true; +} + +void EspAudioEngine::Stop() +{ + if (!started_) { + return; + } + capture_.Stop(); + { + std::lock_guard lock(downlink_mutex_); + ClearPrerollLocked(); + playback_.Stop(); + } + output_.Shutdown(); + started_ = false; +} + +void EspAudioEngine::ApplyPolicy(AudioPolicy policy) +{ + requested_policy_.store(policy); + RefreshEffectivePolicy(); +} + +void EspAudioEngine::SetVolume(uint8_t volume_percent) +{ + output_.SetVolume(volume_percent); +} + +void EspAudioEngine::SetWakeWordEnabled(bool enabled) +{ + wake_word_enabled_.store(enabled); + RefreshEffectivePolicy(); +} + +void EspAudioEngine::SetBargeInEnabled(bool enabled) +{ + barge_in_enabled_.store(enabled); + RefreshEffectivePolicy(); +} + +void EspAudioEngine::SetPlaybackPaused(bool paused) +{ + playback_.SetPaused(paused); +} + +void EspAudioEngine::RefreshEffectivePolicy() +{ + const AudioPolicy requested = requested_policy_.load(); + const bool wake_word = wake_word_enabled_.load(); + const bool barge_in = barge_in_enabled_.load(); + AudioPolicy effective = requested; + if (requested == AudioPolicy::kWakeWordOnly && !wake_word) { + effective = AudioPolicy::kOff; + } else if ( + requested == AudioPolicy::kBargeInDuplex && !barge_in) { + effective = wake_word + ? AudioPolicy::kWakeWordDuplex + : AudioPolicy::kPlaybackOnly; + } + voice_frontend_.SetWakeWordEnabled(wake_word); + capture_.ApplyPolicy(effective); + ESP_LOGI( + kTag, + "audio policy requested=%s effective=%s wake=%d barge=%d", + ToString(requested), + ToString(effective), + wake_word ? 1 : 0, + barge_in ? 1 : 0); +} + +void EspAudioEngine::OnRealtimeBinary( + const uint8_t* data, + size_t size, + uint32_t playback_session_id) +{ + if (!SubmitOpusFrame(playback_session_id, data, size)) { + ESP_LOGW(kTag, + "downlink Opus dropped session=%lu size=%u", + static_cast(playback_session_id), + static_cast(size)); + } +} + +void EspAudioEngine::CancelPlayback(PlaybackSessionId session_id) +{ + std::lock_guard lock(downlink_mutex_); + ClearPrerollLocked(); + playback_.Cancel(session_id); +} + +void EspAudioEngine::BeginRemotePlayback( + PlaybackSessionId session_id, + PlaybackPriority priority) +{ + std::lock_guard lock(downlink_mutex_); + const PlaybackSource source = + priority == PlaybackPriority::kCall + ? PlaybackSource::kCall + : PlaybackSource::kRemoteTts; + const PlaybackStartResult result = playback_.StartSession( + source, priority, session_id); + if (result.status != PlaybackStartStatus::kStarted && + result.status != PlaybackStartStatus::kAlreadyActive) { + if (preroll_ != nullptr && + preroll_->session_id() == session_id) { + ClearPrerollLocked(); + } + ESP_LOGW(kTag, + "remote playback rejected status=%s session=%lu priority=%s", + ToString(result.status), + static_cast(session_id), + ToString(priority)); + return; + } + FlushPrerollLocked(session_id); +} + +void EspAudioEngine::EndPlaybackInput(PlaybackSessionId session_id) +{ + std::lock_guard lock(downlink_mutex_); + if (!playback_.EndInput(session_id)) { + if (preroll_ != nullptr && + preroll_->session_id() == session_id) { + ClearPrerollLocked(); + } + ESP_LOGW(kTag, "ignored end input for stale session=%lu", + static_cast(session_id)); + } +} + +bool EspAudioEngine::SubmitOpusFrame( + PlaybackSessionId session_id, + const uint8_t* data, + size_t size) +{ + std::lock_guard lock(downlink_mutex_); + if (playback_.SubmitOpus(session_id, data, size)) { + return true; + } + + const PlaybackSessionSnapshot snapshot = playback_.Snapshot(); + if ((snapshot.active && snapshot.id == session_id) || + preroll_ == nullptr) { + return false; + } + return preroll_->Push(session_id, data, size); +} + +void EspAudioEngine::ClearPrerollLocked() +{ + if (preroll_ != nullptr) { + preroll_->Reset(); + } +} + +void EspAudioEngine::FlushPrerollLocked(PlaybackSessionId session_id) +{ + if (preroll_ == nullptr || + preroll_->session_id() != session_id) { + return; + } + const size_t frame_count = preroll_->frame_count(); + size_t submitted = 0; + for (; submitted < frame_count; ++submitted) { + if (!playback_.SubmitOpus( + session_id, + preroll_->FrameData(submitted), + preroll_->FrameSize(submitted))) { + break; + } + } + preroll_->Reset(); + if (submitted != frame_count) { + ESP_LOGW( + kTag, + "downlink pre-roll flush incomplete session=%lu submitted=%u total=%u", + static_cast(session_id), + static_cast(submitted), + static_cast(frame_count)); + } else if (frame_count != 0) { + ESP_LOGD( + kTag, + "downlink pre-roll flushed session=%lu frames=%u", + static_cast(session_id), + static_cast(frame_count)); + } +} + +PlaybackSessionId EspAudioEngine::PlayLocalPrompt( + LocalPrompt prompt, + PlaybackPriority priority, + int16_t selector) +{ + const PlaybackSessionId session_id = + prompts_.Play(prompt, priority, selector); + if (session_id == 0 && publisher_ != nullptr) { + publisher_->Publish( + AppEvent::Make(AppEventType::kPlaybackFailed)); + } else if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kLocalPromptStarted, + session_id, + static_cast(prompt), + static_cast(priority))); + } + return session_id; +} + +PlaybackSessionId EspAudioEngine::PlayDetachedPrompt( + LocalPrompt prompt, + PlaybackPriority priority) +{ + // Deliberately silent on the control plane: no kLocalPromptStarted, no + // kPlaybackFailed. The caller's conversation state must survive this + // prompt unchanged. + const PlaybackSessionId session_id = + prompts_.Play(prompt, priority, -1); + if (session_id == 0) { + ESP_LOGW(kTag, "detached prompt rejected prompt=%s", + ToString(prompt)); + } + return session_id; +} + +uint8_t EspAudioEngine::OutputVolumePercent() const +{ + return output_.VolumePercent(); +} + +PlaybackSessionId EspAudioEngine::PlayLocalSequence( + const LocalPromptSequence& sequence, + PlaybackPriority priority) +{ + const PlaybackSessionId session_id = + prompts_.PlaySequence(sequence, priority); + if (session_id == 0 && publisher_ != nullptr) { + publisher_->Publish( + AppEvent::Make(AppEventType::kPlaybackFailed)); + } else if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kLocalSequenceStarted, + session_id, + static_cast(sequence.count), + static_cast(priority))); + } + return session_id; +} + +PlaybackSessionSnapshot EspAudioEngine::PlaybackSnapshot() const +{ + return playback_.Snapshot(); +} + +PlaybackMetrics EspAudioEngine::PlaybackMetricsSnapshot() const +{ + return playback_.Metrics(); +} + +CaptureMetrics EspAudioEngine::CaptureMetricsSnapshot() const +{ + return capture_.Metrics(); +} + +VoiceFrontendMetrics EspAudioEngine::VoiceMetricsSnapshot() const +{ + return voice_frontend_.Metrics(); +} + +void EspAudioEngine::ReleaseWakeWord() +{ + voice_frontend_.ReleaseWakeWord(); +} + +bool EspAudioEngine::WaitForPlaybackIdle(uint32_t timeout_ms) +{ + constexpr uint32_t kPollIntervalMs = 20; + uint32_t waited_ms = 0; + while (playback_.Active()) { + if (waited_ms >= timeout_ms) { + ESP_LOGW(kTag, "playback still active after %lums", + static_cast(timeout_ms)); + return false; + } + vTaskDelay(pdMS_TO_TICKS(kPollIntervalMs)); + waited_ms += kPollIntervalMs; + } + return true; +} + +void EspAudioEngine::LogAudioMetrics(const char* reason) +{ + voice_frontend_.LogMetrics(reason); + // The capture counters answer the question the voice counters raise: when + // the reference ring keeps overrunning, it is because this task is not + // consuming one frame per 60 ms. read_failures and encode_failures say + // whether frames are being lost at the I2S read or in the DSP/encoder. + const CaptureMetrics capture = capture_.Metrics(); + ESP_LOGI(kTag, + "capture metrics (%s) read=%lu encoded=%lu sent=%lu " + "read_fail=%lu encode_fail=%lu backpressure=%lu max_bytes=%lu", + reason, + static_cast(capture.frames_read), + static_cast(capture.frames_encoded), + static_cast(capture.frames_sent), + static_cast(capture.read_failures), + static_cast(capture.encode_failures), + static_cast(capture.backpressure_drops), + static_cast(capture.maximum_encoded_bytes)); +} + +bool EspAudioEngine::LogAudioFrameStats() +{ + const VoiceFrameStats stats = voice_frontend_.ConsumeFrameStats(); + if (stats.frames == 0) { + return false; + } + // Only duplex windows carry information worth a log line: idle wake-word + // and quiet capture windows printed all-zero ERL/reference columns every + // two seconds and drowned the conversation log. The accumulators above + // are still consumed either way so a later interesting window reports + // only its own frames. + const bool duplex_window = + stats.policy == AudioPolicy::kBargeInDuplex || + stats.policy == AudioPolicy::kCallDuplex || + stats.reference_present_frames != 0; + if (!duplex_window) { + capture_.ConsumeTimings(); + return false; + } + const uint32_t frames = stats.frames; + const uint32_t microphone_rms = stats.microphone_rms_sum / frames; + const uint32_t processed_rms = stats.processed_rms_sum / frames; + const uint32_t reference_rms = stats.reference_rms_sum / frames; + // Echo return loss: how much quieter the chain made the microphone. With a + // correctly aligned reference this is strongly positive while the speaker + // is playing; near 0 dB means the AEC is not cancelling and the device is + // about to hear itself. + float echo_return_loss_db = 0.0F; + if (microphone_rms > 0 && processed_rms > 0) { + echo_return_loss_db = 20.0F * std::log10( + static_cast(microphone_rms) / + static_cast(processed_rms)); + } + const uint32_t period_us_avg = frames > 1 + ? static_cast(stats.period_us_sum / (frames - 1)) + : 0; + const CaptureTimings timings = capture_.ConsumeTimings(); + if (timings.frames != 0) { + const uint32_t n = timings.frames; + ESP_LOGI( + kTag, + "capture timing n=%lu read=%lu/%lu convert=%lu process=%lu/%lu " + "encode=%lu/%lu submit=%lu/%lu (us, avg/max)", + static_cast(n), + static_cast(timings.read_us / n), + static_cast(timings.read_us_max), + static_cast(timings.convert_us / n), + static_cast(timings.process_us / n), + static_cast(timings.process_us_max), + static_cast(timings.encode_us / n), + static_cast(timings.encode_us_max), + static_cast(timings.submit_us / n), + static_cast(timings.submit_us_max)); + } + ESP_LOGI( + kTag, + "frame stats policy=%s n=%lu mic_rms=%lu/%lu out_rms=%lu/%lu " + "erl=%.1fdB ref_rms=%lu/%lu ref_present=%lu ref_active=%lu " + "ref_depth=%.1f/%lu aec=%d ns=%d barge_profile=%d agc_gain=%.2f " + "vad_speech=%lu period_avg=%.1fms period_max=%.1fms", + ToString(stats.policy), + static_cast(frames), + static_cast(microphone_rms), + static_cast(stats.microphone_rms_peak), + static_cast(processed_rms), + static_cast(stats.processed_rms_peak), + echo_return_loss_db, + static_cast(reference_rms), + static_cast(stats.reference_rms_peak), + static_cast(stats.reference_present_frames), + static_cast(stats.reference_active_frames), + static_cast(stats.reference_depth_sum) / + static_cast(frames), + static_cast(stats.reference_depth_peak), + stats.aec_active ? 1 : 0, + stats.ns_active ? 1 : 0, + stats.barge_in_profile ? 1 : 0, + static_cast(stats.agc_gain), + static_cast(stats.vad_speech_frames), + static_cast(period_us_avg) / 1000.0, + static_cast(stats.period_us_max) / 1000.0); + return true; +} + +void EspAudioEngine::PublishFatalError(uint32_t error_id) +{ + ESP_LOGE(kTag, "fatal audio initialization error=%lu", + static_cast(error_id)); + if (publisher_ != nullptr) { + publisher_->Publish( + AppEvent::Make(AppEventType::kFatalError, error_id)); + } +} + +} // namespace borla diff --git a/main/adapters/esp_audio_engine.h b/main/adapters/esp_audio_engine.h new file mode 100644 index 0000000..f201d8d --- /dev/null +++ b/main/adapters/esp_audio_engine.h @@ -0,0 +1,94 @@ +#pragma once + +#include "audio/audio_output.h" +#include "audio/audio_input.h" +#include "audio/capture_pipeline.h" +#include "audio/downlink_preroll_buffer.h" +#include "audio/local_prompt_player.h" +#include "audio/playback_pipeline.h" +#include "audio/voice_frontend.h" +#include "ports/audio_engine.h" +#include "ports/event_publisher.h" +#include "protocol/realtime_binary_sink.h" + +#include +#include + +namespace borla { + +class EspAudioEngine final + : public IAudioEngine, + public IRealtimeBinarySink { +public: + EspAudioEngine(IAudioOutput& output, IAudioInput& input); + ~EspAudioEngine(); + + void SetEventPublisher(IEventPublisher* publisher); + void SetUplinkSink(IEncodedAudioSink* sink); + // Debug recorder pass-through: the capture pipeline feeds the tap's + // "server's-ear" uplink channel. + void SetAudioTap(AudioTap* tap) { capture_.SetAudioTap(tap); } + + bool Start() override; + void Stop() override; + void ApplyPolicy(AudioPolicy policy) override; + void SetVolume(uint8_t volume_percent) override; + void SetWakeWordEnabled(bool enabled) override; + void SetBargeInEnabled(bool enabled) override; + void SetPlaybackPaused(bool paused) override; + void ReleaseWakeWord() override; + bool WaitForPlaybackIdle(uint32_t timeout_ms) override; + void LogAudioMetrics(const char* reason) override; + bool LogAudioFrameStats() override; + void CancelPlayback(PlaybackSessionId session_id) override; + void BeginRemotePlayback( + PlaybackSessionId session_id, + PlaybackPriority priority) override; + void EndPlaybackInput(PlaybackSessionId session_id) override; + bool SubmitOpusFrame( + PlaybackSessionId session_id, + const uint8_t* data, + size_t size) override; + PlaybackSessionId PlayLocalPrompt( + LocalPrompt prompt, + PlaybackPriority priority, + int16_t selector = -1) override; + PlaybackSessionId PlayLocalSequence( + const LocalPromptSequence& sequence, + PlaybackPriority priority) override; + PlaybackSessionId PlayDetachedPrompt( + LocalPrompt prompt, + PlaybackPriority priority) override; + uint8_t OutputVolumePercent() const override; + void OnRealtimeBinary( + const uint8_t* data, + size_t size, + uint32_t playback_session_id) override; + + PlaybackSessionSnapshot PlaybackSnapshot() const; + PlaybackMetrics PlaybackMetricsSnapshot() const; + CaptureMetrics CaptureMetricsSnapshot() const; + VoiceFrontendMetrics VoiceMetricsSnapshot() const; + +private: + void PublishFatalError(uint32_t error_id); + void RefreshEffectivePolicy(); + void ClearPrerollLocked(); + void FlushPrerollLocked(PlaybackSessionId session_id); + + IAudioOutput& output_; + IAudioInput& input_; + IEventPublisher* publisher_ = nullptr; + PlaybackPipeline playback_; + LocalPromptPlayer prompts_; + VoiceFrontend voice_frontend_; + CapturePipeline capture_; + std::mutex downlink_mutex_; + DownlinkPrerollBuffer* preroll_ = nullptr; + std::atomic requested_policy_{AudioPolicy::kOff}; + std::atomic wake_word_enabled_{true}; + std::atomic barge_in_enabled_{false}; + bool started_ = false; +}; + +} // namespace borla diff --git a/main/app/app_event_queue.h b/main/app/app_event_queue.h new file mode 100644 index 0000000..7a38e4f --- /dev/null +++ b/main/app/app_event_queue.h @@ -0,0 +1,52 @@ +#pragma once + +#include "core/app_event.h" + +#include +#include + +#include +#include + +namespace borla { + +class AppEventQueue { +public: + static constexpr size_t kCapacity = 32; + + AppEventQueue() + { + queue_ = xQueueCreateStatic( + kCapacity, + sizeof(AppEvent), + storage_, + &queue_storage_); + } + + bool Publish(const AppEvent& event, TickType_t wait_ticks = 0) + { + return xQueueSend(queue_, &event, wait_ticks) == pdTRUE; + } + + bool PublishFromIsr(const AppEvent& event, BaseType_t* higher_priority_woken) + { + return xQueueSendFromISR(queue_, &event, higher_priority_woken) == pdTRUE; + } + + bool Receive(AppEvent* event, TickType_t wait_ticks = portMAX_DELAY) + { + return xQueueReceive(queue_, event, wait_ticks) == pdTRUE; + } + + size_t Pending() const + { + return static_cast(uxQueueMessagesWaiting(queue_)); + } + +private: + StaticQueue_t queue_storage_{}; + alignas(AppEvent) uint8_t storage_[kCapacity * sizeof(AppEvent)]{}; + QueueHandle_t queue_ = nullptr; +}; + +} // namespace borla diff --git a/main/app/application.cc b/main/app/application.cc new file mode 100644 index 0000000..133a178 --- /dev/null +++ b/main/app/application.cc @@ -0,0 +1,92 @@ +#include "app/application.h" + +#include "core/state_reducer.h" + +#include + +namespace borla +{ + namespace + { + + constexpr const char *kTag = "Application2"; + + } // namespace + + Application::Application(IEffectSink &effects) + : effects_(effects) + { + } + + [[noreturn]] void Application::Run() + { + ESP_LOGI(kTag, "control-plane event loop starting"); + + ProcessEvent(AppEvent::Make(AppEventType::kBootRequested)); + + while (true) + { + AppEvent event; + if (events_.Receive(&event)) + { + ProcessEvent(event); + } + } + } + + bool Application::Publish(const AppEvent &event) + { + if (events_.Publish(event)) + { + return true; + } + + ESP_LOGE(kTag, "event queue full, dropped event=%s pending=%u", + ToString(event.type), + static_cast(events_.Pending())); + return false; + } + + void Application::ProcessEvent(const AppEvent &event) + { + const TransitionResult transition = ReduceState(state_, event); + const StateValidation validation = ValidateRuntimeState(transition.next); + if (!validation.valid) + { + ESP_LOGE(kTag, "rejected invalid transition event=%s reason=%s", + ToString(event.type), validation.reason); + return; + } + + state_ = transition.next; + LogState(event); + + for (size_t i = 0; i < transition.effect_count; ++i) + { + effects_.Handle(transition.effects[i], state_); + } + for (size_t i = 0; i < observer_count_; ++i) + { + observers_[i]->OnApplicationEvent(event, state_); + } + } + + void Application::LogState(const AppEvent &event) const + { + ESP_LOGI(kTag, + "event=%s lifecycle=%s net=%s realtime=%s conversation=%s " + "call=%s playback=%s session=%lu pending_start=%d " + "pending_soft_off=%d", + ToString(event.type), + ToString(state_.lifecycle), + ToString(state_.connectivity), + ToString(state_.realtime), + ToString(state_.conversation), + ToString(state_.call), + ToString(state_.playback), + static_cast(state_.playback_session_id), + state_.pending_conversation_start ? 1 : 0, + state_.pending_soft_off_after_playback ? 1 : 0); + } + +} // namespace borla diff --git a/main/app/application.h b/main/app/application.h new file mode 100644 index 0000000..0662f6b --- /dev/null +++ b/main/app/application.h @@ -0,0 +1,41 @@ +#pragma once + +#include "app/app_event_queue.h" +#include "core/runtime_state.h" +#include "ports/effect_sink.h" +#include "ports/event_publisher.h" +#include "ports/application_observer.h" + +#include + +namespace borla { + +class Application final : public IEventPublisher { +public: + explicit Application(IEffectSink& effects); + + [[noreturn]] void Run(); + bool Publish(const AppEvent& event) override; + bool AddObserver(IApplicationObserver* observer) + { + if (observer == nullptr || observer_count_ >= observers_.size()) { + return false; + } + observers_[observer_count_++] = observer; + return true; + } + + const RuntimeState& state() const { return state_; } + +private: + void ProcessEvent(const AppEvent& event); + void LogState(const AppEvent& event) const; + + IEffectSink& effects_; + AppEventQueue events_; + RuntimeState state_; + std::array observers_{}; + size_t observer_count_ = 0; +}; + +} // namespace borla diff --git a/main/app/composition_root.cc b/main/app/composition_root.cc new file mode 100644 index 0000000..059f4ce --- /dev/null +++ b/main/app/composition_root.cc @@ -0,0 +1,401 @@ +#include "app/composition_root.h" + +#include "platform/borla_s3/board_config.h" +#include +#include +#include +#include +#include + +namespace borla +{ + namespace + { + + constexpr const char *kTag = "CompositionRoot2"; + constexpr uint32_t kSystemServicesInitializationError = 1000; + constexpr uint32_t kPlatformInitializationError = 1001; + constexpr uint32_t kButtonInitializationError = 1002; + constexpr uint32_t kConnectivityInitializationError = 1003; + constexpr uint32_t kRealtimeInitializationError = 1004; + constexpr uint32_t kProvisioningInitializationError = 1005; + constexpr uint32_t kSensorInitializationError = 1006; + constexpr uint32_t kScheduleInitializationError = 1007; + constexpr uint32_t kPowerInitializationError = 1008; + constexpr uint32_t kIdleInitializationError = 1009; + constexpr uint32_t kOtaInitializationError = 1010; + constexpr uint32_t kFriendInitializationError = 1011; + constexpr uint32_t kMemoryInitializationError = 1012; + constexpr uint32_t kActivationInitializationError = 1013; + constexpr uint32_t kDiagnosticsInitializationError = 1014; + constexpr uint32_t kRemoteBehaviorInitializationError = 1015; + constexpr uint32_t kTca9555InitializationError = 1016; + + } // namespace + + CompositionRoot::CompositionRoot() + : i2c_bus_(), + tca9555_(i2c_bus_), + platform_(tca9555_), + // audio_output_(i2c_bus_),、 + audio_output_(i2c_bus_, tca9555_), + audio_(audio_output_, audio_output_), + activation_replay_(audio_), + dual_network_transport_( + wifi_transport_, + cellular_transport_, + DualNetworkPolicyConfig{ + board_config::kWifiDisconnectFailoverMs, + board_config::kWifiWeakRssiDbm, + board_config::kWifiWeakSampleCount, + board_config::kModemAbsentSampleCount, + board_config::kModemUnavailableRepeatMs, + }), + connectivity_( + dual_network_transport_, + wifi_credentials_, + ReconnectBackoffConfig{ + board_config::kWifiRetryInitialDelayMs, + board_config::kWifiRetryMaximumDelayMs, + board_config::kWifiRetryMultiplier, + board_config::kWifiRetryJitterPercent, + }), + realtime_(websocket_transport_, realtime_config_), + friend_service_( + ble_friend_exchange_, + friend_store_, + realtime_,connectivity_), + imu_(i2c_bus_), + sensors_(touch_, imu_, battery_, realtime_), + alarms_(alarm_store_), + schedule_(reminders_, alarms_), + alert_ringer_(audio_, alarms_), + provisioning_(wifi_transport_, wifi_credentials_, platform_, audio_), + power_(sensors_, sensors_, alarms_, reminders_, platform_), + effect_router_(audio_, connectivity_, realtime_, platform_, + friend_service_, provisioning_, ota_, + alert_ringer_, power_), + application_(effect_router_), + //button_(application_, remote_behavior_config_) + idle_(), + button_(application_, remote_behavior_config_, tca9555_)//2026-9-4 ckkj add + { + audio_.SetEventPublisher(&application_); + connectivity_.SetEventPublisher(&application_); + connectivity_.SetRemoteBehaviorConfig( + &remote_behavior_config_); + realtime_.SetEventPublisher(&application_); + realtime_.SetBinarySink(&audio_); + realtime_.SetScheduleCommandHandler(&schedule_); + realtime_.SetBatteryStatusProvider(&sensors_); + realtime_.SetVolumeStatusProvider(&audio_); + realtime_.SetDeviceProfileSink(&friend_service_); + realtime_.SetLocalSequenceHandler(&activation_replay_); + realtime_.SetMemoryCache(&memory_cache_); + realtime_.SetRemoteBehaviorConfig( + &remote_behavior_config_); + audio_.SetUplinkSink(&realtime_); + ota_.SetRealtimeConfigStore(&realtime_config_); + ota_.SetRealtimeProtocol(&realtime_); + sensors_.SetEventPublisher(&application_); + provisioning_.SetEventPublisher(&application_); + diagnostics_.SetAudioEngine(&audio_); + alert_ringer_.SetEventPublisher(application_); + application_.AddObserver(&idle_); + application_.AddObserver(&ota_); + application_.AddObserver(&friend_service_); + application_.AddObserver(&activation_replay_); + } + + bool CompositionRoot::Initialize() + { + if (!InitializeSystemServices()) + { + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kSystemServicesInitializationError)); + return false; + } + +#if CONFIG_BORLA_AUDIO_TAP + // Armed before the audio engine starts so the boot prompt is already in + // the ring when the host recorder attaches. Failure is logged inside and + // never blocks boot — this is diagnostics, not product. + if (audio_tap_.Initialize()) + { + audio_output_.SetAudioTap(&audio_tap_); + audio_.SetAudioTap(&audio_tap_); + } +#endif + + bool valid = true; + if (!i2c_bus_.Initialize()) + { + ESP_LOGE(kTag, "I2C bus initialization failed"); + valid = false; + } + esp_err_t tca_ret = tca9555_.Init(); + if (tca_ret != ESP_OK) + { + ESP_LOGE(kTag, "TCA9555 IO扩展芯片 init failed, err=%d", tca_ret); + valid = false; + } + else + { + ESP_LOGI(kTag, "TCA9555 IO扩展初始化成功"); + //tca9555_.set_pin(V5_EN);//舵机,SD需要 + cellular_transport_.SetPowerControl( + [this](bool on) { + if (on) { + tca9555_.set_pin(EN_4G); + } else { + tca9555_.clr_pin(EN_4G);// 4G模块断电 + } + uint8_t out0 = 0; + if (tca9555_.read_reg(TCA9555_REG_OUT0, &out0) == ESP_OK) { + ESP_LOGI(kTag, "4G pwr on=%d OUT0=0x%02x EN_4G(P0.2)=%d", on, out0, (out0 >> TCA_P0_ADD_IO) & 1U); + } + }); + } + if (!platform_.Initialize()) + { + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kPlatformInitializationError)); + valid = false; + } + else + { + // uint8_t val = 0; + // esp_err_t ret = tca9555_.read_p1_input(&val); + // ESP_LOGI(kTag,"val=%02X",val); + + const DeviceIdentity &identity = platform_.Identity(); + ESP_LOGI(kTag, "identity board=%s mac=%s version=%s chip=%s", + identity.board, identity.mac, identity.app_version, + identity.chip_model); + + //#if CONFIG_BORLA_AUDIO_TAP + // I2C bus scan — verifies ES8389 (0x10) and TCA9555 (0x20) are present. + // Temporary debug aid, remove after hardware is validated. + { + i2c_master_bus_handle_t bus = i2c_bus_.Handle(); + if (bus != nullptr) { + ESP_LOGI(kTag, "I2C scan start..."); + int found2 = 0; + for (uint8_t addr7 = 0x08; addr7 < 0x78; ++addr7) { + i2c_master_dev_handle_t dev = nullptr; + i2c_device_config_t cfg = { + .dev_addr_length = I2C_ADDR_BIT_LEN_7, + .device_address = addr7, + .scl_speed_hz = 100000, + .scl_wait_us = 0, + .flags = {}, + }; + if (i2c_master_bus_add_device(bus, &cfg, &dev) == ESP_OK) { + uint8_t buf = 0; + if (i2c_master_transmit_receive(dev, &buf, 1, &buf, 1, pdMS_TO_TICKS(50)) == ESP_OK) { + ESP_LOGI(kTag, "I2C scan: found device at 0x%02x (7-bit) / 0x%02x (8-bit)", + addr7, addr7 << 1); + found2++; + } + i2c_master_bus_rm_device(dev); + } + } + ESP_LOGI(kTag, "I2C scan done (brute): %d device(s) found", found2); + // Restore Port1 to normal (only power rails) + } + } +//#endif + } + if (!valid) + { + platform_.ReportError(kTca9555InitializationError); + } + + if (!dual_network_transport_.Initialize() || + !connectivity_.Initialize()) + { + platform_.ReportError(kConnectivityInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kConnectivityInitializationError)); + valid = false; + } + if (!memory_cache_.Load()) + { + platform_.ReportError(kMemoryInitializationError); + valid = false; + } + if (!remote_behavior_config_.Load()) + { + platform_.ReportError(kRemoteBehaviorInitializationError); + application_.Publish( + AppEvent::Make( + AppEventType::kFatalError, + kRemoteBehaviorInitializationError)); + valid = false; + } + if (!activation_replay_.Initialize(application_)) + { + platform_.ReportError(kActivationInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kActivationInitializationError)); + valid = false; + } + if (!diagnostics_.Initialize()) + { + platform_.ReportError(kDiagnosticsInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kDiagnosticsInitializationError)); + valid = false; + } + + if (!realtime_.Initialize(platform_.Identity())) + { + platform_.ReportError(kRealtimeInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kRealtimeInitializationError)); + valid = false; + } + + if (!friend_service_.Initialize( + platform_.Identity(), application_)) + { + platform_.ReportError(kFriendInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kFriendInitializationError)); + valid = false; + } + + if (!ota_.Initialize(platform_.Identity(), application_)) + { + platform_.ReportError(kOtaInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kOtaInitializationError)); + valid = false; + } + + if (!provisioning_.Initialize()) + { + platform_.ReportError(kProvisioningInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kProvisioningInitializationError)); + valid = false; + } + + if (!sensors_.Initialize()) + { + platform_.ReportError(kSensorInitializationError); + ESP_LOGE(kTag, "sensor service initialization failed"); + valid = false; + } + + if (!reminders_.Initialize(application_) || + !alarms_.Initialize(application_, realtime_)) + { + platform_.ReportError(kScheduleInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kScheduleInitializationError)); + valid = false; + } + //2026-9-4 ckkj add + if (!button_.Initialize()) + { + platform_.ReportError(kButtonInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kButtonInitializationError)); + valid = false; + }////// + if (!power_.Initialize(application_)) + { + platform_.ReportError(kPowerInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kPowerInitializationError)); + valid = false; + } + + if (!idle_.Initialize(application_)) + { + platform_.ReportError(kIdleInitializationError); + application_.Publish( + AppEvent::Make(AppEventType::kFatalError, + kIdleInitializationError)); + valid = false; + } + + // if (!button_.Initialize()) + // { + // platform_.ReportError(kButtonInitializationError); + // application_.Publish( + // AppEvent::Make(AppEventType::kFatalError, + // kButtonInitializationError)); + // valid = false; + // } + if (valid) + { + valid = ota_.ConfirmCurrentImage(); + } + if (!valid) + { + ota_.RejectCurrentImageAndRollback(); + } + return valid; + } + + [[noreturn]] void CompositionRoot::Run() + { + application_.Run(); + } + + bool CompositionRoot::InitializeSystemServices() + { + esp_err_t result = nvs_flash_init(); + if (result == ESP_ERR_NVS_NO_FREE_PAGES || + result == ESP_ERR_NVS_NEW_VERSION_FOUND) + { + result = nvs_flash_erase(); + if (result == ESP_OK) + { + result = nvs_flash_init(); + } + } + if (result != ESP_OK) + { + ESP_LOGE(kTag, "NVS initialization failed: %s", + esp_err_to_name(result)); + return false; + } + + result = esp_event_loop_create_default(); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) + { + ESP_LOGE(kTag, "default event loop creation failed: %s", + esp_err_to_name(result)); + return false; + } + + // 2026-9-19 ckkj fix: esp_netif_init() 原本只在 WiFi 驱动初始化时调用。 + // 强制 4G 路径下 WiFi 不启动,tcpip_init() 不执行,tcpip_mbox 未创建, + // AudioTap 的 socket() 触发 lwIP "Invalid mbox" 断言并启动循环。 + // PPP 的 esp_netif_receive 也依赖 tcpip 线程。此处统一初始化。 + result = esp_netif_init(); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "esp_netif_init failed: %s", + esp_err_to_name(result)); + return false; + }///////// + return true; + } + +} // namespace borla diff --git a/main/app/composition_root.h b/main/app/composition_root.h new file mode 100644 index 0000000..7fc0df9 --- /dev/null +++ b/main/app/composition_root.h @@ -0,0 +1,90 @@ +#pragma once + +#include "activation/activation_replay_service.h" +#include "adapters/effect_router.h" +#include "adapters/esp_audio_engine.h" +#include "app/application.h" +#include "connectivity/connectivity_manager.h" +#include "connectivity/dual_network_transport.h" +#include "connectivity/wifi_credential_store.h" +#include "configuration/remote_behavior_config.h" +#include "diagnostics/audio_tap.h" +#include "diagnostics/runtime_diagnostics_service.h" +#include "friend/friend_service.h" +#include "friend/friend_store.h" +#include "memory/memory_cache.h" +#include "platform/borla_s3/borla_s3_platform.h" +#include "platform/borla_s3/battery_monitor.h" +#include "platform/borla_s3/ble_friend_exchange.h" +#include "platform/borla_s3/bmi270_sensor.h" +#include "platform/borla_s3/button_input.h" +#include "platform/borla_s3/capacitive_touch_input.h" +#include "platform/borla_s3/es8311_audio_output.h" +#include "platform/borla_s3/esp_websocket_transport.h" +#include "platform/borla_s3/esp_wifi_transport.h" +#include "platform/borla_s3/i2c_bus.h" +#include "platform/borla_s3/ml307_transport.h" +#include "ota/ota_service.h" +#include "provisioning/ble_provisioning_service.h" +#include "power/idle_service.h" +#include "power/power_service.h" +#include "protocol/realtime_config.h" +#include "protocol/realtime_protocol.h" +#include "sensor/sensor_service.h" +#include "schedule/alarm_service.h" +#include "schedule/alarm_store.h" +#include "schedule/alert_ringer.h" +#include "schedule/reminder_service.h" +#include "schedule/schedule_coordinator.h" +#include "platform/borla_s3/tca9555.h" +namespace borla { + +class CompositionRoot final { +public: + CompositionRoot(); + + bool Initialize(); + [[noreturn]] void Run(); + +private: + bool InitializeSystemServices(); + BorlaS3I2cBus i2c_bus_; + TCA9555 tca9555_; + BorlaS3Platform platform_; + Es8311AudioOutput audio_output_; + EspAudioEngine audio_; + ActivationReplayService activation_replay_; + NvsMemoryCache memory_cache_; + NvsRemoteBehaviorConfig remote_behavior_config_; + RuntimeDiagnosticsService diagnostics_; + AudioTap audio_tap_; + NvsWifiCredentialStore wifi_credentials_; + EspWifiTransport wifi_transport_; + Ml307Transport cellular_transport_; + DualNetworkTransport dual_network_transport_; + ConnectivityManager connectivity_; + NvsRealtimeConfigStore realtime_config_; + EspWebsocketTransport websocket_transport_; + RealtimeProtocol realtime_; + BleFriendExchange ble_friend_exchange_; + NvsFriendStore friend_store_; + FriendService friend_service_; + CapacitiveTouchInput touch_; + Bmi270Sensor imu_; + BatteryMonitor battery_; + SensorService sensors_; + NvsAlarmStore alarm_store_; + ReminderService reminders_; + AlarmService alarms_; + ScheduleCoordinator schedule_; + AlertRinger alert_ringer_; + BleProvisioningService provisioning_; + OtaService ota_; + PowerService power_; + EffectRouter effect_router_; + Application application_; + IdleService idle_; + ButtonInput button_; +}; + +} // namespace borla diff --git a/main/audio/audio_input.h b/main/audio/audio_input.h new file mode 100644 index 0000000..25e0cf2 --- /dev/null +++ b/main/audio/audio_input.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +namespace borla { + +class IAudioInput { +public: + virtual ~IAudioInput() = default; + + virtual bool Read( + int16_t* samples, + size_t sample_count, + uint32_t timeout_ms) = 0; + virtual uint32_t InputSampleRate() const = 0; +}; + +} // namespace borla diff --git a/main/audio/audio_output.h b/main/audio/audio_output.h new file mode 100644 index 0000000..89df001 --- /dev/null +++ b/main/audio/audio_output.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +namespace borla { + +class IAudioOutput { +public: + virtual ~IAudioOutput() = default; + + virtual bool Initialize() = 0; + virtual void Shutdown() = 0; + virtual bool Write(const int16_t* samples, size_t sample_count) = 0; + virtual void SetVolume(uint8_t volume_percent) = 0; + virtual uint8_t VolumePercent() const = 0; + virtual uint32_t SampleRate() const = 0; +}; + +} // namespace borla diff --git a/main/audio/capture_pipeline.cc b/main/audio/capture_pipeline.cc new file mode 100644 index 0000000..a63b653 --- /dev/null +++ b/main/audio/capture_pipeline.cc @@ -0,0 +1,483 @@ +#include "audio/capture_pipeline.h" + +#include "diagnostics/audio_tap.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "CapturePipeline2"; +constexpr uint32_t kOpusBitrate = 24000; + +} // namespace + +CapturePipeline::CapturePipeline(IAudioInput& input) + : input_(input) +{ +} + +CapturePipeline::~CapturePipeline() +{ + Stop(); + heap_caps_free(hardware_pcm_); + heap_caps_free(raw_protocol_pcm_); + heap_caps_free(processed_protocol_pcm_); + heap_caps_free(encoded_); +} + +bool CapturePipeline::Initialize() +{ + if (initialized_) { + return true; + } + if (input_.InputSampleRate() != kHardwareSampleRate + || !encoder_.Initialize(kProtocolSampleRate, 1, kOpusBitrate)) { + ESP_LOGE(kTag, "input rate/encoder initialization failed"); + return false; + } + // Internal RAM: these four are touched several times per frame by the + // resampler, the AEC and the encoder, and together they are only ~7 KB. + // The bulk storage that genuinely belongs in PSRAM is encode_slots_ below, + // which is written and read once per frame as a straight memcpy. + hardware_pcm_ = static_cast( + //heap_caps_calloc(Pcm24kTo16kConverter::kInputSamples, sizeof(int16_t), + heap_caps_calloc(Pcm48kTo16kConverter::kInputSamples, sizeof(int16_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));//2026-9-3 ckkj debug :wifi start fail + //MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)); + raw_protocol_pcm_ = static_cast( + //heap_caps_calloc(Pcm24kTo16kConverter::kOutputSamples, sizeof(int16_t), + //MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)); + heap_caps_calloc(Pcm48kTo16kConverter::kOutputSamples, sizeof(int16_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));//2026-9-3 ckkj debug :wifi start fail + + processed_protocol_pcm_ = static_cast( + //heap_caps_calloc(Pcm24kTo16kConverter::kOutputSamples, sizeof(int16_t), + heap_caps_calloc(Pcm48kTo16kConverter::kOutputSamples, sizeof(int16_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + encoded_ = static_cast( + heap_caps_calloc(kBinaryAudioMaximumUplinkOpusBytes, sizeof(uint8_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + encode_slots_ = static_cast( + //heap_caps_calloc(kEncodeSlots * Pcm24kTo16kConverter::kOutputSamples, + heap_caps_calloc(kEncodeSlots * Pcm48kTo16kConverter::kOutputSamples, + sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + stopped_signal_ = xSemaphoreCreateBinaryStatic(&stopped_signal_storage_); + encoder_stopped_signal_ = + xSemaphoreCreateBinaryStatic(&encoder_stopped_signal_storage_); + encode_ready_ = xQueueCreate(kEncodeSlots, sizeof(uint8_t)); + encode_free_ = xQueueCreate(kEncodeSlots, sizeof(uint8_t)); + if (hardware_pcm_ == nullptr || raw_protocol_pcm_ == nullptr + || processed_protocol_pcm_ == nullptr + || encoded_ == nullptr || stopped_signal_ == nullptr + || encode_slots_ == nullptr || encode_ready_ == nullptr + || encode_free_ == nullptr || encoder_stopped_signal_ == nullptr) { + ESP_LOGE(kTag, "capture buffers/signal allocation failed"); + return false; + } + initialized_ = true; + ESP_LOGI(kTag, + "initialized hardware=48k protocol=16k frame=60ms bitrate=%lu", + static_cast(kOpusBitrate)); + return true; +} + +// bool CapturePipeline::Start() +// { +// if (running_.load()) { +// return true; +// } +// if (!initialized_ && !Initialize()) { +// return false; +// } +// xSemaphoreTake(stopped_signal_, 0); +// xSemaphoreTake(encoder_stopped_signal_, 0); +// xQueueReset(encode_ready_); +// xQueueReset(encode_free_); +// for (uint8_t slot = 0; slot < kEncodeSlots; ++slot) { +// xQueueSend(encode_free_, &slot, 0); +// } +// running_.store(true); +// // Plain xTaskCreate: the stack comes from the internal heap and goes back +// // to it on Stop(), which is what BLE provisioning relies on when it +// // releases the audio engine to make room for the WiFi driver. +// const BaseType_t result +// = xTaskCreatePinnedToCore(&CapturePipeline::TaskEntry, +// "capture2", task_stack_budget::kCaptureBytes, this, +// task_priority::kCaptureLoop, &task_, 0); +// if (result != pdPASS) { +// running_.store(false); +// return false; +// } +// return true; +// } + +bool CapturePipeline::Start() +{ + if (running_.load()) { + return true; + } + if (!initialized_ && !Initialize()) { + return false; + } + xSemaphoreTake(stopped_signal_, 0); + xSemaphoreTake(encoder_stopped_signal_, 0); + xQueueReset(encode_ready_); + xQueueReset(encode_free_); + for (uint8_t slot = 0; slot < kEncodeSlots; ++slot) { + xQueueSend(encode_free_, &slot, 0); + } + running_.store(true); + // Plain xTaskCreate: the stack comes from the internal heap and goes back + // to it on Stop(), which is what BLE provisioning relies on when it + // releases the audio engine to make room for the WiFi driver. + const BaseType_t result + = xTaskCreatePinnedToCore(&CapturePipeline::TaskEntry, + "capture2", task_stack_budget::kCaptureBytes, + this, + task_priority::kCaptureLoop, &task_, 0); + if (result != pdPASS) { + running_.store(false); + task_ = nullptr; + ESP_LOGE(kTag, "capture task creation failed"); + return false; + } + // Core 1: capture is pinned to core 0, so this is real parallelism. + const BaseType_t encoder_result + = xTaskCreatePinnedToCoreWithCaps(&CapturePipeline::EncoderTaskEntry, + "capture_enc2", task_stack_budget::kCaptureEncoderBytes, this, + task_priority::kAudioCodec, &encoder_task_, 1, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (encoder_result != pdPASS) { + running_.store(false); + encoder_task_ = nullptr; + // The capture task above was already created; without this it would + // park itself in vTaskSuspend forever and strand its internal-RAM + // stack — on the pool this whole exercise is trying to protect. + if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) { + ESP_LOGE(kTag, "capture task stop timed out"); + } + vTaskDelete(task_); + task_ = nullptr; + ESP_LOGE(kTag, "capture encoder task creation failed"); + return false; + } + ESP_LOGI(kTag, "task started stack_bytes=%u memory=internal prio=%u", + static_cast(task_stack_budget::kCaptureBytes), + static_cast(task_priority::kCaptureLoop)); + return true; +} + +void CapturePipeline::Stop() +{ + if (!running_.exchange(false)) { + return; + } + policy_.store(AudioPolicy::kOff); + if (task_ != nullptr) { + if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) { + ESP_LOGE(kTag, "capture task stop timed out"); + } + vTaskDelete(task_); + task_ = nullptr; + } + if (encoder_task_ != nullptr) { + if (xSemaphoreTake( + encoder_stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) { + ESP_LOGE(kTag, "capture encoder task stop timed out"); + } + vTaskDeleteWithCaps(encoder_task_); + encoder_task_ = nullptr; + } + IEncodedAudioSink* sink = sink_.load(); + if (sink != nullptr) { + sink->FlushEncodedAudio(); + } +} + +void CapturePipeline::SetSink(IEncodedAudioSink* sink) { sink_.store(sink); } + +void CapturePipeline::SetAudioTap(AudioTap* tap) +{ + audio_tap_.store(tap, std::memory_order_release); +} + +void CapturePipeline::SetProcessor(IVoiceFrameProcessor* processor) +{ + processor_.store(processor); +} + +void CapturePipeline::ApplyPolicy(AudioPolicy policy) +{ + const AudioPolicy previous = policy_.exchange(policy); + IVoiceFrameProcessor* processor = processor_.load(); + if (processor != nullptr) { + processor->ApplyPolicy(policy); + } + if (CaptureEnabled(previous) && !CaptureEnabled(policy)) { + // The encoder state must be reset by the encoder task itself, not + // here: this runs on the application task while RunEncoder may be in + // the middle of encoder_.Encode() on core 1, and libopus state is not + // reentrant — a concurrent Reset() tears the state mid-frame. Every + // conversation turn ends by leaving a capture policy, so the race was + // armed constantly. + encoder_reset_pending_.store(true); + IEncodedAudioSink* sink = sink_.load(); + if (sink != nullptr) { + sink->FlushEncodedAudio(); + } + } + // Debug: the engine's one-line summary already reports every change. + ESP_LOGD(kTag, "policy=%s capture=%d", ToString(policy), + CaptureEnabled(policy) ? 1 : 0); +} + +CaptureMetrics CapturePipeline::Metrics() const +{ + portENTER_CRITICAL(&metrics_lock_); + const CaptureMetrics snapshot = metrics_; + portEXIT_CRITICAL(&metrics_lock_); + return snapshot; +} + +void CapturePipeline::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void CapturePipeline::Run() +{ + ESP_LOGI(kTag, "capture owner task started"); + while (running_.load()) { + const AudioPolicy policy = policy_.load(); + if (!InputEnabled(policy)) { + vTaskDelay(pdMS_TO_TICKS(20)); + continue; + } + + const uint64_t read_start_us = + static_cast(esp_timer_get_time()); + if (!input_.Read( + //hardware_pcm_, Pcm24kTo16kConverter::kInputSamples, 100)) { + hardware_pcm_, Pcm48kTo16kConverter::kInputSamples, 100)) { + portENTER_CRITICAL(&metrics_lock_); + metrics_.read_failures++; + portEXIT_CRITICAL(&metrics_lock_); + continue; + } + const uint64_t convert_start_us = + static_cast(esp_timer_get_time()); + portENTER_CRITICAL(&metrics_lock_); + metrics_.frames_read++; + portEXIT_CRITICAL(&metrics_lock_); + + if (!converter_.Convert(hardware_pcm_, + // Pcm24kTo16kConverter::kInputSamples, raw_protocol_pcm_, + // Pcm24kTo16kConverter::kOutputSamples)) { + Pcm48kTo16kConverter::kInputSamples, raw_protocol_pcm_, + Pcm48kTo16kConverter::kOutputSamples)) { + portENTER_CRITICAL(&metrics_lock_); + metrics_.encode_failures++; + portEXIT_CRITICAL(&metrics_lock_); + continue; + } + + const uint64_t process_start_us = + static_cast(esp_timer_get_time()); + IVoiceFrameProcessor* processor = processor_.load(); + const bool frame_passed = processor == nullptr + || processor->Process(policy, raw_protocol_pcm_, + //Pcm24kTo16kConverter::kOutputSamples, + Pcm48kTo16kConverter::kOutputSamples, + processed_protocol_pcm_, + //Pcm24kTo16kConverter::kOutputSamples); + Pcm48kTo16kConverter::kOutputSamples); + const int16_t* upload_pcm = processor != nullptr + ? processed_protocol_pcm_ + : raw_protocol_pcm_; + // Server's-ear channel: exactly the PCM that goes to the encoder, or + // silence when this frame is suppressed/not uplinked — so listening + // to uplink.wav answers "what did the server hear at second N". + if (AudioTap* tap = + audio_tap_.load(std::memory_order_acquire)) { + const bool uplinked = frame_passed && CaptureEnabled(policy); + tap->PushUplink(uplinked ? upload_pcm : nullptr, + //Pcm24kTo16kConverter::kOutputSamples); + Pcm48kTo16kConverter::kOutputSamples); + } + if (!frame_passed) { + portENTER_CRITICAL(&metrics_lock_); + metrics_.encode_failures++; + portEXIT_CRITICAL(&metrics_lock_); + continue; + } + if (!CaptureEnabled(policy)) { + continue; + } + + const uint64_t handoff_start_us = + static_cast(esp_timer_get_time()); + + // Hand the frame to the encoder task instead of encoding here. A full + // free queue means the encoder is behind; dropping the newest frame is + // better than stalling capture, because a stalled capture loses the + // microphone stream itself and with it the AEC alignment. + uint8_t slot = 0; + if (xQueueReceive(encode_free_, &slot, 0) != pdTRUE) { + portENTER_CRITICAL(&metrics_lock_); + metrics_.backpressure_drops++; + portEXIT_CRITICAL(&metrics_lock_); + continue; + } + std::memcpy( + //encode_slots_ + slot * Pcm24kTo16kConverter::kOutputSamples, + encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples, + upload_pcm, + //Pcm24kTo16kConverter::kOutputSamples * sizeof(int16_t)); + Pcm48kTo16kConverter::kOutputSamples * sizeof(int16_t)); + if (xQueueSend(encode_ready_, &slot, 0) != pdTRUE) { + xQueueSend(encode_free_, &slot, 0); + portENTER_CRITICAL(&metrics_lock_); + metrics_.backpressure_drops++; + portEXIT_CRITICAL(&metrics_lock_); + continue; + } + + const uint64_t handoff_end_us = + static_cast(esp_timer_get_time()); + RecordTimings( + static_cast(convert_start_us - read_start_us), + static_cast(process_start_us - convert_start_us), + static_cast(handoff_start_us - process_start_us), + 0, + static_cast(handoff_end_us - handoff_start_us)); + } + xSemaphoreGive(stopped_signal_); + for (;;) { + vTaskSuspend(nullptr); + } +} + +void CapturePipeline::EncoderTaskEntry(void* context) +{ + static_cast(context)->RunEncoder(); +} + +[[noreturn]] void CapturePipeline::RunEncoder() +{ + ESP_LOGI(kTag, "capture encoder task started stack_bytes=%u memory=PSRAM", + static_cast(task_stack_budget::kCaptureEncoderBytes)); + while (running_.load()) { + if (encoder_reset_pending_.exchange(false)) { + encoder_.Reset(); + } + uint8_t slot = 0; + if (xQueueReceive(encode_ready_, &slot, pdMS_TO_TICKS(100)) + != pdTRUE) { + continue; + } + const int16_t* pcm = + //encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples; + encode_slots_ + slot * Pcm48kTo16kConverter::kOutputSamples; + const uint64_t encode_start_us = + static_cast(esp_timer_get_time()); + size_t encoded_size = 0; + const bool encoded = encoder_.Encode(pcm, + //Pcm24kTo16kConverter::kOutputSamples, encoded_, + Pcm48kTo16kConverter::kOutputSamples, encoded_, + kBinaryAudioMaximumUplinkOpusBytes, &encoded_size); + const uint64_t encode_end_us = + static_cast(esp_timer_get_time()); + + bool sent = false; + if (encoded) { + IEncodedAudioSink* sink = sink_.load(); + sent = sink != nullptr + && sink->SubmitEncodedAudio(encoded_, encoded_size); + } + const uint64_t submit_end_us = + static_cast(esp_timer_get_time()); + + xQueueSend(encode_free_, &slot, 0); + + portENTER_CRITICAL(&metrics_lock_); + if (!encoded) { + metrics_.encode_failures++; + } else { + metrics_.frames_encoded++; + metrics_.maximum_encoded_bytes + = std::max(metrics_.maximum_encoded_bytes, + static_cast(encoded_size)); + if (sent) { + metrics_.frames_sent++; + } else { + metrics_.backpressure_drops++; + } + } + timings_.encode_us += encode_end_us - encode_start_us; + timings_.encode_us_max = std::max(timings_.encode_us_max, + static_cast(encode_end_us - encode_start_us)); + timings_.submit_us += submit_end_us - encode_end_us; + portEXIT_CRITICAL(&metrics_lock_); + // One tick between frames so IDLE1 gets runtime while the slot queue + // is backlogged. A single opus_encode() call cannot yield internally, + // and when frames queue up the xQueueReceive above returns instantly, + // so without this the loop monopolises core 1 for as long as the + // backlog lasts and the task watchdog fires — every backtrace it + // printed ended inside silk_encode. Costs 1 ms per 60 ms frame. + vTaskDelay(1); + } + xSemaphoreGive(encoder_stopped_signal_); + for (;;) { + vTaskSuspend(nullptr); + } +} + +void CapturePipeline::RecordTimings(uint32_t read_us, uint32_t convert_us, + uint32_t process_us, uint32_t encode_us, uint32_t submit_us) +{ + portENTER_CRITICAL(&metrics_lock_); + timings_.frames++; + timings_.read_us += read_us; + timings_.convert_us += convert_us; + timings_.process_us += process_us; + timings_.encode_us += encode_us; + timings_.submit_us += submit_us; + timings_.read_us_max = std::max(timings_.read_us_max, read_us); + timings_.process_us_max = std::max(timings_.process_us_max, process_us); + timings_.encode_us_max = std::max(timings_.encode_us_max, encode_us); + timings_.submit_us_max = std::max(timings_.submit_us_max, submit_us); + portEXIT_CRITICAL(&metrics_lock_); +} + +CaptureTimings CapturePipeline::ConsumeTimings() +{ + portENTER_CRITICAL(&metrics_lock_); + const CaptureTimings snapshot = timings_; + timings_ = CaptureTimings{}; + portEXIT_CRITICAL(&metrics_lock_); + return snapshot; +} + +bool CapturePipeline::CaptureEnabled(AudioPolicy policy) const +{ + return policy == AudioPolicy::kConversationCapture + || policy == AudioPolicy::kBargeInDuplex + || policy == AudioPolicy::kCallDuplex; +} + +bool CapturePipeline::InputEnabled(AudioPolicy policy) const +{ + return policy == AudioPolicy::kWakeWordOnly || + policy == AudioPolicy::kWakeWordDuplex || + CaptureEnabled(policy); +} + +} // namespace borla diff --git a/main/audio/capture_pipeline.h b/main/audio/capture_pipeline.h new file mode 100644 index 0000000..b1ca96a --- /dev/null +++ b/main/audio/capture_pipeline.h @@ -0,0 +1,133 @@ +#pragma once + +#include "audio/audio_input.h" +#include "audio/encoded_audio_sink.h" +#include "audio/opus_frame_encoder.h" +#include "audio/pcm_rate_converter.h" +#include "audio/voice_frame_processor.h" +#include "core/runtime_state.h" +#include "core/task_stack_budget.h" + +#include +#include +#include + +namespace borla { +class AudioTap; +} + +#include +#include +#include +#include + +namespace borla { + +struct CaptureMetrics { + uint32_t frames_read = 0; + uint32_t frames_encoded = 0; + uint32_t frames_sent = 0; + uint32_t read_failures = 0; + uint32_t encode_failures = 0; + uint32_t backpressure_drops = 0; + uint32_t maximum_encoded_bytes = 0; +}; + +// Per-stage cost of the capture loop, accumulated by the capture task and +// drained by diagnostics. Added because the loop was measured at 94.6 ms per +// frame against a 60 ms budget while duplex was active — over budget means the +// I2S RX DMA overflows, frames are lost, and the AEC's microphone/reference +// alignment drifts, which is what capped echo cancellation at 13 dB and let the +// device's own TTS reach the server's ASR. Which stage is responsible was pure +// guesswork without these numbers. +struct CaptureTimings { + uint32_t frames = 0; + uint64_t read_us = 0; + uint64_t convert_us = 0; + uint64_t process_us = 0; + uint64_t encode_us = 0; + uint64_t submit_us = 0; + uint32_t read_us_max = 0; + uint32_t process_us_max = 0; + uint32_t encode_us_max = 0; + uint32_t submit_us_max = 0; +}; + +class CapturePipeline final { +public: + static constexpr uint32_t kHardwareSampleRate = 48000;//24000; + static constexpr uint32_t kProtocolSampleRate = 16000; + static constexpr uint32_t kFrameDurationMs = 60; + + explicit CapturePipeline(IAudioInput& input); + ~CapturePipeline(); + + bool Initialize(); + bool Start(); + void Stop(); + void SetSink(IEncodedAudioSink* sink); + void SetProcessor(IVoiceFrameProcessor* processor); + // Debug recorder for the "what does the server actually hear" channel. + void SetAudioTap(AudioTap* tap); + void ApplyPolicy(AudioPolicy policy); + CaptureMetrics Metrics() const; + CaptureTimings ConsumeTimings(); + +private: + // Opus encoding costs ~42 ms per 60 ms frame on this board (measured), and + // it used to run inline on the capture task together with the ~56 ms of + // AEC + wake-word work. Total ~104 ms against a 60 ms budget meant the I2S + // RX DMA overflowed every frame: audio was lost, the AEC's microphone and + // reference streams drifted apart, echo cancellation collapsed to ~9 dB and + // the device's own TTS reached the server's ASR — it answered itself. + // + // The previous firmware never had this problem because encoding lived on a + // separate task (audio_service.cc "Task 3: Opus 编码/解码"). Same split + // here, pinned to the other core so it genuinely runs in parallel with + // capture rather than merely interleaving with it. + static constexpr size_t kEncodeSlots = 4; + + static void TaskEntry(void* context); + [[noreturn]] void Run(); + static void EncoderTaskEntry(void* context); + [[noreturn]] void RunEncoder(); + void RecordTimings(uint32_t read_us, uint32_t convert_us, + uint32_t process_us, uint32_t encode_us, uint32_t submit_us); + bool CaptureEnabled(AudioPolicy policy) const; + bool InputEnabled(AudioPolicy policy) const; + + IAudioInput& input_; + std::atomic sink_ { nullptr }; + std::atomic processor_ { nullptr }; + std::atomic audio_tap_ { nullptr }; + std::atomic policy_ { AudioPolicy::kOff }; + OpusFrameEncoder encoder_; + //Pcm24kTo16kConverter converter_; + Pcm48kTo16kConverter converter_; + + // Set by ApplyPolicy when leaving a capture policy; consumed by the + // encoder task, which is the only task allowed to touch encoder_ state. + std::atomic encoder_reset_pending_ { false }; + int16_t* encode_slots_ = nullptr; + QueueHandle_t encode_ready_ = nullptr; + QueueHandle_t encode_free_ = nullptr; + TaskHandle_t encoder_task_ = nullptr; + SemaphoreHandle_t encoder_stopped_signal_ = nullptr; + StaticSemaphore_t encoder_stopped_signal_storage_ {}; + + int16_t* hardware_pcm_ = nullptr; + int16_t* raw_protocol_pcm_ = nullptr; + int16_t* processed_protocol_pcm_ = nullptr; + uint8_t* encoded_ = nullptr; + + mutable portMUX_TYPE metrics_lock_ = portMUX_INITIALIZER_UNLOCKED; + CaptureMetrics metrics_ {}; + CaptureTimings timings_ {}; + TaskHandle_t task_ = nullptr; + SemaphoreHandle_t stopped_signal_ = nullptr; + StaticSemaphore_t stopped_signal_storage_ {}; + bool initialized_ = false; + std::atomic running_ { false }; +}; + +} // namespace borla diff --git a/main/audio/downlink_preroll_buffer.h b/main/audio/downlink_preroll_buffer.h new file mode 100644 index 0000000..3973715 --- /dev/null +++ b/main/audio/downlink_preroll_buffer.h @@ -0,0 +1,74 @@ +#pragma once + +#include "protocol/binary_audio_protocol.h" + +#include +#include +#include +#include + +namespace borla { + +// Holds the small number of downlink frames that can arrive after the +// protocol has announced a TTS session but before Application has applied the +// corresponding BeginRemotePlayback effect. The object is allocated in +// PSRAM by EspAudioEngine so the fixed frame storage does not consume +// internal DRAM. +class DownlinkPrerollBuffer final { +public: + static constexpr size_t kCapacity = 8; + + bool Push( + uint32_t session_id, + const uint8_t* data, + size_t size) + { + if (session_id == 0 || data == nullptr || size == 0 || + size > kBinaryAudioMaximumOpusBytes) { + return false; + } + if (session_id_ != session_id) { + Reset(session_id); + } + if (frame_count_ >= frames_.size()) { + return false; + } + Frame& frame = frames_[frame_count_++]; + frame.size = static_cast(size); + std::memcpy(frame.payload.data(), data, size); + return true; + } + + void Reset(uint32_t session_id = 0) + { + session_id_ = session_id; + frame_count_ = 0; + } + + uint32_t session_id() const { return session_id_; } + size_t frame_count() const { return frame_count_; } + + const uint8_t* FrameData(size_t index) const + { + return index < frame_count_ + ? frames_[index].payload.data() + : nullptr; + } + + size_t FrameSize(size_t index) const + { + return index < frame_count_ ? frames_[index].size : 0; + } + +private: + struct Frame { + uint16_t size = 0; + std::array payload{}; + }; + + std::array frames_{}; + uint32_t session_id_ = 0; + size_t frame_count_ = 0; +}; + +} // namespace borla diff --git a/main/audio/embedded_prompt_catalog.cc b/main/audio/embedded_prompt_catalog.cc new file mode 100644 index 0000000..6f5fe02 --- /dev/null +++ b/main/audio/embedded_prompt_catalog.cc @@ -0,0 +1,143 @@ +#include "audio/embedded_prompt_catalog.h" + +#include "audio_prompts_data.h" + +#include + +namespace borla { +namespace { + +const char* AssetGroup(LocalPrompt prompt) +{ + switch (prompt) { + case LocalPrompt::kActivationDevice: + return "activation_device"; + case LocalPrompt::kDeviceAlreadyBound: + return "device_already_bound"; + case LocalPrompt::kServerError: + return "server_error"; + case LocalPrompt::kAlarmWake: + return "alarm_wake"; + case LocalPrompt::kAlarmSet: + return "alarm_set"; + case LocalPrompt::kNoNetwork: + return "no_network"; + case LocalPrompt::kProvisioning: + return "wifi_config"; + case LocalPrompt::kWakeResponse: + return "wake_response"; + case LocalPrompt::kStoryExpired: + return "story_expired"; + case LocalPrompt::kIdleCheck: + return "idle_check"; + case LocalPrompt::kIdleGoodbye: + return "idle_goodbye"; + case LocalPrompt::kSnoreLight: + return "snore_light"; + case LocalPrompt::kWifiSuccess: + return "wifi_success"; + case LocalPrompt::kWelcome: + return "welcome"; + case LocalPrompt::kShutdown: + return "shutdown"; + case LocalPrompt::kBoot: + return "boot"; + case LocalPrompt::kError: + return "error"; + case LocalPrompt::kLowBattery20: + return "low_battery_20"; + case LocalPrompt::kLowBattery10: + return "low_battery_10"; + case LocalPrompt::kNet4gBootOn: + return "net4g_boot_on"; + case LocalPrompt::kNet4gOff: + return "net4g_off"; + case LocalPrompt::kNet4gOn: + return "net4g_on"; + case LocalPrompt::kNet4gNoWifi: + return "net4g_no_wifi"; + case LocalPrompt::kCallWait: + // Explicit compatibility fallbacks until dedicated call assets exist. + return "wake_response"; + case LocalPrompt::kCallRing: + return "alarm_wake"; + case LocalPrompt::kCallConnected: + return "wifi_success"; + case LocalPrompt::kCallEnded: + return "error"; + case LocalPrompt::kDigit0: + return "digit_0"; + case LocalPrompt::kDigit1: + return "digit_1"; + case LocalPrompt::kDigit2: + return "digit_2"; + case LocalPrompt::kDigit3: + return "digit_3"; + case LocalPrompt::kDigit4: + return "digit_4"; + case LocalPrompt::kDigit5: + return "digit_5"; + case LocalPrompt::kDigit6: + return "digit_6"; + case LocalPrompt::kDigit7: + return "digit_7"; + case LocalPrompt::kDigit8: + return "digit_8"; + case LocalPrompt::kDigit9: + return "digit_9"; + } + return ""; +} + +} // namespace + +size_t EmbeddedPromptCatalog::Count(LocalPrompt prompt) +{ + const char* group = AssetGroup(prompt); + size_t count = 0; + for (size_t index = 0; + index < generated_prompts::kPromptBlobCount; + ++index) { + if (std::strcmp( + generated_prompts::kPromptBlobs[index].group, + group) == 0) { + count++; + } + } + return count; +} + +bool EmbeddedPromptCatalog::Select( + LocalPrompt prompt, + uint32_t selector, + EmbeddedPromptBlob* blob) +{ + if (blob == nullptr) { + return false; + } + const char* group = AssetGroup(prompt); + const size_t count = Count(prompt); + if (count == 0) { + return false; + } + + size_t desired = selector % count; + for (size_t index = 0; + index < generated_prompts::kPromptBlobCount; + ++index) { + const auto& candidate = + generated_prompts::kPromptBlobs[index]; + if (std::strcmp(candidate.group, group) != 0) { + continue; + } + if (desired-- == 0) { + blob->data = candidate.data; + blob->size = candidate.size; + blob->filename = candidate.filename; + return true; + } + } + return false; +} + +} // namespace borla diff --git a/main/audio/embedded_prompt_catalog.h b/main/audio/embedded_prompt_catalog.h new file mode 100644 index 0000000..65796e2 --- /dev/null +++ b/main/audio/embedded_prompt_catalog.h @@ -0,0 +1,25 @@ +#pragma once + +#include "core/playback_types.h" + +#include +#include + +namespace borla { + +struct EmbeddedPromptBlob { + const uint8_t* data = nullptr; + size_t size = 0; + const char* filename = nullptr; +}; + +class EmbeddedPromptCatalog final { +public: + static bool Select( + LocalPrompt prompt, + uint32_t selector, + EmbeddedPromptBlob* blob); + static size_t Count(LocalPrompt prompt); +}; + +} // namespace borla diff --git a/main/audio/encoded_audio_sink.h b/main/audio/encoded_audio_sink.h new file mode 100644 index 0000000..d6607ac --- /dev/null +++ b/main/audio/encoded_audio_sink.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace borla { + +class IEncodedAudioSink { +public: + virtual ~IEncodedAudioSink() = default; + virtual bool SubmitEncodedAudio( + const uint8_t* data, + size_t size) = 0; + virtual void FlushEncodedAudio() = 0; +}; + +} // namespace borla diff --git a/main/audio/local_prompt_player.cc b/main/audio/local_prompt_player.cc new file mode 100644 index 0000000..3695818 --- /dev/null +++ b/main/audio/local_prompt_player.cc @@ -0,0 +1,588 @@ +#include "audio/local_prompt_player.h" + +#include "audio/packed_opus_reader.h" +#include "core/task_stack_budget.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "LocalPromptPlayer2"; +constexpr float kPi = 3.14159265358979323846f; +constexpr uint32_t kQueueBackpressureTimeoutMs = 1500; +constexpr uint16_t kActivationIntroGapMs = 1000; +constexpr uint16_t kActivationDigitGapMs = 150; +constexpr std::array< + int16_t, + PlaybackPipeline::kSamplesPerFrame> kSilence{}; + +struct ToneSegment { + uint16_t frequency_hz; + uint16_t duration_ms; + uint8_t amplitude_percent; +}; + +constexpr std::array kBootFallback = {{ + {523, 150, 24}, + {659, 200, 30}, +}}; +constexpr std::array kProvisioningFallback = {{ + {440, 100, 24}, + {554, 100, 26}, + {659, 150, 30}, +}}; +constexpr std::array kErrorFallback = {{ + {220, 200, 28}, + {0, 80, 0}, + {220, 200, 28}, +}}; +constexpr std::array kShutdownFallback = {{ + {659, 150, 24}, + {262, 250, 20}, +}}; + +uint64_t NowMs() +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace + +struct LocalPromptPlayer::ProducerContext { + LocalPromptPlayer* player = nullptr; + PlaybackSessionId session_id = 0; + std::array< + EmbeddedPromptBlob, + kMaxLocalPromptSequenceItems> blobs{}; + std::array< + LocalPrompt, + kMaxLocalPromptSequenceItems> prompts{}; + size_t count = 0; + bool activation_sequence = false; +}; + +LocalPromptPlayer::LocalPromptPlayer(PlaybackPipeline& pipeline) + : pipeline_(pipeline) +{ +} + +LocalPromptPlayer::~LocalPromptPlayer() +{ + producer_running_.store(false, std::memory_order_release); + if (producer_task_ != nullptr) { + if (xSemaphoreTake( + producer_stopped_, pdMS_TO_TICKS(2000)) != pdTRUE) { + ESP_LOGE(kTag, "prompt worker stop timed out"); + } + vTaskDeleteWithCaps(producer_task_); + producer_task_ = nullptr; + } + if (producer_queue_ != nullptr) { + ProducerContext* pending = nullptr; + while (xQueueReceive(producer_queue_, &pending, 0) == pdTRUE) { + DestroyProducerContext(pending); + } + } + if (pcm_buffer_ != nullptr) { + heap_caps_free(pcm_buffer_); + } + if (context_pool_ != nullptr) { + heap_caps_free(context_pool_); + context_pool_ = nullptr; + } +} + +bool LocalPromptPlayer::Initialize() +{ + if (pcm_buffer_ != nullptr && producer_task_ != nullptr) { + return true; + } + if (pcm_buffer_ == nullptr) { + pcm_buffer_ = static_cast(heap_caps_calloc( + PlaybackPipeline::kSamplesPerFrame, + sizeof(int16_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (pcm_buffer_ == nullptr) { + ESP_LOGE(kTag, "failed to allocate PSRAM fallback buffer"); + return false; + } + + if (producer_queue_ == nullptr) { + producer_queue_ = xQueueCreateStatic( + kProducerQueueDepth, + sizeof(ProducerContext*), + producer_queue_bytes_.data(), + &producer_queue_storage_); + } + if (producer_stopped_ == nullptr) { + producer_stopped_ = xSemaphoreCreateBinaryStatic( + &producer_stopped_storage_); + } + // if (producer_queue_ == nullptr || producer_stopped_ == nullptr) { + // ESP_LOGE(kTag, "failed to create prompt worker controls"); + // return false; + // } + if (context_pool_ == nullptr) { + context_pool_ = static_cast( + heap_caps_calloc( + kProducerQueueDepth, + sizeof(ProducerContext), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (free_slots_ == nullptr) { + free_slots_ = xQueueCreateStatic( + kProducerQueueDepth, + sizeof(uint8_t), + free_slots_bytes_.data(), + &free_slots_storage_); + if (free_slots_ != nullptr) { + for (uint8_t index = 0; index < kProducerQueueDepth; ++index) { + xQueueSend(free_slots_, &index, 0); + } + } + } + if (producer_queue_ == nullptr || producer_stopped_ == nullptr || + context_pool_ == nullptr || free_slots_ == nullptr) { + ESP_LOGE(kTag, "failed to create prompt worker controls or pool"); + return false; + }///////// + + xSemaphoreTake(producer_stopped_, 0); + producer_running_.store(true, std::memory_order_release); + const BaseType_t created = xTaskCreatePinnedToCoreWithCaps( + &LocalPromptPlayer::ProducerTaskEntry, + "prompt_producer", + task_stack_budget::kLocalPromptProducerBytes, + this, + 4, + &producer_task_, + 0, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (created != pdPASS) { + producer_running_.store(false, std::memory_order_release); + producer_task_ = nullptr; + ESP_LOGE(kTag, "failed to create PSRAM prompt worker"); + return false; + } + ESP_LOGI(kTag, "worker started stack_bytes=%u memory=PSRAM queue=%u", + static_cast( + task_stack_budget::kLocalPromptProducerBytes), + static_cast(kProducerQueueDepth)); + return true; +} + +PlaybackSessionId LocalPromptPlayer::Play( + LocalPrompt prompt, + PlaybackPriority priority, + int16_t selector) +{ + EmbeddedPromptBlob blob; + const uint32_t selected = + selector < 0 + ? esp_random() + : static_cast(selector); + if (!EmbeddedPromptCatalog::Select(prompt, selected, &blob)) { + ESP_LOGW(kTag, "no embedded asset prompt=%s; using tone fallback", + ToString(prompt)); + return PlayProceduralFallback(prompt, priority); + } + + auto* context = AllocateProducerContext(); + if (context == nullptr) { + ESP_LOGE(kTag, "failed to allocate PSRAM prompt context"); + return 0; + } + context->player = this; + context->blobs[0] = blob; + context->prompts[0] = prompt; + context->count = 1; + return StartProducer(context, priority); +} + +PlaybackSessionId LocalPromptPlayer::PlaySequence( + const LocalPromptSequence& sequence, + PlaybackPriority priority) +{ + if (sequence.Empty() || + sequence.count > kMaxLocalPromptSequenceItems) { + return 0; + } + auto* context = AllocateProducerContext(); + if (context == nullptr) { + return 0; + } + context->player = this; + context->activation_sequence = + sequence.Contains(LocalPrompt::kActivationDevice); + for (size_t index = 0; index < sequence.count; ++index) { + const LocalPromptSequenceItem& item = sequence.items[index]; + const uint32_t selected = item.selector < 0 + ? esp_random() + : static_cast(item.selector); + if (!EmbeddedPromptCatalog::Select( + item.prompt, + selected, + &context->blobs[context->count])) { + ESP_LOGW(kTag, + "sequence asset missing prompt=%s", + ToString(item.prompt)); + DestroyProducerContext(context); + return 0; + } + context->prompts[context->count] = item.prompt; + context->count++; + } + return StartProducer(context, priority); +} + +PlaybackSessionId LocalPromptPlayer::StartProducer( + ProducerContext* context, + PlaybackPriority priority) +{ + const PlaybackStartResult start = pipeline_.StartSession( + PlaybackSource::kLocalPrompt, priority); + if (start.status != PlaybackStartStatus::kStarted) { + ESP_LOGW(kTag, "prompt producer rejected status=%s", + ToString(start.status)); + DestroyProducerContext(context); + return start.status == PlaybackStartStatus::kAlreadyActive + ? start.session_id + : 0; + } + context->session_id = start.session_id; + const size_t item_count = context->count; + const char* first_filename = context->blobs[0].filename; + if (!producer_running_.load(std::memory_order_acquire) || + xQueueSend(producer_queue_, &context, 0) != pdTRUE) { + DestroyProducerContext(context); + pipeline_.Cancel(start.session_id); + ESP_LOGE(kTag, "prompt worker unavailable or queue full"); + return 0; + } + + ESP_LOGI(kTag, + "prompt producer started items=%u first=%s session=%lu", + static_cast(item_count), + first_filename, + static_cast(start.session_id)); + return start.session_id; +} + +void LocalPromptPlayer::ProducerTaskEntry(void* raw_context) +{ + static_cast(raw_context)->RunProducer(); +} + +LocalPromptPlayer::ProducerContext* +LocalPromptPlayer::AllocateProducerContext() +{ + // void* storage = heap_caps_calloc( + // 1, + // sizeof(ProducerContext), + // MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + // return storage == nullptr + // ? nullptr + // : new (storage) ProducerContext{};///改堆分配为队列 + if (context_pool_ == nullptr || free_slots_ == nullptr) { + return nullptr; + } + uint8_t index = 0; + if (xQueueReceive(free_slots_, &index, 0) != pdTRUE) { + return nullptr; + } + if (index >= kProducerQueueDepth) { + return nullptr; + } + ProducerContext* context = &context_pool_[index]; + new (context) ProducerContext{}; + return context; +} + +void LocalPromptPlayer::DestroyProducerContext( + ProducerContext* context) +{ + // if (context == nullptr) { + // return; + // } + if (context == nullptr || context_pool_ == nullptr || + free_slots_ == nullptr) { + return; + } + const uint8_t index = static_cast( + context - context_pool_); + if (index >= kProducerQueueDepth) { + return; + } + context->~ProducerContext(); + //heap_caps_free(context); + xQueueSend(free_slots_, &index, 0); +} + +void LocalPromptPlayer::RunProducer() +{ + while (producer_running_.load(std::memory_order_acquire)) { + ProducerContext* context = nullptr; + if (xQueueReceive( + producer_queue_, + &context, + pdMS_TO_TICKS(100)) != pdTRUE) { + continue; + } + if (!producer_running_.load(std::memory_order_acquire)) { + DestroyProducerContext(context); + break; + } + Produce(*context); + DestroyProducerContext(context); + } + xSemaphoreGive(producer_stopped_); + for (;;) { + vTaskSuspend(nullptr); + } +} + +void LocalPromptPlayer::Produce(ProducerContext& context) +{ + for (size_t index = 0; index < context.count; ++index) { + if (!producer_running_.load(std::memory_order_acquire)) { + pipeline_.Cancel(context.session_id); + return; + } + if (!SubmitEmbedded( + context.blobs[index], context.session_id)) { + return; + } + if (context.activation_sequence && + index + 1 < context.count) { + const uint16_t gap = + context.prompts[index] == + LocalPrompt::kActivationDevice + ? kActivationIntroGapMs + : kActivationDigitGapMs; + if (!SubmitSilence(context.session_id, gap)) { + return; + } + } + } + if (!pipeline_.EndInput(context.session_id)) { + ESP_LOGW(kTag, + "prompt producer ended after preemption session=%lu", + static_cast(context.session_id)); + } +} + +bool LocalPromptPlayer::SubmitEmbedded( + const EmbeddedPromptBlob& blob, + PlaybackSessionId session_id) +{ + PackedOpusReader reader(blob.data, blob.size); + if (!reader.valid()) { + pipeline_.Cancel(session_id); + ESP_LOGE(kTag, "invalid packed prompt asset=%s", blob.filename); + return false; + } + + const uint8_t* frame = nullptr; + size_t frame_size = 0; + while (reader.Next(&frame, &frame_size)) { + if (!producer_running_.load(std::memory_order_acquire)) { + pipeline_.Cancel(session_id); + return false; + } + const uint64_t wait_started = NowMs(); + while (!pipeline_.SubmitOpus(session_id, frame, frame_size)) { + if (!producer_running_.load(std::memory_order_acquire)) { + pipeline_.Cancel(session_id); + return false; + } + const PlaybackSessionSnapshot current = pipeline_.Snapshot(); + if (!current.active || current.id != session_id) { + ESP_LOGI(kTag, + "prompt producer preempted asset=%s session=%lu", + blob.filename, + static_cast(session_id)); + return false; + } + if (NowMs() - wait_started >= + kQueueBackpressureTimeoutMs) { + pipeline_.Cancel(session_id); + ESP_LOGE(kTag, + "prompt queue stalled asset=%s session=%lu", + blob.filename, + static_cast(session_id)); + return false; + } + vTaskDelay(pdMS_TO_TICKS(5)); + } + } + + if (!reader.complete()) { + pipeline_.Cancel(session_id); + ESP_LOGE(kTag, "truncated packed prompt asset=%s", blob.filename); + return false; + } + return true; +} + +bool LocalPromptPlayer::SubmitSilence( + PlaybackSessionId session_id, + uint16_t duration_ms) +{ + size_t samples_remaining = + static_cast(PlaybackPipeline::kSampleRate) * + duration_ms / 1000; + while (samples_remaining > 0) { + if (!producer_running_.load(std::memory_order_acquire)) { + pipeline_.Cancel(session_id); + return false; + } + const size_t samples = std::min( + samples_remaining, + PlaybackPipeline::kSamplesPerFrame); + const uint64_t wait_started = NowMs(); + while (!pipeline_.SubmitPcm( + session_id, kSilence.data(), samples)) { + const PlaybackSessionSnapshot current = pipeline_.Snapshot(); + if (!current.active || current.id != session_id) { + return false; + } + if (NowMs() - wait_started >= + kQueueBackpressureTimeoutMs) { + pipeline_.Cancel(session_id); + ESP_LOGE(kTag, + "sequence silence queue stalled session=%lu", + static_cast(session_id)); + return false; + } + vTaskDelay(pdMS_TO_TICKS(5)); + } + samples_remaining -= samples; + } + return true; +} + +PlaybackSessionId LocalPromptPlayer::PlayProceduralFallback( + LocalPrompt prompt, + PlaybackPriority priority) +{ + std::lock_guard lock(mutex_); + if (!Initialize()) { + return 0; + } + + const PlaybackStartResult start = pipeline_.StartSession( + PlaybackSource::kLocalPrompt, priority); + if (start.status != PlaybackStartStatus::kStarted) { + return start.status == PlaybackStartStatus::kAlreadyActive + ? start.session_id + : 0; + } + + float phase = 0.0f; + const auto submit_sequence = + [this, &start, &phase](const auto& sequence) { + for (const auto& tone : sequence) { + if (!SubmitTone( + start.session_id, + tone.frequency_hz, + tone.duration_ms, + tone.amplitude_percent, + &phase)) { + return false; + } + } + return true; + }; + + bool submitted = false; + switch (prompt) { + case LocalPrompt::kBoot: + submitted = submit_sequence(kBootFallback); + break; + case LocalPrompt::kProvisioning: + submitted = submit_sequence(kProvisioningFallback); + break; + case LocalPrompt::kShutdown: + submitted = submit_sequence(kShutdownFallback); + break; + default: + submitted = submit_sequence(kErrorFallback); + break; + } + + if (!submitted || !pipeline_.EndInput(start.session_id)) { + pipeline_.Cancel(start.session_id); + return 0; + } + return start.session_id; +} + +bool LocalPromptPlayer::SubmitTone( + PlaybackSessionId session_id, + uint16_t frequency_hz, + uint16_t duration_ms, + uint8_t amplitude_percent, + float* phase) +{ + const size_t total_samples = + static_cast(PlaybackPipeline::kSampleRate) * + duration_ms / 1000; + const float amplitude = + 32767.0f * static_cast(amplitude_percent) / 100.0f; + const size_t fade_samples = + PlaybackPipeline::kSampleRate / 100; + + size_t generated = 0; + while (generated < total_samples) { + const size_t frame_samples = std::min( + PlaybackPipeline::kSamplesPerFrame, + total_samples - generated); + for (size_t index = 0; index < frame_samples; ++index) { + const size_t absolute = generated + index; + float envelope = 1.0f; + if (absolute < fade_samples) { + envelope = static_cast(absolute) / + static_cast(fade_samples); + } else if (total_samples - absolute < fade_samples) { + envelope = static_cast(total_samples - absolute) / + static_cast(fade_samples); + } + + if (frequency_hz == 0) { + pcm_buffer_[index] = 0; + } else { + pcm_buffer_[index] = static_cast( + amplitude * envelope * std::sin(*phase)); + *phase += 2.0f * kPi * + static_cast(frequency_hz) / + static_cast( + PlaybackPipeline::kSampleRate); + if (*phase >= 2.0f * kPi) { + *phase -= 2.0f * kPi; + } + } + } + + if (!pipeline_.SubmitPcm( + session_id, pcm_buffer_, frame_samples)) { + return false; + } + generated += frame_samples; + } + return true; +} + +} // namespace borla diff --git a/main/audio/local_prompt_player.h b/main/audio/local_prompt_player.h new file mode 100644 index 0000000..6aff7cd --- /dev/null +++ b/main/audio/local_prompt_player.h @@ -0,0 +1,83 @@ +#pragma once + +#include "audio/embedded_prompt_catalog.h" +#include "audio/playback_pipeline.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace borla { + +class LocalPromptPlayer final { +public: + explicit LocalPromptPlayer(PlaybackPipeline& pipeline); + ~LocalPromptPlayer(); + + bool Initialize(); + PlaybackSessionId Play( + LocalPrompt prompt, + PlaybackPriority priority, + int16_t selector = -1); + PlaybackSessionId PlaySequence( + const LocalPromptSequence& sequence, + PlaybackPriority priority); + +private: + struct ProducerContext; + static constexpr size_t kProducerQueueDepth = 4; + + static void ProducerTaskEntry(void* context); + // static ProducerContext* AllocateProducerContext(); + // static void DestroyProducerContext(ProducerContext* context); + ProducerContext* AllocateProducerContext(); + void DestroyProducerContext(ProducerContext* context); + void RunProducer(); + void Produce(ProducerContext& context); + bool SubmitEmbedded( + const EmbeddedPromptBlob& blob, + PlaybackSessionId session_id); + bool SubmitSilence( + PlaybackSessionId session_id, + uint16_t duration_ms); + PlaybackSessionId StartProducer( + ProducerContext* context, + PlaybackPriority priority); + PlaybackSessionId PlayProceduralFallback( + LocalPrompt prompt, + PlaybackPriority priority); + bool SubmitTone( + PlaybackSessionId session_id, + uint16_t frequency_hz, + uint16_t duration_ms, + uint8_t amplitude_percent, + float* phase); + + PlaybackPipeline& pipeline_; + std::mutex mutex_; + int16_t* pcm_buffer_ = nullptr; + std::array< + uint8_t, + kProducerQueueDepth * sizeof(ProducerContext*)> + producer_queue_bytes_{}; + StaticQueue_t producer_queue_storage_{}; + QueueHandle_t producer_queue_ = nullptr; + StaticSemaphore_t producer_stopped_storage_{}; + SemaphoreHandle_t producer_stopped_ = nullptr; + std::atomic producer_running_{false}; + ///// + TaskHandle_t producer_task_ = nullptr; + ProducerContext* context_pool_ = nullptr; + std::array free_slots_bytes_{}; + StaticQueue_t free_slots_storage_{}; + QueueHandle_t free_slots_ = nullptr; +}; + +} // namespace borla diff --git a/main/audio/opus_frame_decoder.cc b/main/audio/opus_frame_decoder.cc new file mode 100644 index 0000000..af59c73 --- /dev/null +++ b/main/audio/opus_frame_decoder.cc @@ -0,0 +1,107 @@ +#include "audio/opus_frame_decoder.h" + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "OpusFrameDecoder2"; + +} // namespace + +OpusFrameDecoder::~OpusFrameDecoder() +{ + std::lock_guard lock(mutex_); + if (decoder_ != nullptr) { + opus_decoder_destroy(decoder_); + } +} + +bool OpusFrameDecoder::Initialize( + uint32_t sample_rate, + uint8_t channels) +{ + std::lock_guard lock(mutex_); + if (decoder_ != nullptr) { + return true; + } + + int error = OPUS_OK; + decoder_ = opus_decoder_create( + static_cast(sample_rate), channels, &error); + if (decoder_ == nullptr || error != OPUS_OK) { + ESP_LOGE(kTag, "opus decoder creation failed: %s", + opus_strerror(error)); + decoder_ = nullptr; + return false; + } + channels_ = channels; + ESP_LOGI(kTag, "decoder initialized rate=%lu channels=%u", + static_cast(sample_rate), + static_cast(channels)); + return true; +} + +bool OpusFrameDecoder::Decode( + const uint8_t* encoded, + size_t encoded_size, + int16_t* pcm, + size_t pcm_capacity, + size_t* decoded_samples) +{ + if (pcm == nullptr || decoded_samples == nullptr || + pcm_capacity == 0 || + (encoded_size > 0 && encoded == nullptr)) { + return false; + } + + std::lock_guard lock(mutex_); + if (decoder_ == nullptr) { + return false; + } + + const size_t capacity_per_channel = pcm_capacity / channels_; + const int decoded = opus_decode( + decoder_, + encoded, + static_cast(encoded_size), + pcm, + static_cast(capacity_per_channel), + 0); + if (decoded < 0) { + ESP_LOGE(kTag, "decode failed: %s", opus_strerror(decoded)); + return false; + } + + *decoded_samples = + static_cast(decoded) * static_cast(channels_); + // 2026-8-28 CKKJ temp debug: log first 10 frames peak + raw Opus info + static uint32_t s_decode_seq = 0; + if (s_decode_seq < 10) { + s_decode_seq++; + int32_t peak = 0; + for (size_t i = 0; i < *decoded_samples; ++i) { + int32_t a = pcm[i] < 0 ? -pcm[i] : pcm[i]; + if (a > peak) peak = a; + } + const uint8_t toc = encoded_size > 0 ? encoded[0] : 0; + ESP_LOGI(kTag, "decode seq=%u enc_size=%u toc=0x%02x decoded=%u peak=%d", + static_cast(s_decode_seq), + static_cast(encoded_size), + static_cast(toc), + static_cast(*decoded_samples), + static_cast(peak)); + }// + return true; +} + +void OpusFrameDecoder::Reset() +{ + std::lock_guard lock(mutex_); + if (decoder_ != nullptr) { + opus_decoder_ctl(decoder_, OPUS_RESET_STATE); + } +} + +} // namespace borla diff --git a/main/audio/opus_frame_decoder.h b/main/audio/opus_frame_decoder.h new file mode 100644 index 0000000..f6b8726 --- /dev/null +++ b/main/audio/opus_frame_decoder.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include + +struct OpusDecoder; + +namespace borla { + +class OpusFrameDecoder final { +public: + OpusFrameDecoder() = default; + ~OpusFrameDecoder(); + + bool Initialize(uint32_t sample_rate, uint8_t channels); + bool Decode( + const uint8_t* encoded, + size_t encoded_size, + int16_t* pcm, + size_t pcm_capacity, + size_t* decoded_samples); + void Reset(); + +private: + std::mutex mutex_; + OpusDecoder* decoder_ = nullptr; + uint8_t channels_ = 1; +}; + +} // namespace borla diff --git a/main/audio/opus_frame_encoder.cc b/main/audio/opus_frame_encoder.cc new file mode 100644 index 0000000..47f3706 --- /dev/null +++ b/main/audio/opus_frame_encoder.cc @@ -0,0 +1,105 @@ +#include "audio/opus_frame_encoder.h" + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "OpusFrameEncoder2"; + +} // namespace + +OpusFrameEncoder::~OpusFrameEncoder() +{ + std::lock_guard lock(mutex_); + if (encoder_ != nullptr) { + opus_encoder_destroy(encoder_); + } +} + +bool OpusFrameEncoder::Initialize( + uint32_t sample_rate, + uint8_t channels, + uint32_t bitrate) +{ + std::lock_guard lock(mutex_); + if (encoder_ != nullptr) { + return true; + } + int error = OPUS_OK; + encoder_ = opus_encoder_create( + static_cast(sample_rate), + channels, + OPUS_APPLICATION_VOIP, + &error); + if (encoder_ == nullptr || error != OPUS_OK) { + ESP_LOGE(kTag, "encoder creation failed: %s", + opus_strerror(error)); + encoder_ = nullptr; + return false; + } + channels_ = channels; + // Complexity 3, matching the previous firmware ("ESP32 上用最低复杂度保证 + // 实时性", audio_service.cc:14). At complexity 4 a 60 ms frame measured + // 33 ms to encode with the core to itself and 82 ms averaged when TTS + // playback shared core 1 — the task-watchdog backtraces all ended inside + // silk_encode_frame_FIX. The uplink feeds server-side ASR at 16 kHz mono; + // it does not need the marginal quality of the higher search depth. + if (opus_encoder_ctl( + encoder_, + OPUS_SET_BITRATE(static_cast(bitrate))) != OPUS_OK || + opus_encoder_ctl(encoder_, OPUS_SET_COMPLEXITY(3)) != OPUS_OK || + opus_encoder_ctl(encoder_, OPUS_SET_VBR(1)) != OPUS_OK || + opus_encoder_ctl(encoder_, OPUS_SET_DTX(0)) != OPUS_OK) { + ESP_LOGE(kTag, "encoder configuration failed"); + opus_encoder_destroy(encoder_); + encoder_ = nullptr; + return false; + } + ESP_LOGI(kTag, "initialized rate=%lu channels=%u bitrate=%lu", + static_cast(sample_rate), + static_cast(channels), + static_cast(bitrate)); + return true; +} + +bool OpusFrameEncoder::Encode( + const int16_t* pcm, + size_t samples_per_channel, + uint8_t* encoded, + size_t capacity, + size_t* encoded_size) +{ + if (pcm == nullptr || encoded == nullptr || + encoded_size == nullptr || samples_per_channel == 0 || + capacity == 0 || capacity > INT32_MAX) { + return false; + } + std::lock_guard lock(mutex_); + if (encoder_ == nullptr) { + return false; + } + const int result = opus_encode( + encoder_, + pcm, + static_cast(samples_per_channel), + encoded, + static_cast(capacity)); + if (result <= 0) { + ESP_LOGE(kTag, "encode failed: %s", opus_strerror(result)); + return false; + } + *encoded_size = static_cast(result); + return true; +} + +void OpusFrameEncoder::Reset() +{ + std::lock_guard lock(mutex_); + if (encoder_ != nullptr) { + opus_encoder_ctl(encoder_, OPUS_RESET_STATE); + } +} + +} // namespace borla diff --git a/main/audio/opus_frame_encoder.h b/main/audio/opus_frame_encoder.h new file mode 100644 index 0000000..06f42c5 --- /dev/null +++ b/main/audio/opus_frame_encoder.h @@ -0,0 +1,36 @@ +#pragma once + +#include "protocol/binary_audio_protocol.h" + +#include +#include +#include + +struct OpusEncoder; + +namespace borla { + +class OpusFrameEncoder final { +public: + OpusFrameEncoder() = default; + ~OpusFrameEncoder(); + + bool Initialize( + uint32_t sample_rate, + uint8_t channels, + uint32_t bitrate); + bool Encode( + const int16_t* pcm, + size_t samples_per_channel, + uint8_t* encoded, + size_t capacity, + size_t* encoded_size); + void Reset(); + +private: + std::mutex mutex_; + OpusEncoder* encoder_ = nullptr; + uint8_t channels_ = 1; +}; + +} // namespace borla diff --git a/main/audio/packed_opus_reader.cc b/main/audio/packed_opus_reader.cc new file mode 100644 index 0000000..d8425a6 --- /dev/null +++ b/main/audio/packed_opus_reader.cc @@ -0,0 +1,61 @@ +#include "audio/packed_opus_reader.h" + +namespace borla { +namespace { + +uint16_t ReadLe16(const uint8_t* data) +{ + return static_cast( + static_cast(data[0]) | + (static_cast(data[1]) << 8)); +} + +} // namespace + +PackedOpusReader::PackedOpusReader( + const uint8_t* data, + size_t size) + : data_(data), + size_(size) +{ + if (data_ == nullptr || size_ < 2) { + return; + } + frame_count_ = ReadLe16(data_); + offset_ = 2; + valid_ = frame_count_ > 0; +} + +bool PackedOpusReader::Next( + const uint8_t** frame, + size_t* frame_size) +{ + if (!valid_ || frame == nullptr || frame_size == nullptr || + frames_read_ >= frame_count_) { + return false; + } + if (offset_ + 2 > size_) { + valid_ = false; + return false; + } + + const uint16_t size = ReadLe16(data_ + offset_); + offset_ += 2; + if (size == 0 || offset_ + size > size_) { + valid_ = false; + return false; + } + + *frame = data_ + offset_; + *frame_size = size; + offset_ += size; + frames_read_++; + return true; +} + +bool PackedOpusReader::complete() const +{ + return valid_ && frames_read_ == frame_count_ && offset_ == size_; +} + +} // namespace borla diff --git a/main/audio/packed_opus_reader.h b/main/audio/packed_opus_reader.h new file mode 100644 index 0000000..378f36d --- /dev/null +++ b/main/audio/packed_opus_reader.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +namespace borla { + +class PackedOpusReader final { +public: + PackedOpusReader(const uint8_t* data, size_t size); + + bool Next(const uint8_t** frame, size_t* frame_size); + bool valid() const { return valid_; } + bool complete() const; + uint16_t frame_count() const { return frame_count_; } + uint16_t frames_read() const { return frames_read_; } + +private: + const uint8_t* data_ = nullptr; + size_t size_ = 0; + size_t offset_ = 0; + uint16_t frame_count_ = 0; + uint16_t frames_read_ = 0; + bool valid_ = false; +}; + +} // namespace borla diff --git a/main/audio/pcm_rate_converter.cc b/main/audio/pcm_rate_converter.cc new file mode 100644 index 0000000..3160e61 --- /dev/null +++ b/main/audio/pcm_rate_converter.cc @@ -0,0 +1,45 @@ +#include "audio/pcm_rate_converter.h" + +#include + +namespace borla { +constexpr int32_t kMicDigitalGain = 16; +//bool Pcm24kTo16kConverter::Convert( +bool Pcm48kTo16kConverter::Convert( + const int16_t* input, + size_t input_samples, + int16_t* output, + size_t output_capacity) const +{ + if (input == nullptr || output == nullptr || + input_samples != kInputSamples || + output_capacity < kOutputSamples) { + return false; + } + + // 24k -> 16k is a 3:2 ratio. Even outputs copy an input sample and odd + // outputs interpolate the two adjacent samples. The exact frame boundary + // is preserved, which is more important than a streaming fractional + // accumulator for the fixed 60 ms protocol. + for (size_t index = 0; index < kOutputSamples; ++index) { + const size_t base = (index * 3U) / 2U *2U; + int32_t value; + if ((index & 1U) == 0U) { + value = static_cast(input[base]); + } else { + value = (static_cast(input[base]) + static_cast(input[base + 2U])) / 2; + } + value *= kMicDigitalGain; + output[index] = static_cast(std::clamp(value, -32768, 32767)); + // const size_t base = index * 3U; + // const int32_t mixed = + // static_cast(input[base]) + + // static_cast(input[base + 1]) + + // static_cast(input[base + 2]); + // output[index] = static_cast( + // std::clamp(mixed / 3, -32768, 32767)); + } + return true; +} + +} // namespace borla diff --git a/main/audio/pcm_rate_converter.h b/main/audio/pcm_rate_converter.h new file mode 100644 index 0000000..851a924 --- /dev/null +++ b/main/audio/pcm_rate_converter.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + +namespace borla { + +// Stateless conversion for exact 60 ms frames. The hardware codec runs at +// 24 kHz so RX and TX can share one I2S clock; uplink is converted to the +// protocol's fixed 16 kHz rate before voice processing/Opus. +//class Pcm24kTo16kConverter final { +class Pcm48kTo16kConverter final { +public: + //static constexpr size_t kInputSamples = 1440; + static constexpr size_t kInputSamples = 2880; + static constexpr size_t kOutputSamples = 960; + + bool Convert( + const int16_t* input, + size_t input_samples, + int16_t* output, + size_t output_capacity) const; +}; + +} // namespace borla diff --git a/main/audio/playback_controller.cc b/main/audio/playback_controller.cc new file mode 100644 index 0000000..fe980f1 --- /dev/null +++ b/main/audio/playback_controller.cc @@ -0,0 +1,321 @@ +#include "audio/playback_controller.h" + +#include +#include + +namespace borla { +namespace { + +constexpr PlaybackSessionId kLocalSessionIdBase = 0x80000000U; + +bool IsRemoteSource(PlaybackSource source) +{ + return source == PlaybackSource::kRemoteTts || + source == PlaybackSource::kRemoteMusic; +} + +} // namespace + +PlaybackStartResult PlaybackController::StartSession( + PlaybackSource source, + PlaybackPriority priority, + PlaybackSessionId requested_id, + uint64_t now_ms) +{ + if (IsRemoteSource(source) && + (requested_id == 0 || requested_id >= kLocalSessionIdBase)) { + return { + PlaybackStartStatus::kRejectedInvalidSessionId, + 0, + 0, + 0, + }; + } + + if (session_.active && requested_id != 0 && + requested_id == session_.id && source == session_.source) { + return { + PlaybackStartStatus::kAlreadyActive, + session_.id, + 0, + session_.generation, + }; + } + + if (session_.active && + static_cast(priority) < + static_cast(session_.priority)) { + metrics_.lower_priority_rejections++; + return { + PlaybackStartStatus::kRejectedLowerPriority, + 0, + 0, + 0, + }; + } + + PlaybackSessionId preempted = 0; + if (session_.active) { + preempted = session_.id; + session_.state = PlaybackSessionState::kCancelled; + session_.active = false; + metrics_.sessions_cancelled++; + metrics_.sessions_preempted++; + } + + session_ = {}; + session_.id = AllocateSessionId(requested_id); + session_.generation = next_generation_++; + if (next_generation_ == 0) { + next_generation_ = 1; + } + session_.source = source; + session_.priority = priority; + session_.state = PlaybackSessionState::kPending; + session_.active = true; + started_at_ms_ = now_ms; + last_progress_ms_ = now_ms; + metrics_.sessions_started++; + + return { + PlaybackStartStatus::kStarted, + session_.id, + preempted, + session_.generation, + }; +} + +bool PlaybackController::CanAcceptFrame( + PlaybackSessionId session_id) const +{ + return session_.active && session_id != 0 && + session_.id == session_id; +} + +bool PlaybackController::QueueFrame( + PlaybackSessionId session_id, + uint64_t now_ms) +{ + if (!CanAcceptFrame(session_id)) { + return false; + } + + session_.producer_started = true; + session_.queued_frames++; + session_.state = session_.input_ended + ? PlaybackSessionState::kDraining + : PlaybackSessionState::kStreaming; + metrics_.frames_queued++; + metrics_.queue_high_watermark = + std::max(metrics_.queue_high_watermark, session_.queued_frames); + Touch(now_ms); + return true; +} + +bool PlaybackController::RollbackQueuedFrame( + PlaybackSessionId session_id) +{ + if (!IsCurrent(session_id) || session_.queued_frames == 0) { + return false; + } + session_.queued_frames--; + metrics_.frames_dropped++; + return true; +} + +bool PlaybackController::BeginFrame( + PlaybackSessionId session_id, + uint64_t now_ms) +{ + if (!CanAcceptFrame(session_id) || session_.queued_frames == 0) { + return false; + } + session_.queued_frames--; + session_.in_flight_frames++; + Touch(now_ms); + return true; +} + +bool PlaybackController::FinishFrame( + PlaybackSessionId session_id, + bool write_succeeded, + uint64_t now_ms) +{ + if (!CanAcceptFrame(session_id) || + session_.in_flight_frames == 0) { + return false; + } + + session_.in_flight_frames--; + if (write_succeeded) { + session_.written_frames++; + metrics_.frames_written++; + } else { + metrics_.frames_dropped++; + } + Touch(now_ms); + return true; +} + +bool PlaybackController::EndInput( + PlaybackSessionId session_id, + uint64_t now_ms) +{ + if (!CanAcceptFrame(session_id)) { + return false; + } + session_.input_ended = true; + session_.state = PlaybackSessionState::kDraining; + Touch(now_ms); + return true; +} + +PlaybackSessionId PlaybackController::TryComplete() +{ + if (!session_.active || !session_.producer_started || + !session_.input_ended || session_.queued_frames != 0 || + session_.in_flight_frames != 0) { + return 0; + } + + session_.state = PlaybackSessionState::kCompleted; + session_.active = false; + metrics_.sessions_completed++; + return session_.id; +} + +PlaybackSessionId PlaybackController::Cancel( + PlaybackSessionId session_id) +{ + if (!session_.active || + (session_id != 0 && session_id != session_.id)) { + return 0; + } + + session_.state = PlaybackSessionState::kCancelled; + session_.active = false; + session_.queued_frames = 0; + metrics_.sessions_cancelled++; + return session_.id; +} + +PlaybackSessionId PlaybackController::Fail( + PlaybackSessionId session_id) +{ + if (!session_.active || session_id != session_.id) { + return 0; + } + + session_.state = PlaybackSessionState::kFailed; + session_.active = false; + session_.queued_frames = 0; + metrics_.sessions_failed++; + return session_.id; +} + +PlaybackTimeoutResult PlaybackController::CheckTimeout( + uint64_t now_ms, + uint32_t producer_start_timeout_ms, + uint32_t stalled_timeout_ms) +{ + if (!session_.active) { + return {}; + } + + if (!session_.producer_started && + now_ms - started_at_ms_ >= producer_start_timeout_ms) { + const PlaybackSessionId failed = Fail(session_.id); + metrics_.producer_start_timeouts++; + return {PlaybackTimeoutReason::kProducerStart, failed}; + } + + if (session_.producer_started && stalled_timeout_ms > 0 && + now_ms - last_progress_ms_ >= stalled_timeout_ms) { + const PlaybackSessionId failed = Fail(session_.id); + metrics_.stalled_timeouts++; + return {PlaybackTimeoutReason::kStalled, failed}; + } + + return {}; +} + +void PlaybackController::RecordStaleFrame() +{ + metrics_.stale_frames_rejected++; + metrics_.frames_dropped++; +} + +bool PlaybackController::IsCurrent( + PlaybackSessionId session_id) const +{ + return session_.active && session_.id == session_id; +} + +PlaybackSessionId PlaybackController::AllocateSessionId( + PlaybackSessionId requested_id) +{ + if (requested_id != 0) { + return requested_id; + } + + const PlaybackSessionId allocated = next_session_id_; + next_session_id_++; + if (next_session_id_ < kLocalSessionIdBase) { + next_session_id_ = kLocalSessionIdBase; + } + return allocated; +} + +void PlaybackController::Touch(uint64_t now_ms) +{ + last_progress_ms_ = now_ms; +} + +const char* ToString(PlaybackSessionState state) +{ + switch (state) { + case PlaybackSessionState::kPending: + return "pending"; + case PlaybackSessionState::kStreaming: + return "streaming"; + case PlaybackSessionState::kDraining: + return "draining"; + case PlaybackSessionState::kCancelled: + return "cancelled"; + case PlaybackSessionState::kCompleted: + return "completed"; + case PlaybackSessionState::kFailed: + return "failed"; + } + return "unknown"; +} + +const char* ToString(PlaybackStartStatus status) +{ + switch (status) { + case PlaybackStartStatus::kStarted: + return "started"; + case PlaybackStartStatus::kAlreadyActive: + return "already_active"; + case PlaybackStartStatus::kRejectedLowerPriority: + return "rejected_lower_priority"; + case PlaybackStartStatus::kRejectedInvalidSessionId: + return "rejected_invalid_session_id"; + } + return "unknown"; +} + +const char* ToString(PlaybackTimeoutReason reason) +{ + switch (reason) { + case PlaybackTimeoutReason::kNone: + return "none"; + case PlaybackTimeoutReason::kProducerStart: + return "producer_start"; + case PlaybackTimeoutReason::kStalled: + return "stalled"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/audio/playback_controller.h b/main/audio/playback_controller.h new file mode 100644 index 0000000..74ba34b --- /dev/null +++ b/main/audio/playback_controller.h @@ -0,0 +1,121 @@ +#pragma once + +#include "core/playback_types.h" + +#include +#include + +namespace borla { + +enum class PlaybackSessionState : uint8_t { + kPending, + kStreaming, + kDraining, + kCancelled, + kCompleted, + kFailed, +}; + +enum class PlaybackStartStatus : uint8_t { + kStarted, + kAlreadyActive, + kRejectedLowerPriority, + kRejectedInvalidSessionId, +}; + +enum class PlaybackTimeoutReason : uint8_t { + kNone, + kProducerStart, + kStalled, +}; + +struct PlaybackSessionSnapshot { + PlaybackSessionId id = 0; + uint32_t generation = 0; + PlaybackSource source = PlaybackSource::kRemoteTts; + PlaybackPriority priority = PlaybackPriority::kConversation; + PlaybackSessionState state = PlaybackSessionState::kCompleted; + size_t queued_frames = 0; + size_t in_flight_frames = 0; + uint32_t written_frames = 0; + bool active = false; + bool producer_started = false; + bool input_ended = false; +}; + +struct PlaybackMetrics { + uint32_t sessions_started = 0; + uint32_t sessions_completed = 0; + uint32_t sessions_cancelled = 0; + uint32_t sessions_failed = 0; + uint32_t sessions_preempted = 0; + uint32_t lower_priority_rejections = 0; + uint32_t stale_frames_rejected = 0; + uint32_t frames_queued = 0; + uint32_t frames_written = 0; + uint32_t frames_dropped = 0; + uint32_t producer_start_timeouts = 0; + uint32_t stalled_timeouts = 0; + size_t queue_high_watermark = 0; +}; + +struct PlaybackStartResult { + PlaybackStartStatus status = PlaybackStartStatus::kRejectedLowerPriority; + PlaybackSessionId session_id = 0; + PlaybackSessionId preempted_session_id = 0; + uint32_t generation = 0; +}; + +struct PlaybackTimeoutResult { + PlaybackTimeoutReason reason = PlaybackTimeoutReason::kNone; + PlaybackSessionId session_id = 0; +}; + +class PlaybackController final { +public: + PlaybackStartResult StartSession( + PlaybackSource source, + PlaybackPriority priority, + PlaybackSessionId requested_id, + uint64_t now_ms); + + bool CanAcceptFrame(PlaybackSessionId session_id) const; + bool QueueFrame(PlaybackSessionId session_id, uint64_t now_ms); + bool RollbackQueuedFrame(PlaybackSessionId session_id); + bool BeginFrame(PlaybackSessionId session_id, uint64_t now_ms); + bool FinishFrame( + PlaybackSessionId session_id, + bool write_succeeded, + uint64_t now_ms); + bool EndInput(PlaybackSessionId session_id, uint64_t now_ms); + + PlaybackSessionId TryComplete(); + PlaybackSessionId Cancel(PlaybackSessionId session_id); + PlaybackSessionId Fail(PlaybackSessionId session_id); + PlaybackTimeoutResult CheckTimeout( + uint64_t now_ms, + uint32_t producer_start_timeout_ms, + uint32_t stalled_timeout_ms); + + void RecordStaleFrame(); + bool IsCurrent(PlaybackSessionId session_id) const; + const PlaybackSessionSnapshot& snapshot() const { return session_; } + const PlaybackMetrics& metrics() const { return metrics_; } + +private: + PlaybackSessionId AllocateSessionId(PlaybackSessionId requested_id); + void Touch(uint64_t now_ms); + + PlaybackSessionSnapshot session_{}; + PlaybackMetrics metrics_{}; + PlaybackSessionId next_session_id_ = 0x80000000U; + uint32_t next_generation_ = 1; + uint64_t started_at_ms_ = 0; + uint64_t last_progress_ms_ = 0; +}; + +const char* ToString(PlaybackSessionState state); +const char* ToString(PlaybackStartStatus status); +const char* ToString(PlaybackTimeoutReason reason); + +} // namespace borla diff --git a/main/audio/playback_pipeline.cc b/main/audio/playback_pipeline.cc new file mode 100644 index 0000000..aac02ff --- /dev/null +++ b/main/audio/playback_pipeline.cc @@ -0,0 +1,660 @@ +#include "audio/playback_pipeline.h" + +#include "core/task_stack_budget.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "PlaybackPipeline2"; +constexpr uint32_t kProducerStartTimeoutMs = 2000; +constexpr uint32_t kStalledTimeoutMs = 10000; +// How long a late frame may be held waiting for a companion after the ready +// queue ran dry. Playout health showed why: the server re-anchors its rate +// control after a TTS generation stall and never refills the burst cushion, +// so a starved stretch played as a run of 60-80 ms micro-gaps (16 in one +// session). Holding once converts that into a single short pause followed by +// smooth playout. Draining sessions never hold — every frame is already +// queued once EndInput has been seen. +constexpr uint32_t kDryRebuildHoldMs = 150; +// Fixed hold before the FIRST write of a remote TTS session. The server runs +// 6 frames (360 ms) ahead and never refills after a generation stall (it +// re-anchors instead), so the cushion only ever shrinks over a reply. +// Delaying playout start grows the server's effective lead by exactly the +// hold: 360 + 180 = 540 ms of stall budget, which absorbs typical +// inter-sentence TTS generation gaps that were audible as mid-reply breaks. +// Local prompts are exempt — they are fully buffered and latency-sensitive. +constexpr uint32_t kStartupPrebufferMs = 180; + +} // namespace + +PlaybackPipeline::PlaybackPipeline(IAudioOutput& output) + : output_(output) +{ +} + +PlaybackPipeline::~PlaybackPipeline() +{ + Stop(); + if (frame_pool_ != nullptr) { + heap_caps_free(frame_pool_); + } + if (decode_buffer_ != nullptr) { + heap_caps_free(decode_buffer_); + } + if (reference_buffer_ != nullptr) { + heap_caps_free(reference_buffer_); + } +} + +void PlaybackPipeline::SetEventPublisher(IEventPublisher* publisher) +{ + publisher_.store(publisher, std::memory_order_release); +} + +bool PlaybackPipeline::Initialize() +{ + if (initialized_) { + return true; + } + if (output_.SampleRate() != kSampleRate) { + ESP_LOGE(kTag, "output rate=%lu does not match pipeline rate=%lu", + static_cast(output_.SampleRate()), + static_cast(kSampleRate)); + return false; + } + if (!decoder_.Initialize(kSampleRate, 1)) { + return false; + } + if (stopped_signal_ == nullptr) { + stopped_signal_ + = xSemaphoreCreateBinaryStatic(&stopped_signal_storage_); + if (stopped_signal_ == nullptr) { + ESP_LOGE(kTag, "task stop signal creation failed"); + return false; + } + } + + if (frame_pool_ == nullptr) { + frame_pool_ = static_cast(heap_caps_calloc(kFramePoolSize, + sizeof(FrameSlot), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (decode_buffer_ == nullptr) { + decode_buffer_ + = static_cast(heap_caps_calloc(kSamplesPerFrame, + sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (reference_buffer_ == nullptr) { + reference_buffer_ + = static_cast(heap_caps_calloc(kSamplesPerFrame, + sizeof(int16_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (frame_pool_ == nullptr || decode_buffer_ == nullptr || + reference_buffer_ == nullptr) { + ESP_LOGE(kTag, + "PSRAM allocation failed pool=%p decode=%p reference=%p", + frame_pool_, decode_buffer_, reference_buffer_); + return false; + } + for (size_t index = 0; index < kFramePoolSize; ++index) { + new (&frame_pool_[index]) FrameSlot(); + } + + free_slots_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t), + free_slots_queue_bytes_, &free_slots_storage_); + ready_frames_ = xQueueCreateStatic(kFramePoolSize, sizeof(uint16_t), + ready_frames_queue_bytes_, &ready_frames_storage_); + if (free_slots_ == nullptr || ready_frames_ == nullptr) { + ESP_LOGE(kTag, "static queue creation failed"); + return false; + } + + for (uint16_t index = 0; index < kFramePoolSize; ++index) { + if (xQueueSend(free_slots_, &index, 0) != pdTRUE) { + ESP_LOGE(kTag, "failed to seed frame slot=%u", index); + return false; + } + } + + initialized_ = true; + ESP_LOGI(kTag, "initialized frames=%u slot_bytes=%u PSRAM=%u bytes", + static_cast(kFramePoolSize), + static_cast(sizeof(FrameSlot)), + static_cast(kFramePoolSize * sizeof(FrameSlot) + + 2 * kSamplesPerFrame * sizeof(int16_t))); + return true; +} + +bool PlaybackPipeline::Start() +{ + if (running_.load(std::memory_order_acquire)) { + return true; + } + if (!initialized_ && !Initialize()) { + return false; + } + + xSemaphoreTake(stopped_signal_, 0); + running_.store(true, std::memory_order_release); + const BaseType_t result + = xTaskCreatePinnedToCoreWithCaps(&PlaybackPipeline::TaskEntry, + "playback", task_stack_budget::kPlaybackBytes, this, + task_priority::kPlaybackLoop, &task_, 1, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (result != pdPASS) { + running_.store(false, std::memory_order_release); + task_ = nullptr; + ESP_LOGE(kTag, "failed to create playback task"); + return false; + } + ESP_LOGI(kTag, "task started stack_bytes=%u memory=PSRAM", + static_cast(task_stack_budget::kPlaybackBytes)); + return true; +} + +void PlaybackPipeline::Stop() +{ + paused_.store(false, std::memory_order_release); + if (!running_.exchange(false, std::memory_order_acq_rel)) { + return; + } + if (task_ != nullptr) { + if (xSemaphoreTake(stopped_signal_, pdMS_TO_TICKS(1500)) != pdTRUE) { + ESP_LOGE(kTag, "speaker-owner task stop timed out"); + } + vTaskDeleteWithCaps(task_); + task_ = nullptr; + } + + std::lock_guard lock(mutex_); + controller_.Cancel(0); + DrainReadyQueueLocked(); + decoder_.Reset(); +} + +PlaybackStartResult PlaybackPipeline::StartSession(PlaybackSource source, + PlaybackPriority priority, PlaybackSessionId requested_id) +{ + if (!running_.load(std::memory_order_acquire)) { + return {}; + } + + PlaybackStartResult result; + { + std::lock_guard lock(mutex_); + result + = controller_.StartSession(source, priority, requested_id, NowMs()); + if (result.status == PlaybackStartStatus::kStarted) { + paused_.store(false, std::memory_order_release); + backpressure_logged_session_.store( + 0, std::memory_order_release); + DrainReadyQueueLocked(); + // The decoder is reset by the playback task itself, right before + // the next Decode: this path runs on the application task while + // Run() may be inside Decode() — which happens OUTSIDE mutex_ — + // and libopus state is not reentrant. The flag is honoured before + // the new session's first frame, which is all the reset is for. + decoder_reset_pending_.store( + true, std::memory_order_release); + // Drop any reference frames stranded from the previous session so + // the AEC starts this one in phase with the speaker. + IPlaybackReferenceSink* reference_sink + = reference_sink_.load(std::memory_order_acquire); + if (reference_sink != nullptr) { + reference_sink->ResetPlaybackReference(); + } + ESP_LOGI(kTag, + "session start id=%lu generation=%lu source=%s " + "priority=%s preempted=%lu", + static_cast(result.session_id), + static_cast(result.generation), ToString(source), + ToString(priority), + static_cast(result.preempted_session_id)); + } else { + ESP_LOGW(kTag, + "session request status=%s requested=%lu source=%s " + "priority=%s", + ToString(result.status), + static_cast(requested_id), ToString(source), + ToString(priority)); + } + } + if (result.preempted_session_id != 0) { + PublishPlaybackEvent(AppEventType::kPlaybackPreempted, + result.preempted_session_id, result.session_id); + } + return result; +} + +bool PlaybackPipeline::SubmitOpus( + PlaybackSessionId session_id, const uint8_t* data, size_t size) +{ + if (data == nullptr || size == 0 || size > kMaxOpusBytes) { + ESP_LOGW( + kTag, "invalid Opus frame size=%u", static_cast(size)); + return false; + } + return SubmitFrame(session_id, FrameFormat::kOpus, data, size, 0); +} + +bool PlaybackPipeline::SubmitPcm( + PlaybackSessionId session_id, const int16_t* samples, size_t sample_count) +{ + if (samples == nullptr || sample_count == 0 + || sample_count > kSamplesPerFrame) { + return false; + } + return SubmitFrame(session_id, FrameFormat::kPcm, samples, + sample_count * sizeof(int16_t), sample_count); +} + +bool PlaybackPipeline::EndInput(PlaybackSessionId session_id) +{ + PlaybackSessionId completed = 0; + { + std::lock_guard lock(mutex_); + if (!controller_.EndInput(session_id, NowMs())) { + return false; + } + completed = controller_.TryComplete(); + } + + if (completed != 0) { + PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed); + } + return true; +} + +bool PlaybackPipeline::Cancel(PlaybackSessionId session_id) +{ + paused_.store(false, std::memory_order_release); + std::lock_guard lock(mutex_); + const PlaybackSessionId cancelled = controller_.Cancel(session_id); + if (cancelled == 0) { + return false; + } + DrainReadyQueueLocked(); + // Same reentrancy rule as StartSession: Decode() runs outside mutex_ on + // the playback task, so the reset must happen there, not here. + decoder_reset_pending_.store(true, std::memory_order_release); + ESP_LOGI(kTag, "session cancelled id=%lu", + static_cast(cancelled)); + return true; +} + +void PlaybackPipeline::SetPaused(bool paused) +{ + const bool previous = paused_.exchange( + paused, std::memory_order_acq_rel); + if (previous != paused) { + ESP_LOGI(kTag, "playback %s for barge-in candidate", + paused ? "paused" : "resumed"); + } +} + +PlaybackSessionSnapshot PlaybackPipeline::Snapshot() const +{ + std::lock_guard lock(mutex_); + return controller_.snapshot(); +} + +PlaybackMetrics PlaybackPipeline::Metrics() const +{ + std::lock_guard lock(mutex_); + return controller_.metrics(); +} + +void PlaybackPipeline::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void PlaybackPipeline::Run() +{ + ESP_LOGI(kTag, "speaker-owner task started"); + while (running_.load(std::memory_order_acquire)) { + uint16_t slot_index = 0; + if (xQueueReceive(ready_frames_, &slot_index, pdMS_TO_TICKS(20)) + != pdTRUE) { + CheckTimeout(); + continue; + } + if (slot_index >= kFramePoolSize) { + ESP_LOGE(kTag, "invalid frame slot=%u", slot_index); + continue; + } + const uint32_t ready_depth = static_cast( + uxQueueMessagesWaiting(ready_frames_)); + + // Candidate barge-in is reversible. Keep the dequeued head frame and + // every queued frame intact until the server confirms or rejects the + // ASR result. A frame already inside synchronous I2S Write() may finish, + // so pause latency is bounded by one 60 ms frame. + if (paused_.load(std::memory_order_acquire)) { + // A deliberate hold is not starvation; skip the next gap sample. + health_skip_gap_ = true; + } + while (running_.load(std::memory_order_acquire) && + paused_.load(std::memory_order_acquire)) { + vTaskDelay(pdMS_TO_TICKS(10)); + } + if (!running_.load(std::memory_order_acquire)) { + ReleaseSlot(slot_index); + break; + } + + FrameSlot& slot = frame_pool_[slot_index]; + + if (slot.session_id != health_session_) { + // First frame of a new session: see kStartupPrebufferMs. + bool prebuffer = false; + { + std::lock_guard lock(mutex_); + prebuffer = controller_.IsCurrent(slot.session_id) && + controller_.snapshot().source == + PlaybackSource::kRemoteTts; + } + if (prebuffer) { + const uint64_t deadline_us = + static_cast(esp_timer_get_time()) + + kStartupPrebufferMs * 1000ULL; + bool still_current = true; + while (still_current && + running_.load(std::memory_order_acquire) && + !paused_.load(std::memory_order_acquire) && + static_cast(esp_timer_get_time()) < + deadline_us) { + vTaskDelay(pdMS_TO_TICKS(10)); + std::lock_guard lock(mutex_); + still_current = + controller_.IsCurrent(slot.session_id); + } + } + } else if (last_write_end_us_ != 0 && + static_cast(esp_timer_get_time()) - + last_write_end_us_ > + kFrameDurationMs * 1000ULL) { + // De-jitter rebuild: reaching this frame more than one period + // after the previous write finished means the queue ran dry and + // the DMA is draining right now. Hold briefly for a companion + // frame so the dry spell plays as one pause instead of a + // micro-gap per frame. Also covers the post-candidate resume, + // which restarts with zero cushion. + bool input_ended = false; + { + std::lock_guard lock(mutex_); + input_ended = !controller_.IsCurrent(slot.session_id) || + controller_.snapshot().input_ended; + } + const uint64_t hold_deadline_us = + static_cast(esp_timer_get_time()) + + kDryRebuildHoldMs * 1000ULL; + while (!input_ended && + running_.load(std::memory_order_acquire) && + !paused_.load(std::memory_order_acquire) && + uxQueueMessagesWaiting(ready_frames_) == 0 && + static_cast(esp_timer_get_time()) < + hold_deadline_us) { + vTaskDelay(pdMS_TO_TICKS(10)); + std::lock_guard lock(mutex_); + input_ended = controller_.snapshot().input_ended; + } + } + + bool process = false; + { + std::lock_guard lock(mutex_); + process = controller_.BeginFrame(slot.session_id, NowMs()); + if (!process) { + controller_.RecordStaleFrame(); + } + } + if (!process) { + ReleaseSlot(slot_index); + continue; + } + + size_t decoded_samples = 0; + bool decoded = false; + if (slot.format == FrameFormat::kOpus) { + if (decoder_reset_pending_.exchange( + false, std::memory_order_acq_rel)) { + decoder_.Reset(); + } + decoded = decoder_.Decode(slot.payload, slot.payload_size, + decode_buffer_, kSamplesPerFrame, &decoded_samples); + } else { + decoded_samples = slot.sample_count; + std::memcpy(decode_buffer_, slot.payload, + decoded_samples * sizeof(int16_t)); + decoded = true; + } + + PlaybackSessionId completed = 0; + PlaybackSessionId failed = 0; + { + std::lock_guard lock(mutex_); + if (!controller_.IsCurrent(slot.session_id)) { + controller_.RecordStaleFrame(); + } else if (!decoded) { + failed = controller_.Fail(slot.session_id); + DrainReadyQueueLocked(); + } else { + // Hold the ownership lock across the synchronous I2S write. + // A preemption waits at most one 60 ms frame, and after it + // returns no frame from the old session can reach the PA. + IPlaybackReferenceSink* reference_sink + = reference_sink_.load(std::memory_order_acquire); + if (reference_sink != nullptr) { + // Mirror the software volume applied inside Write(). AEC + // must receive the PCM amplitude that reaches the DAC, + // not the unscaled decoder output. + const int32_t gain = + static_cast(output_.VolumePercent()) * + 256 / 100; + for (size_t index = 0; + index < decoded_samples; + ++index) { + const int32_t scaled = + (static_cast(decode_buffer_[index]) * + gain) >> 8; + reference_buffer_[index] = + static_cast(std::clamp( + scaled, -32768, 32767)); + } + reference_sink->OnPlaybackReference( + reference_buffer_, decoded_samples); + } + if (slot.session_id != health_session_) { + FlushPlayoutHealth(); + health_session_ = slot.session_id; + health_skip_gap_ = true; + health_depth_min_ = ready_depth; + health_depth_max_ = ready_depth; + } + const uint64_t write_start_us = + static_cast(esp_timer_get_time()); + if (!health_skip_gap_ && last_write_end_us_ != 0) { + const uint32_t gap_ms = static_cast( + (write_start_us - last_write_end_us_) / 1000ULL); + health_max_gap_ms_ = + std::max(health_max_gap_ms_, gap_ms); + if (gap_ms > kFrameDurationMs) { + health_gap_over_frame_++; + } + if (gap_ms > 90) { + health_gap_over_dma_++; + } + } + health_skip_gap_ = false; + health_frames_++; + health_depth_min_ = + std::min(health_depth_min_, ready_depth); + health_depth_max_ = + std::max(health_depth_max_, ready_depth); + const bool written + = output_.Write(decode_buffer_, decoded_samples); + last_write_end_us_ = + static_cast(esp_timer_get_time()); + controller_.FinishFrame(slot.session_id, written, NowMs()); + if (!written) { + failed = controller_.Fail(slot.session_id); + DrainReadyQueueLocked(); + } else { + completed = controller_.TryComplete(); + } + } + } + + ReleaseSlot(slot_index); + if (failed != 0 || completed != 0) { + FlushPlayoutHealth(); + } + if (failed != 0) { + PublishPlaybackEvent(AppEventType::kPlaybackFailed, failed); + } else if (completed != 0) { + PublishPlaybackEvent(AppEventType::kPlaybackDrained, completed); + } + } + FlushPlayoutHealth(); + xSemaphoreGive(stopped_signal_); + for (;;) { + vTaskSuspend(nullptr); + } +} + +void PlaybackPipeline::FlushPlayoutHealth() +{ + if (health_frames_ > 1) { + // One line per session. gaps>frame means the queue ran dry longer + // than one frame period (cushion gone); gaps>dma means the 90 ms + // I2S buffer also drained and the break reached the speaker. + ESP_LOGI(kTag, + "playout health id=%lu frames=%lu max_gap=%lums " + "gaps>frame=%lu gaps>dma=%lu depth=%lu..%lu", + static_cast(health_session_), + static_cast(health_frames_), + static_cast(health_max_gap_ms_), + static_cast(health_gap_over_frame_), + static_cast(health_gap_over_dma_), + static_cast(health_depth_min_), + static_cast(health_depth_max_)); + } + health_session_ = 0; + health_frames_ = 0; + health_max_gap_ms_ = 0; + health_gap_over_frame_ = 0; + health_gap_over_dma_ = 0; + health_depth_min_ = 0; + health_depth_max_ = 0; + last_write_end_us_ = 0; + health_skip_gap_ = false; +} + +bool PlaybackPipeline::SubmitFrame(PlaybackSessionId session_id, + FrameFormat format, const void* data, size_t byte_count, + size_t sample_count) +{ + if (!running_.load(std::memory_order_acquire) || data == nullptr + || byte_count > kMaxFrameBytes) { + return false; + } + + uint16_t slot_index = 0; + if (xQueueReceive(free_slots_, &slot_index, 0) != pdTRUE) { + const PlaybackSessionId already_logged + = backpressure_logged_session_.exchange( + session_id, std::memory_order_acq_rel); + if (already_logged != session_id) { + ESP_LOGD(kTag, + "producer pacing session=%lu; frame pool temporarily full", + static_cast(session_id)); + } + return false; + } + + FrameSlot& slot = frame_pool_[slot_index]; + slot.session_id = session_id; + slot.format = format; + slot.payload_size = static_cast(byte_count); + slot.sample_count = static_cast(sample_count); + std::memcpy(slot.payload, data, byte_count); + + { + std::lock_guard lock(mutex_); + if (!controller_.QueueFrame(session_id, NowMs())) { + controller_.RecordStaleFrame(); + ReleaseSlot(slot_index); + return false; + } + if (xQueueSend(ready_frames_, &slot_index, 0) != pdTRUE) { + controller_.RollbackQueuedFrame(session_id); + ReleaseSlot(slot_index); + ESP_LOGE(kTag, "ready queue unexpectedly full"); + return false; + } + } + return true; +} + +void PlaybackPipeline::DrainReadyQueueLocked() +{ + uint16_t slot_index = 0; + while (xQueueReceive(ready_frames_, &slot_index, 0) == pdTRUE) { + ReleaseSlot(slot_index); + } +} + +void PlaybackPipeline::ReleaseSlot(uint16_t slot_index) +{ + if (xQueueSend(free_slots_, &slot_index, 0) != pdTRUE) { + ESP_LOGE(kTag, "failed to release frame slot=%u", slot_index); + } +} + +void PlaybackPipeline::CheckTimeout() +{ + PlaybackTimeoutResult timeout; + { + std::lock_guard lock(mutex_); + timeout = controller_.CheckTimeout( + NowMs(), kProducerStartTimeoutMs, kStalledTimeoutMs); + if (timeout.session_id != 0) { + DrainReadyQueueLocked(); + decoder_.Reset(); + } + } + if (timeout.session_id != 0) { + ESP_LOGE(kTag, "session timeout id=%lu reason=%s", + static_cast(timeout.session_id), + ToString(timeout.reason)); + PublishPlaybackEvent(AppEventType::kPlaybackFailed, timeout.session_id); + } +} + +void PlaybackPipeline::PublishPlaybackEvent(AppEventType type, + PlaybackSessionId session_id, PlaybackSessionId replacement_session_id) +{ + IEventPublisher* publisher = publisher_.load(std::memory_order_acquire); + if (publisher == nullptr + || !publisher->Publish( + AppEvent::Make(type, session_id, 0, replacement_session_id))) { + ESP_LOGE(kTag, "failed to publish playback event=%s session=%lu", + ToString(type), static_cast(session_id)); + } +} + +uint64_t PlaybackPipeline::NowMs() +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace borla diff --git a/main/audio/playback_pipeline.h b/main/audio/playback_pipeline.h new file mode 100644 index 0000000..95c2dfe --- /dev/null +++ b/main/audio/playback_pipeline.h @@ -0,0 +1,151 @@ +#pragma once + +#include "audio/audio_output.h" +#include "audio/opus_frame_decoder.h" +#include "audio/playback_controller.h" +#include "audio/voice_frame_processor.h" +#include "ports/event_publisher.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace borla { + +class PlaybackPipeline final { +public: + static constexpr uint32_t kSampleRate = 48000;//24000; + static constexpr uint32_t kFrameDurationMs = 60; + static constexpr size_t kSamplesPerFrame = + kSampleRate * kFrameDurationMs / 1000; + static constexpr size_t kMaxFrameBytes = + kSamplesPerFrame * sizeof(int16_t); + static constexpr size_t kMaxOpusBytes = 1536; + static constexpr size_t kFramePoolSize = 48; + + explicit PlaybackPipeline(IAudioOutput& output); + ~PlaybackPipeline(); + + void SetEventPublisher(IEventPublisher* publisher); + // True while a session still owns the speaker. Used to hold off a reboot + // until the prompt that explains the reboot has actually been heard. + bool Active() const + { + std::lock_guard lock(mutex_); + return controller_.snapshot().active; + } + + void SetReferenceSink(IPlaybackReferenceSink* sink) + { + reference_sink_.store(sink); + } + bool Initialize(); + bool Start(); + void Stop(); + + PlaybackStartResult StartSession( + PlaybackSource source, + PlaybackPriority priority, + PlaybackSessionId requested_id = 0); + bool SubmitOpus( + PlaybackSessionId session_id, + const uint8_t* data, + size_t size); + bool SubmitPcm( + PlaybackSessionId session_id, + const int16_t* samples, + size_t sample_count); + bool EndInput(PlaybackSessionId session_id); + void SetPaused(bool paused); + bool Cancel(PlaybackSessionId session_id = 0); + + PlaybackSessionSnapshot Snapshot() const; + PlaybackMetrics Metrics() const; + +private: + enum class FrameFormat : uint8_t { + kOpus, + kPcm, + }; + + struct FrameSlot { + PlaybackSessionId session_id = 0; + FrameFormat format = FrameFormat::kOpus; + uint16_t payload_size = 0; + uint16_t sample_count = 0; + alignas(int16_t) uint8_t payload[kMaxFrameBytes]{}; + }; + + static void TaskEntry(void* context); + + void Run(); + void FlushPlayoutHealth(); + bool SubmitFrame( + PlaybackSessionId session_id, + FrameFormat format, + const void* data, + size_t byte_count, + size_t sample_count); + void DrainReadyQueueLocked(); + void ReleaseSlot(uint16_t slot_index); + void CheckTimeout(); + void PublishPlaybackEvent( + AppEventType type, + PlaybackSessionId session_id, + PlaybackSessionId replacement_session_id = 0); + static uint64_t NowMs(); + + IAudioOutput& output_; + std::atomic publisher_{nullptr}; + std::atomic reference_sink_{nullptr}; + OpusFrameDecoder decoder_; + mutable std::mutex mutex_; + PlaybackController controller_; + + FrameSlot* frame_pool_ = nullptr; + int16_t* decode_buffer_ = nullptr; + int16_t* reference_buffer_ = nullptr; + QueueHandle_t free_slots_ = nullptr; + QueueHandle_t ready_frames_ = nullptr; + StaticQueue_t free_slots_storage_{}; + StaticQueue_t ready_frames_storage_{}; + uint8_t free_slots_queue_bytes_[kFramePoolSize * sizeof(uint16_t)]{}; + uint8_t ready_frames_queue_bytes_[kFramePoolSize * sizeof(uint16_t)]{}; + SemaphoreHandle_t stopped_signal_ = nullptr; + StaticSemaphore_t stopped_signal_storage_{}; + + TaskHandle_t task_ = nullptr; + bool initialized_ = false; + std::atomic running_{false}; + std::atomic paused_{false}; + // Playout health accounting, owned exclusively by the speaker task. + // The server paces frames in real time after a 6-frame (360 ms) burst, + // so the whole jitter cushion is that burst plus the 90 ms I2S DMA. + // These counters turn "偶发卡顿" into one measurable line per session: + // an inter-write gap > 60 ms means the cushion fully eroded, > 90 ms + // means the DMA drained and the break was audible. + PlaybackSessionId health_session_ = 0; + uint64_t last_write_end_us_ = 0; + bool health_skip_gap_ = false; + uint32_t health_frames_ = 0; + uint32_t health_gap_over_frame_ = 0; + uint32_t health_gap_over_dma_ = 0; + uint32_t health_max_gap_ms_ = 0; + uint32_t health_depth_min_ = 0; + uint32_t health_depth_max_ = 0; + + // Set by StartSession/Cancel (application task); consumed by Run() right + // before Decode(), the only place allowed to touch decoder_ while the + // playback task lives. Decode() runs outside mutex_, so a direct Reset() + // from another task would race it. + std::atomic decoder_reset_pending_{false}; + std::atomic backpressure_logged_session_{0}; +}; + +} // namespace borla diff --git a/main/audio/voice_activity_detector.cc b/main/audio/voice_activity_detector.cc new file mode 100644 index 0000000..91ff80e --- /dev/null +++ b/main/audio/voice_activity_detector.cc @@ -0,0 +1,68 @@ +#include "audio/voice_activity_detector.h" + +#include + +namespace borla { + +VoiceActivityDetector::VoiceActivityDetector( + VoiceActivityConfig config) + : config_(config) +{ + if (config_.start_frames == 0) { + config_.start_frames = 1; + } + if (config_.stop_frames == 0) { + config_.stop_frames = 1; + } +} + +VoiceActivityResult VoiceActivityDetector::Process( + const int16_t* samples, + size_t sample_count) +{ + if (samples == nullptr || sample_count == 0) { + return VoiceActivityResult::kSilence; + } + uint64_t energy = 0; + for (size_t index = 0; index < sample_count; ++index) { + const int32_t sample = samples[index]; + energy += static_cast(sample * sample); + } + last_rms_ = static_cast( + std::sqrt( + static_cast(energy) / + static_cast(sample_count))); + const bool loud = last_rms_ >= config_.rms_threshold; + + if (!speech_active_) { + quiet_frames_ = 0; + loud_frames_ = loud ? static_cast(loud_frames_ + 1) : 0; + if (loud_frames_ >= config_.start_frames) { + speech_active_ = true; + loud_frames_ = 0; + return VoiceActivityResult::kSpeechStarted; + } + return VoiceActivityResult::kSilence; + } + + if (loud) { + quiet_frames_ = 0; + return VoiceActivityResult::kSpeech; + } + if (++quiet_frames_ >= config_.stop_frames) { + speech_active_ = false; + quiet_frames_ = 0; + return VoiceActivityResult::kSpeechEnded; + } + return VoiceActivityResult::kSpeech; +} + +void VoiceActivityDetector::Reset() +{ + loud_frames_ = 0; + quiet_frames_ = 0; + speech_active_ = false; + last_rms_ = 0; +} + +} // namespace borla diff --git a/main/audio/voice_activity_detector.h b/main/audio/voice_activity_detector.h new file mode 100644 index 0000000..4c2b731 --- /dev/null +++ b/main/audio/voice_activity_detector.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +namespace borla { + +enum class VoiceActivityResult : uint8_t { + kSilence, + kSpeechStarted, + kSpeech, + kSpeechEnded, +}; + +struct VoiceActivityConfig { + uint16_t rms_threshold = 650; + uint8_t start_frames = 2; + uint8_t stop_frames = 13; +}; + +class VoiceActivityDetector final { +public: + explicit VoiceActivityDetector( + VoiceActivityConfig config = {}); + + VoiceActivityResult Process( + const int16_t* samples, + size_t sample_count); + void Reset(); + bool speech_active() const { return speech_active_; } + uint32_t LastRms() const { return last_rms_; } + +private: + VoiceActivityConfig config_; + uint8_t loud_frames_ = 0; + uint8_t quiet_frames_ = 0; + bool speech_active_ = false; + uint32_t last_rms_ = 0; +}; + +} // namespace borla diff --git a/main/audio/voice_dsp.cc b/main/audio/voice_dsp.cc new file mode 100644 index 0000000..07a8b77 --- /dev/null +++ b/main/audio/voice_dsp.cc @@ -0,0 +1,403 @@ +#include "audio/voice_dsp.h" + +#include +#include + +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "VoiceDsp2"; +constexpr float kTargetPeak = 0.42f; +constexpr float kMinimumGain = 0.8f; +constexpr float kMaximumGain = 4.0f; +constexpr float kBargeInMaximumGain = 1.8f; +constexpr float kNoiseGateAttenuation = 0.1f; +constexpr float kBargeInNoiseGateAttenuation = 0.05f; + +// esp-sr allocates its AEC and NS state with plain malloc, and this build +// routes allocations larger than 16 KB to PSRAM. An earlier revision forced +// them into internal SRAM on the theory that the adaptive filter running over +// the PSRAM bus explained the AEC's per-frame cost. Field measurement killed +// that theory twice over: with the states internal the AEC still cost ~50 ms +// per 60 ms frame (placement was worth at most a few ms), and the ~50 KB of +// internal RAM they consumed starved lwIP (free=4415 min=531) until a TLS +// send failed mid-conversation and dropped the WebSocket. PSRAM placement is +// therefore the correct trade; the probes below keep reporting where the +// states actually land so the question stays answered. + +} // namespace + +VoiceDsp::~VoiceDsp() +{ + DisableEchoCancellation(); + if (ns_ != nullptr) { + ns_destroy(ns_); + } +} + +bool VoiceDsp::InitializeNoiseSuppression() +{ + if (ns_ != nullptr) { + return true; + } + const size_t internal_before = + heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + ns_ = ns_pro_create(10, 2, 16000); + if (ns_ == nullptr) { + ESP_LOGE(kTag, "NS initialization failed"); + return false; + } + ESP_LOGI(kTag, "NS state internal=%d bytes", + static_cast( + internal_before - + heap_caps_get_free_size(MALLOC_CAP_INTERNAL))); + return true; +} + +bool VoiceDsp::EnableEchoCancellation(bool barge_in_profile) +{ + if (aec_ != nullptr) { + // Both profiles use identical aec_create parameters — the flag only + // selects post-processing (NS off + conservative AGC for barge-in). + // Never tear the state down for a profile flip: aec_create grabs + // whatever internal RAM is free at that instant and keeps it for the + // rest of the session, so a mid-session re-create once confiscated + // the websocket's reconnect budget the moment it was released + // (internal free pinned at 75 bytes, every TLS attempt failing). + if (barge_in_profile_ != barge_in_profile) { + barge_in_profile_ = barge_in_profile; + Reset(); + } + return true; + } + // FD_LOW_COST left speech-shaped TTS residue at RMS 4k-12k on this + // board. VOIP_HIGH_PERF/filter=4 is the field-proven ESP32-S3 setup for + // both barge-in and calls. The profile flag selects conservative + // post-processing for barge-in; it no longer selects a weaker AEC. + const aec_mode_t mode = AEC_MODE_VOIP_HIGH_PERF; + const int filter_length = 4; + // The deltas logged below say where the state actually landed — see the + // note above InitializeNoiseSuppression for why PSRAM is the intended + // answer. + const size_t internal_before = + heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + const size_t psram_before = + heap_caps_get_free_size(MALLOC_CAP_SPIRAM); + aec_ = aec_create(16000, filter_length, 1, mode); + ESP_LOGI(kTag, + "AEC state allocated internal=%d psram=%d (bytes)", + static_cast( + internal_before - + heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + psram_before - + heap_caps_get_free_size(MALLOC_CAP_SPIRAM))); + if (aec_ == nullptr) { + ESP_LOGE(kTag, "AEC initialization failed"); + return false; + } + aec_chunk_samples_ = aec_get_chunksize(aec_); + if (aec_chunk_samples_ <= 0 || + aec_chunk_samples_ > + static_cast(kMaximumAecChunk)) { + ESP_LOGE(kTag, "unsupported AEC chunk=%d", + aec_chunk_samples_); + DisableEchoCancellation(); + return false; + } + barge_in_profile_ = barge_in_profile; + Reset(); + ESP_LOGI(kTag, "AEC enabled mode=%s chunk=%d filter=%d profile=%s", + aec_get_mode_string(mode), + aec_chunk_samples_, + filter_length, + barge_in_profile ? "barge_in" : "call"); + return true; +} + +bool VoiceDsp::PrewarmEchoCancellation() +{ + if (aec_ != nullptr) { + return true; + } + // aec_create is opportunistic: it takes whatever internal RAM is free at + // that instant (observed 2.6-12.4 KB across boots) and the handle then + // lives for the whole session. Created lazily at the first TTS it once + // grabbed 12 KB exactly as the dropped websocket released its buffers — + // after that no TLS reconnect could ever allocate again. Placement is + // speed-neutral on this board (~50 ms/frame measured both ways), so the + // state belongs in PSRAM: create it ONCE at boot, before the WiFi driver + // exists, with guard blocks squatting on internal RAM so esp-sr's greedy + // pass lands in PSRAM, then release the guards. + // Guard blocks sized to the CURRENT largest free block, not a fixed + // size: the boot heap is a handful of region tails and DMA-pool chunks, + // and a fixed-8KB loop bailed on the first sub-8KB fragment while + // esp-sr's many small allocations then filled 24.9 KB of exactly those + // fragments — leaving the WiFi driver so dry that phy_track_pll_init's + // esp_timer_create aborted the boot. + constexpr uint32_t kGuardCaps = MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT; + constexpr size_t kInternalFloorBytes = 8 * 1024; + constexpr size_t kMinimumGuardBytes = 1024; + constexpr size_t kGuardHeadroomBytes = 256; + std::array guards{}; + size_t guard_count = 0; + size_t guarded_bytes = 0; + while (guard_count < guards.size() && + heap_caps_get_free_size(kGuardCaps) > kInternalFloorBytes) { + const size_t largest = + heap_caps_get_largest_free_block(kGuardCaps); + if (largest < kMinimumGuardBytes) { + break; + } + const size_t take = largest - kGuardHeadroomBytes; + void* block = heap_caps_malloc(take, kGuardCaps); + if (block == nullptr) { + break; + } + guards[guard_count++] = block; + guarded_bytes += take; + } + ESP_LOGI(kTag, + "AEC prewarm guards=%u held=%u free=%u largest=%u", + static_cast(guard_count), + static_cast(guarded_bytes), + static_cast(heap_caps_get_free_size(kGuardCaps)), + static_cast( + heap_caps_get_largest_free_block(kGuardCaps))); + const bool enabled = EnableEchoCancellation(true); + for (size_t index = 0; index < guard_count; ++index) { + heap_caps_free(guards[index]); + } + if (!enabled) { + ESP_LOGE(kTag, "AEC prewarm failed"); + return false; + } + Reset(); + return true; +} + +void VoiceDsp::SuspendEchoCancellation() +{ + // Keep the adaptive filter warm across TTS turns. Reset() clears only + // frame accumulators and AGC state; the ESP AEC handle retains its learned + // acoustic path. + if (aec_ != nullptr) { + Reset(); + } +} + +void VoiceDsp::DisableEchoCancellation() +{ + if (aec_ != nullptr) { + aec_destroy(aec_); + aec_ = nullptr; + } + aec_chunk_samples_ = 0; + barge_in_profile_ = false; + mic_count_ = 0; + ref_count_ = 0; + clean_count_ = 0; +} + +void VoiceDsp::Reset() +{ + mic_count_ = 0; + ref_count_ = 0; + clean_count_ = 0; + if (aec_chunk_samples_ > 0) { + clean_count_ = static_cast(aec_chunk_samples_); + std::fill_n(clean_acc_.data(), clean_count_, 0); + } + envelope_ = 0.08f; + gain_ = 1.0f; +} + +bool VoiceDsp::Process( + const int16_t* microphone, + const int16_t* reference, + bool echo_cancellation, + int16_t* output, + size_t sample_count, + int16_t* wake_tap) +{ + if (microphone == nullptr || output == nullptr || + sample_count != kFrameSamples) { + return false; + } + bool valid = true; + if (echo_cancellation) { + valid = reference != nullptr && + ProcessAec( + microphone, reference, output, sample_count); + } else { + std::memcpy( + output, + microphone, + sample_count * sizeof(int16_t)); + } + if (!valid) { + return false; + } + if (wake_tap != nullptr) { + std::memcpy( + wake_tap, output, sample_count * sizeof(int16_t)); + } + ProcessNsAndAgc( + output, + sample_count, + echo_cancellation && barge_in_profile_); + return true; +} + +bool VoiceDsp::ProcessAec( + const int16_t* microphone, + const int16_t* reference, + int16_t* output, + size_t sample_count) +{ + if (aec_ == nullptr || + mic_count_ + sample_count > mic_acc_.size() || + ref_count_ + sample_count > ref_acc_.size()) { + return false; + } + std::memcpy( + mic_acc_.data() + mic_count_, + microphone, + sample_count * sizeof(int16_t)); + std::memcpy( + ref_acc_.data() + ref_count_, + reference, + sample_count * sizeof(int16_t)); + mic_count_ += sample_count; + ref_count_ += sample_count; + + const size_t chunk = + static_cast(aec_chunk_samples_); + while (mic_count_ >= chunk && ref_count_ >= chunk) { + if (clean_count_ + chunk > clean_acc_.size()) { + return false; + } + aec_process( + aec_, + mic_acc_.data(), + ref_acc_.data(), + aec_chunk_.data()); + std::memmove( + mic_acc_.data(), + mic_acc_.data() + chunk, + (mic_count_ - chunk) * sizeof(int16_t)); + std::memmove( + ref_acc_.data(), + ref_acc_.data() + chunk, + (ref_count_ - chunk) * sizeof(int16_t)); + mic_count_ -= chunk; + ref_count_ -= chunk; + std::memcpy( + clean_acc_.data() + clean_count_, + aec_chunk_.data(), + chunk * sizeof(int16_t)); + clean_count_ += chunk; + // Hand the core back between chunks. This loop runs 3-4 times per 60 ms + // frame on the capture task at priority 8, and aec_process() never + // blocks, so without this the idle task on this core gets no runtime for + // as long as duplex is active and the task watchdog fires. taskYIELD() + // would not help: the idle task sits at priority 0 and only a blocking + // delay lets it run. The previous firmware carried the same one-tick + // yield in the same position for the same reason. At 1000 Hz a tick is + // 1 ms, so the cost is ~4 ms per frame against a 60 ms budget. + vTaskDelay(1); + } + if (clean_count_ < sample_count) { + return false; + } + std::memcpy( + output, + clean_acc_.data(), + sample_count * sizeof(int16_t)); + std::memmove( + clean_acc_.data(), + clean_acc_.data() + sample_count, + (clean_count_ - sample_count) * sizeof(int16_t)); + clean_count_ -= sample_count; + return true; +} + +void VoiceDsp::ProcessNsAndAgc( + int16_t* samples, + size_t sample_count, + bool barge_in_profile) +{ + // Full NS remains active for normal capture and calls. During TTS it can + // reshape residual echo and costs CPU, so barge-in uses high-performance + // AEC plus the conservative gate/AGC below. + if (ns_ != nullptr && !barge_in_profile) { + for (size_t offset = 0; + offset + kNsFrameSamples <= sample_count; + offset += kNsFrameSamples) { + ns_process( + ns_, samples + offset, ns_frame_.data()); + std::memcpy( + samples + offset, + ns_frame_.data(), + kNsFrameSamples * sizeof(int16_t)); + } + } + ApplyAgc(samples, sample_count, barge_in_profile); +} + +void VoiceDsp::ApplyAgc( + int16_t* samples, + size_t sample_count, + bool barge_in_profile) +{ + int32_t peak = 0; + uint64_t energy = 0; + for (size_t index = 0; index < sample_count; ++index) { + const int32_t value = samples[index]; + peak = std::max(peak, std::abs(value)); + energy += static_cast(value * value); + } + const float peak_normalized = + static_cast(peak) / 32768.0f; + const float rms = std::sqrt( + static_cast(energy) / + static_cast(sample_count)) / 32768.0f; + if (rms < 0.004f && peak_normalized < 0.015f) { + const float attenuation = barge_in_profile + ? kBargeInNoiseGateAttenuation + : kNoiseGateAttenuation; + for (size_t index = 0; index < sample_count; ++index) { + samples[index] = + static_cast(samples[index] * attenuation); + } + return; + } + + const float alpha = + peak_normalized > envelope_ ? 0.45f : 0.12f; + envelope_ += alpha * (peak_normalized - envelope_); + envelope_ = std::max(envelope_, 0.01f); + const float target = std::clamp( + kTargetPeak / envelope_, + kMinimumGain, + barge_in_profile + ? kBargeInMaximumGain + : kMaximumGain); + gain_ += 0.18f * (target - gain_); + for (size_t index = 0; index < sample_count; ++index) { + const float value = std::clamp( + static_cast(samples[index]) * gain_, + -32768.0f, + 32767.0f); + samples[index] = static_cast(value); + } +} + +} // namespace borla diff --git a/main/audio/voice_dsp.h b/main/audio/voice_dsp.h new file mode 100644 index 0000000..887468b --- /dev/null +++ b/main/audio/voice_dsp.h @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace borla { + +class VoiceDsp final { +public: + static constexpr size_t kFrameSamples = 960; + + ~VoiceDsp(); + + bool InitializeNoiseSuppression(); + // Creates the AEC state once at boot (guarded so it lands in PSRAM) and + // leaves it suspended. See the implementation for why lazy creation was + // a session-killer. + bool PrewarmEchoCancellation(); + bool EnableEchoCancellation(bool barge_in_profile); + void SuspendEchoCancellation(); + void DisableEchoCancellation(); + void Reset(); + // wake_tap, when provided, receives the post-AEC pre-NS/AGC samples — + // the signal WakeNet should hear. The AGC pumps during double-talk and a + // gain-chopped phrase defeats the detector. + bool Process( + const int16_t* microphone, + const int16_t* reference, + bool echo_cancellation, + int16_t* output, + size_t sample_count, + int16_t* wake_tap = nullptr); + + // Diagnostics. Cheap accessors so the frame statistics can report what the + // DSP is actually doing rather than what the policy asked for. + bool EchoCancellationActive() const { return aec_ != nullptr; } + bool NoiseSuppressionActive() const { return ns_ != nullptr; } + // NS is deliberately skipped in the barge-in profile; see ProcessNsAndAgc. + bool BargeInProfile() const { return barge_in_profile_; } + int AecChunkSamples() const { return aec_chunk_samples_; } + float AgcGain() const { return gain_; } + float AgcEnvelope() const { return envelope_; } + +private: + static constexpr size_t kAccumulatorCapacity = 4096; + static constexpr size_t kMaximumAecChunk = 1024; + static constexpr size_t kNsFrameSamples = 160; + + bool ProcessAec( + const int16_t* microphone, + const int16_t* reference, + int16_t* output, + size_t sample_count); + void ProcessNsAndAgc( + int16_t* samples, + size_t sample_count, + bool barge_in_profile); + void ApplyAgc( + int16_t* samples, + size_t sample_count, + bool barge_in_profile); + + aec_handle_t* aec_ = nullptr; + ns_handle_t ns_ = nullptr; + int aec_chunk_samples_ = 0; + bool barge_in_profile_ = false; + + std::array mic_acc_{}; + std::array ref_acc_{}; + std::array clean_acc_{}; + std::array aec_chunk_{}; + std::array ns_frame_{}; + size_t mic_count_ = 0; + size_t ref_count_ = 0; + size_t clean_count_ = 0; + float envelope_ = 0.08f; + float gain_ = 1.0f; +}; + +} // namespace borla diff --git a/main/audio/voice_frame_processor.h b/main/audio/voice_frame_processor.h new file mode 100644 index 0000000..9982a9c --- /dev/null +++ b/main/audio/voice_frame_processor.h @@ -0,0 +1,36 @@ +#pragma once + +#include "core/runtime_state.h" + +#include +#include + +namespace borla { + +class IVoiceFrameProcessor { +public: + virtual ~IVoiceFrameProcessor() = default; + virtual void ApplyPolicy(AudioPolicy policy) = 0; + virtual bool Process( + AudioPolicy policy, + const int16_t* input, + size_t sample_count, + int16_t* output, + size_t output_capacity) = 0; +}; + +class IPlaybackReferenceSink { +public: + virtual ~IPlaybackReferenceSink() = default; + virtual void OnPlaybackReference( + const int16_t* samples, + size_t sample_count) = 0; + // Called when a new playback session begins. Frames queued for the + // previous session are acoustically unrelated to what the microphone is + // about to hear, and leaving them in the ring offsets every reference by + // however many were stranded. Emptying it here phase-locks the reference + // stream to the session that is actually about to reach the speaker. + virtual void ResetPlaybackReference() = 0; +}; + +} // namespace borla diff --git a/main/audio/voice_frontend.cc b/main/audio/voice_frontend.cc new file mode 100644 index 0000000..c8dbcac --- /dev/null +++ b/main/audio/voice_frontend.cc @@ -0,0 +1,969 @@ +#include "audio/voice_frontend.h" + +#include "core/task_stack_budget.h" + +#include +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "VoiceFrontend2"; + +} // namespace + +bool VoiceFrontend::Initialize() +{ + std::lock_guard lock(processor_mutex_); + if (initialized_) { + return true; + } + buffers_ = MakePsramObject(); + if (!buffers_) { + ESP_LOGE(kTag, "voice scratch buffer allocation failed"); + return false; + } + if (!dsp_.InitializeNoiseSuppression()) { + buffers_.reset(); + return false; + } + // Boot runs before the WiFi driver exists, so this is the one moment the + // internal heap is rich and unfragmented. Non-fatal: without the prewarm + // the first duplex turn creates the state mid-conversation and steals the + // websocket's reconnect budget. + dsp_.PrewarmEchoCancellation(); + + wake_queue_ = xQueueCreateWithCaps( + kWakeQueueFrames, + kFrameSamples * sizeof(int16_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (wake_queue_ == nullptr) { + ESP_LOGE(kTag, "wake queue allocation failed"); + buffers_.reset(); + return false; + } + const BaseType_t created = xTaskCreatePinnedToCoreWithCaps( + &VoiceFrontend::WakeScanTaskEntry, + "wake_scan2", + kWakeScanStackBytes, + this, + task_priority::kAudioCodec, + &wake_task_, + 1, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (created != pdPASS) { + ESP_LOGE(kTag, "wake scan task creation failed"); + vQueueDeleteWithCaps(wake_queue_); + wake_queue_ = nullptr; + buffers_.reset(); + return false; + } + ESP_LOGI(kTag, + "wake scan task started core=1 stack_bytes=%u queue=%u", + static_cast(kWakeScanStackBytes), + static_cast(kWakeQueueFrames)); + initialized_ = true; + return true; +} + +void VoiceFrontend::WakeScanTaskEntry(void* context) +{ + static_cast(context)->RunWakeScan(); +} + +[[noreturn]] void VoiceFrontend::RunWakeScan() +{ + // PSRAM stack is fine here: WakeNet's weights already live in PSRAM and + // the detect cost is dominated by the model math, not stack traffic. + std::array frame{}; + while (true) { + if (wake_reset_pending_.exchange( + false, std::memory_order_acq_rel)) { + wake_accumulator_count_ = 0; + } + if (xQueueReceive( + wake_queue_, frame.data(), pdMS_TO_TICKS(100)) == + pdTRUE) { + FeedWakeWord(frame.data(), frame.size()); + } + } +} + +void VoiceFrontend::QueueWakeAudio(const int16_t* samples) +{ + if (wake_queue_ == nullptr) { + return; + } + // Zero timeout: the capture task must never block on the scanner. A full + // queue means the scanner is more than 360 ms behind — dropping is the + // only option that keeps the microphone stream (and AEC alignment) alive. + xQueueSend(wake_queue_, samples, 0); +} + +void VoiceFrontend::SetEventPublisher(IEventPublisher* publisher) +{ + publisher_.store(publisher); +} + +bool VoiceFrontend::EnsureWakeWordLoaded() +{ + if (wake_word_.initialized()) { + return true; + } + // esp_srmodel_init() + create() reads the model partition and takes ~110 ms + // on this board. It happens at most once per boot; the previous code ran it + // on every policy change that needed the wake word, i.e. twice per + // conversation turn, while holding processor_mutex_. That stalled the + // capture task for two whole 60 ms frames right as TTS playback started, + // which both blinded the wake word during the exact window a child would + // use it and scrambled the AEC mic/reference phase so the speaker echo + // reached the server uncancelled. The previous firmware kept the model + // resident for the whole uptime and only toggled a flag; so do we. + std::lock_guard lock(wake_mutex_); + return wake_word_.Initialize(); +} + +void VoiceFrontend::ReleaseWakeWord() +{ + std::lock_guard lock(processor_mutex_); + std::lock_guard wake_lock(wake_mutex_); + if (!wake_word_.initialized()) { + return; + } + wake_word_.Deinitialize(); + wake_reset_pending_.store(true, std::memory_order_release); + ESP_LOGI(kTag, "WakeNet released"); +} + +void VoiceFrontend::SetWakeWordEnabled(bool enabled) +{ + std::lock_guard lock(processor_mutex_); + if (wake_word_enabled_ == enabled) { + return; + } + wake_word_enabled_ = enabled; + if (!enabled) { + // Keep the model loaded; only stop feeding it. Destroying it here is + // what made the reload expensive in the first place. + wake_reset_pending_.store(true, std::memory_order_release); + } else if (initialized_ && WakeRequired(policy_) && + !EnsureWakeWordLoaded()) { + ESP_LOGE(kTag, "WakeNet unavailable after remote enable"); + } + ESP_LOGI(kTag, "remote wake word=%d", enabled ? 1 : 0); +} + +void VoiceFrontend::ApplyPolicy(AudioPolicy policy) +{ + bool wake_ready = false; + bool aec_active = false; + bool duplex_window_closed = false; + // The mutex is scoped so the log lines below are written with it released. + // A ~150 character line takes on the order of 10 ms to drain at the console + // baud rate, and the capture task blocks on this same mutex once per 60 ms + // frame; holding it across the write is the same class of stall that the + // per-turn WakeNet reload used to cause. + { + std::lock_guard lock(processor_mutex_); + if (!initialized_ || policy_ == policy) { + policy_ = policy; + return; + } + + if (WakeRequired(policy) && !EnsureWakeWordLoaded()) { + ESP_LOGE(kTag, "WakeNet unavailable for policy=%s", + ToString(policy)); + } + if (!WakeRequired(policy)) { + // The model stays resident; only the accumulator is dropped so the + // next duplex window does not start mid-phrase. The accumulator + // is owned by the wake-scan task, so hand it a reset flag rather + // than racing it. + wake_reset_pending_.store(true, std::memory_order_release); + } + + const bool old_aec_required = AecRequired(policy_); + const bool new_aec_required = AecRequired(policy); + if (new_aec_required) { + const bool barge_in_profile = + policy != AudioPolicy::kCallDuplex; + if (!dsp_.EnableEchoCancellation(barge_in_profile)) { + ESP_LOGE(kTag, "AEC unavailable for policy=%s", + ToString(policy)); + } + } else { + dsp_.SuspendEchoCancellation(); + } + if (old_aec_required != new_aec_required) { + ClearReference(); + } + if (policy == AudioPolicy::kConversationCapture || + policy_ == AudioPolicy::kConversationCapture) { + vad_.Reset(); + self_capture_hangover_ = 0; + } + if (policy != AudioPolicy::kBargeInDuplex) { + // The policy change means the control plane already decided the + // turn; a pending candidate must not publish a stale verdict on + // top. leak_ratio_ intentionally survives — the echo path barely + // moves between sessions, so the next duplex window starts with a + // trained gate instead of re-learning through a dirty one. + candidate_active_ = false; + consecutive_speech_frames_ = 0; + streak_peak_rms_ = 0; + uplink_pass_until_us_ = 0; + probe_silence_frames_ = 0; + candidate_deadline_us_ = 0; + candidate_rearm_until_us_ = 0; + candidate_needs_quiet_ = false; + window_ref_active_frames_ = 0; + previous_reference_rms_[0] = 0; + previous_reference_rms_[1] = 0; + } + policy_ = policy; + wake_ready = wake_word_.initialized(); + aec_active = new_aec_required; + duplex_window_closed = old_aec_required && !new_aec_required; + } + + // Debug: the engine's one-line summary (requested/effective/wake/barge) + // already covers every policy change at INFO. + ESP_LOGD(kTag, "policy=%s wake=%d aec=%d", + ToString(policy), + wake_ready ? 1 : 0, + aec_active ? 1 : 0); + if (duplex_window_closed) { + // One line per duplex window. aec_reference_misses is the number that + // matters: every miss is a 60 ms frame the AEC could not cancel, i.e. + // a frame of the device's own TTS that would have reached the server. + LogMetrics("duplex window closed"); + } +} + +void VoiceFrontend::LogMetrics(const char* reason) const +{ + // Snapshot under the spinlock, format outside it. + const VoiceFrontendMetrics snapshot = Metrics(); + ESP_LOGI(kTag, + "voice metrics (%s) frames=%lu ref_frames=%lu ref_drops=%lu " + "ref_trims=%lu " + "ref_misses=%lu uplink_suppressed=%lu self_capture=%lu " + "gated=%lu cand=%lu cand_local_rej=%lu cand_timeout=%lu " + "wake=%lu self_wake=%lu " + "vad_stops=%lu dsp_fail=%lu", + reason, + static_cast(snapshot.processed_frames), + static_cast(snapshot.reference_frames), + static_cast(snapshot.reference_drops), + static_cast(snapshot.reference_trims), + static_cast(snapshot.aec_reference_misses), + static_cast(snapshot.uplink_suppressions), + static_cast(snapshot.self_capture_suppressions), + static_cast(snapshot.residual_gated), + static_cast(snapshot.barge_in_candidates), + static_cast(snapshot.barge_in_local_rejects), + static_cast(snapshot.barge_in_timeouts), + static_cast(snapshot.wake_detections), + static_cast(snapshot.self_wake_suppressions), + static_cast(snapshot.vad_stops), + static_cast(snapshot.dsp_failures)); +} + +bool VoiceFrontend::Process( + AudioPolicy policy, + const int16_t* input, + size_t sample_count, + int16_t* output, + size_t output_capacity) +{ + if (input == nullptr || output == nullptr || + sample_count != kFrameSamples || + output_capacity < kFrameSamples) { + return false; + } + std::lock_guard lock(processor_mutex_); + std::array reference{}; + const bool has_reference = PopReference(reference.data()); + const uint32_t microphone_rms = FrameRms(input, sample_count); + const uint32_t reference_rms = + has_reference ? FrameRms(reference.data(), reference.size()) : 0; + + // Authoritative "is our own speaker running right now" test, shared by the + // VAD gate below and the wake-word self-trigger guard further down. Derived + // from the playback task's per-frame callback rather than from the energy of + // a popped reference frame, because the reference ring is empty whenever it + // has just been cleared or trimmed — and then the energy test silently + // reports "quiet" while the speaker is at full volume. + const uint64_t now_us = + static_cast(esp_timer_get_time()); + const uint64_t last_playback_us = + last_playback_frame_us_.load(std::memory_order_relaxed); + const bool speaker_active = + last_playback_us != 0 && + now_us - last_playback_us < kSpeakerActiveWindowUs; + + bool processed = true; + bool uplink_suppressed = false; + if (policy == AudioPolicy::kConversationCapture) { + processed = dsp_.Process( + input, nullptr, false, output, sample_count); + // Local prompts play while this policy is active — the wake + // acknowledgement "我在" is emitted immediately after the device enters + // listening — and this policy deliberately runs without AEC, so the + // microphone hears them at full level. Uploading that feeds the + // server's ASR the device's own voice, so the frames are dropped and + // the VAD is held in reset while the speaker runs. The server owns + // the authoritative auto-stop (listen mode="auto"), so a turn cannot + // hang here when the child stays quiet. + if (speaker_active) { + self_capture_hangover_ = kSelfCaptureHangoverFrames; + } + if (self_capture_hangover_ > 0) { + --self_capture_hangover_; + vad_.Reset(); + uplink_suppressed = true; + portENTER_CRITICAL(&metrics_lock_); + metrics_.self_capture_suppressions++; + portEXIT_CRITICAL(&metrics_lock_); + } else if (processed) { + // Observability only. The turn end is owned by the server + // (listen mode="auto", protocols/websocket_protocol.md): its VAD + // pads and finalizes the ASR segment. Publishing a local stop + // here used to close the turn early — WakeNet fires mid-phrase, + // so the wake word's own tail (>=2 loud frames = 120 ms) read as + // "speech started" and 13 quiet frames later the device tore the + // listening window down before the child had said a word. + const VoiceActivityResult vad = + vad_.Process(output, sample_count); + // Two short lines per turn. Kept on this task on purpose: the + // instant a turn opens and closes is exactly what needs a + // timestamp, and aggregating it would lose that. + if (vad == VoiceActivityResult::kSpeechStarted) { + ESP_LOGI(kTag, "vad speech_started rms=%lu", + static_cast(vad_.LastRms())); + } else if (vad == VoiceActivityResult::kSpeechEnded) { + ESP_LOGI(kTag, "vad speech_ended rms=%lu", + static_cast(vad_.LastRms())); + portENTER_CRITICAL(&metrics_lock_); + metrics_.vad_stops++; + portEXIT_CRITICAL(&metrics_lock_); + } + } + } else if (AecRequired(policy)) { + processed = dsp_.Process( + input, + reference.data(), + true, + output, + sample_count, + buffers_->wake_tap.data()); + if (processed && + policy == AudioPolicy::kBargeInDuplex && + UpdateBargeInGate( + FrameRms(output, sample_count), + reference_rms, + has_reference, + speaker_active, + now_us)) { + uplink_suppressed = true; + portENTER_CRITICAL(&metrics_lock_); + metrics_.residual_gated++; + portEXIT_CRITICAL(&metrics_lock_); + } + if (processed && !uplink_suppressed && + !has_reference && speaker_active) { + // The speaker is running but the reference ring was empty for this + // frame, so the AEC subtracted nothing and the frame still carries + // the full echo. Uploading it makes the server's ASR transcribe the + // device's own TTS and raise a barge-in against itself. Drop it from + // the uplink but keep it for the local wake word below, which is + // exactly the path that has to survive so "你好波乐" can still + // interrupt playback. + // + // speaker_active is load-bearing. This used to suppress on "no + // reference" alone — but an empty reference ring is overwhelmingly + // the signature of "nothing is playing", not of a missed frame. In + // kCallDuplex the far end is silent for most of a call, so no + // playback frame ever arrives, the ring stays empty, and every + // single microphone frame was dropped: the uplink was mute for the + // whole call. kWakeWordDuplex and the tail of a kBargeInDuplex turn + // had the same hole. No playback means no echo, so those frames are + // safe to send and must be sent — that silence was the child's turn. + uplink_suppressed = true; + portENTER_CRITICAL(&metrics_lock_); + metrics_.aec_reference_misses++; + portEXIT_CRITICAL(&metrics_lock_); + } + // Both duplex flavors feed WakeNet the AEC-cleaned output: it is the + // only interrupt in kWakeWordDuplex (no uplink there), and the fast + // "你好播乐 cuts the reply" path in kBargeInDuplex — natural speech + // there still goes through server VAD/ASR arbitration. Fed from the + // pre-AGC tap, not `output`: the AGC swings 0.9-1.8 during + // music+speech double-talk and the gain steps chop the phrase. + // A missing playback reference must not create a blind WakeNet frame: + // with a zero reference the DSP output is still a usable microphone + // fallback, and dropping it could cut an arbitrary part of the wake + // phrase. + if (processed && WakeRequired(policy)) { + QueueWakeAudio(buffers_->wake_tap.data()); + } + } else { + std::memcpy( + output, input, sample_count * sizeof(int16_t)); + if (WakeRequired(policy)) { + // Same hazard as the VAD gate: idle-mode prompts (idle_check, + // alarms, the shutdown prompt) reach the microphone unattenuated + // because this path has no AEC, and WakeNet will happily trigger on + // the device's own voice. The previous firmware hit this in the + // field (2026-07-03: idle_check "你还在吗小朋友" self-triggering) + // and muted detection around the prompt for the same reason. + if (speaker_active || self_capture_hangover_ > 0) { + if (self_capture_hangover_ > 0) { + --self_capture_hangover_; + } + if (speaker_active) { + self_capture_hangover_ = kSelfCaptureHangoverFrames; + } + portENTER_CRITICAL(&metrics_lock_); + metrics_.self_wake_suppressions++; + portEXIT_CRITICAL(&metrics_lock_); + } else { + QueueWakeAudio(output); + } + } + } + + AccumulateFrameStats( + policy, + microphone_rms, + FrameRms(output, sample_count), + reference_rms, + has_reference); + + portENTER_CRITICAL(&metrics_lock_); + metrics_.processed_frames++; + if (!processed) { + metrics_.dsp_failures++; + } + if (uplink_suppressed) { + metrics_.uplink_suppressions++; + } + portEXIT_CRITICAL(&metrics_lock_); + // Returning false makes CapturePipeline skip the encode/uplink for this + // frame. The wake word has already consumed it above. + return processed && !uplink_suppressed; +} + +void VoiceFrontend::OnPlaybackReference( + const int16_t* samples, + size_t sample_count) +{ + // Stamp first: this call means a frame is on its way to the DAC, which is + // the fact the capture side needs. Whether it also lands in the reference + // ring is a separate question. + last_playback_frame_us_.store( + static_cast(esp_timer_get_time()), + std::memory_order_relaxed); + + std::array converted{}; + if (!reference_converter_.Convert( + samples, + sample_count, + converted.data(), + converted.size())) { + return; + } + uint32_t discarded = 0; + { + std::lock_guard lock(reference_mutex_); + if (!buffers_) { + return; + } + // Trim before pushing so occupancy after this call never exceeds + // kReferenceMaxLeadFrames. See the constant for why the old + // drop-one-when-full rule pinned the skew at its maximum instead of + // bounding it. + while (reference_count_ >= kReferenceMaxLeadFrames) { + reference_read_ = + (reference_read_ + 1) % kReferenceDepth; + reference_count_--; + discarded++; + } + buffers_->reference_ring[reference_write_] = converted; + reference_write_ = + (reference_write_ + 1) % kReferenceDepth; + reference_count_++; + } + if (discarded != 0) { + // The reference just jumped a frame relative to the echo still in + // flight; the AEC runs misaligned until it re-adapts and its residual + // bursts over the floor. Field run: 15 trims, ~17 false candidates, + // each pausing playback 0.4-1.5 s. Hold candidates while it settles. + alignment_settle_until_us_.store( + static_cast(esp_timer_get_time()) + kAlignmentSettleUs, + std::memory_order_relaxed); + } + portENTER_CRITICAL(&metrics_lock_); + metrics_.reference_frames++; + if (discarded != 0) { + metrics_.reference_drops += discarded; + metrics_.reference_trims++; + } + portEXIT_CRITICAL(&metrics_lock_); +} + +void VoiceFrontend::ResetPlaybackReference() +{ + ClearReference(); +} + +VoiceFrontendMetrics VoiceFrontend::Metrics() const +{ + portENTER_CRITICAL(&metrics_lock_); + const VoiceFrontendMetrics snapshot = metrics_; + portEXIT_CRITICAL(&metrics_lock_); + return snapshot; +} + +bool VoiceFrontend::WakeRequired(AudioPolicy policy) const +{ + // kBargeInDuplex feeds WakeNet too, so "你好播乐" interrupts a playing + // reply (product requirement). This was disabled while AEC+WakeNet + // measured 68 ms per 60 ms frame — but that number had Opus encode on the + // same task. With the encoder on core 1 and complexity 3 the duplex + // process step averages 10-15 ms (max ~37 ms); WakeNet's ~14 ms fits the + // budget. Watch period_avg in the frame stats: if it climbs past ~65 ms + // the fallback is a dedicated core-1 wake task (audit option R7). + // Self-trigger safety: the feed is post-AEC (echo at -10..-20 dB), and a + // rare false fire lands in the state machine as an ordinary barge-in. + // + // kWakeWordDuplex keeps it for the no-uplink prompt/alert windows where + // the wake word is the only interrupt. + return wake_word_enabled_ && + (policy == AudioPolicy::kWakeWordOnly || + policy == AudioPolicy::kWakeWordDuplex || + policy == AudioPolicy::kBargeInDuplex); +} + +bool VoiceFrontend::AecRequired(AudioPolicy policy) const +{ + return policy == AudioPolicy::kWakeWordDuplex || + policy == AudioPolicy::kBargeInDuplex || + policy == AudioPolicy::kCallDuplex; +} + +void VoiceFrontend::FeedWakeWord( + const int16_t* samples, + size_t sample_count) +{ + // Wake-scan task only. The lock serializes Detect against the model + // being loaded (ApplyPolicy) or released (BLE provisioning). + std::lock_guard lock(wake_mutex_); + if (!buffers_ || !wake_word_.initialized() || + wake_word_.ChunkSamples() == 0) { + return; + } + auto& wake_accumulator = buffers_->wake_accumulator; + const uint64_t now_ms = static_cast( + esp_timer_get_time() / 1000); + if (now_ms < wake_cooldown_until_ms_) { + return; + } + if (wake_accumulator_count_ + sample_count > + wake_accumulator.size()) { + wake_accumulator_count_ = 0; + } + std::memcpy( + wake_accumulator.data() + wake_accumulator_count_, + samples, + sample_count * sizeof(int16_t)); + wake_accumulator_count_ += sample_count; + const size_t chunk = wake_word_.ChunkSamples(); + while (wake_accumulator_count_ >= chunk) { + const bool detected = wake_word_.Detect( + wake_accumulator.data(), chunk); + std::memmove( + wake_accumulator.data(), + wake_accumulator.data() + chunk, + (wake_accumulator_count_ - chunk) * sizeof(int16_t)); + wake_accumulator_count_ -= chunk; + if (detected) { + // ConversationCapture does not feed WakeNet. A frame counter used + // to freeze for the whole user question, then blind the first two + // seconds of the following TTS reply. Wall time keeps the intended + // duplicate-trigger protection without carrying that blind spot. + wake_cooldown_until_ms_ = now_ms + kWakeCooldownMs; + portENTER_CRITICAL(&metrics_lock_); + metrics_.wake_detections++; + portEXIT_CRITICAL(&metrics_lock_); + Publish(AppEvent::Make( + AppEventType::kWakeWordDetected)); + wake_accumulator_count_ = 0; + break; + } + } +} + +void VoiceFrontend::ResolveCandidateLocked( + AppEventType verdict, + const char* reason, + uint64_t now_us) +{ + candidate_active_ = false; + consecutive_speech_frames_ = 0; + streak_peak_rms_ = 0; + probe_silence_frames_ = 0; + candidate_deadline_us_ = 0; + // No new candidate until the energy has both cooled off in time and + // dipped below the leak line at least once — see kCandidateRearmUs. + candidate_rearm_until_us_ = now_us + kCandidateRearmUs; + candidate_needs_quiet_ = true; + ESP_LOGI(kTag, "barge-in candidate %s", reason); + Publish(AppEvent::Make(verdict)); +} + +bool VoiceFrontend::UpdateBargeInGate( + uint32_t out_rms, + uint32_t reference_rms, + bool has_reference, + bool speaker_active, + uint64_t now_us) +{ + if (candidate_active_) { + if (now_us >= candidate_deadline_us_) { + // Neither the server nor the probe decided. Resume playback; the + // reducer drops this if the server confirmed meanwhile. + portENTER_CRITICAL(&metrics_lock_); + metrics_.barge_in_timeouts++; + portEXIT_CRITICAL(&metrics_lock_); + // Sustained energy the server chose not to act on is most likely + // a raised noise floor; lift the line so it stops re-triggering. + leak_ratio_ = std::min(leak_ratio_ * 1.25F, kLeakMaximum); + ResolveCandidateLocked( + AppEventType::kBargeInRejected, "timed out, resuming", + now_us); + } else if (!speaker_active) { + // Playback paused, so the echo source is gone: whatever the + // microphone hears now is ground truth. + if (out_rms < kProbeSpeechFloorRms) { + if (++probe_silence_frames_ >= kProbeSilenceFrames) { + // The energy vanished with the speaker — it was residual. + // Raise the leak line so the same level does not trigger + // again, and resume. + leak_ratio_ = std::min( + leak_ratio_ * 1.5F, kLeakMaximum); + portENTER_CRITICAL(&metrics_lock_); + metrics_.barge_in_local_rejects++; + portEXIT_CRITICAL(&metrics_lock_); + ResolveCandidateLocked( + AppEventType::kBargeInRejected, + "probe heard silence, resuming", + now_us); + } + } else { + // A voice that survives the pause is a real voice; it is now + // uploading clean. Leave the verdict to the server's STT. + probe_silence_frames_ = 0; + } + } + } + + if (!speaker_active) { + // Speaker quiet (idle gap or candidate pause): no echo to gate, every + // frame belongs to the room. Upload freely. + consecutive_speech_frames_ = 0; + streak_peak_rms_ = 0; + return false; + } + if (!has_reference) { + // Full echo with nothing to subtract; the caller's reference-miss rule + // suppresses it. It carries no gate information either way. + consecutive_speech_frames_ = 0; + streak_peak_rms_ = 0; + return false; + } + + // Residual lags the reference by the TX DMA depth (~1.5 frames), so the + // echo in this frame is explained by the loudest of the LAST THREE + // reference frames, not by the instantaneous one. Judged against the + // instantaneous value the per-frame ratio swung between ~0.1 and ~1.0 + // with alignment jitter (field: out=1437 against ref=1450 one moment, + // out=787 against ref=7325 the next) — no single line covers that spread + // without also swallowing speech. + const uint32_t reference_peak = std::max( + {reference_rms, + previous_reference_rms_[0], + previous_reference_rms_[1]}); + previous_reference_rms_[1] = previous_reference_rms_[0]; + previous_reference_rms_[0] = reference_rms; + // Leak information only exists while the reference actually carries + // energy. In an inter-sentence TTS gap the ratio degenerates — training + // on it would drag the line to a clamp and blind the gate for the next + // sentence. Gap frames are judged by the absolute floor alone. + const bool reference_active = + reference_peak >= kReferenceActiveRms; + if (reference_active && + window_ref_active_frames_ < UINT16_MAX) { + window_ref_active_frames_++; + } + const float ratio = + static_cast(out_rms) / + static_cast(reference_peak != 0 ? reference_peak : 1); + + if (!leak_seeded_ && reference_active) { + // Warm-up. The first reference frames PRECEDE their own echo (the + // reference is queued ~1.5 frames before the sound leaves the + // speaker), so seeding from the first frame reads out≈noise and pins + // the line at the floor — the field failure was candidates raised + // with leak=0.05 while ERL was 7 dB, each pausing playback for half a + // second. Instead: withhold the first kLeakWarmupFrames loud frames + // outright, remember the WORST ratio seen, and floor the seed. A high + // start self-corrects (the EMA below only trains on gated frames, so + // the line can walk down to truth but never up past speech); a low + // start is a trap. + leak_ratio_ = std::clamp( + std::max(leak_ratio_, ratio), + kLeakMinimum, + kLeakMaximum); + consecutive_speech_frames_ = 0; + streak_peak_rms_ = 0; + if (++leak_warmup_frames_ >= kLeakWarmupFrames) { + leak_ratio_ = std::max(leak_ratio_, kLeakSeedMinimum); + leak_seeded_ = true; + ESP_LOGI(kTag, "barge-in gate seeded leak=%.2f", + static_cast(leak_ratio_)); + } + return true; + } + + float threshold = leak_seeded_ + ? leak_ratio_ * static_cast(reference_peak) * + kLeakMargin + : 0.0F; + threshold = std::max( + threshold, static_cast(kResidualFloorRms)); + + if (static_cast(out_rms) <= threshold) { + // The dip below the line still re-arms the candidate gate either way. + candidate_needs_quiet_ = false; + consecutive_speech_frames_ = 0; + streak_peak_rms_ = 0; + if (now_us < uplink_pass_until_us_) { + // Inside an open voice segment this is an envelope dip, not + // residual: pass it so the server hears one contiguous + // utterance, and do NOT train the leak line on it — the frame + // may carry voice and training would drag the line upward. + return false; + } + // Explainable as residual: withhold it from the uplink, and train the + // leak line when the frame carries usable ratio information. + if (leak_seeded_ && reference_active) { + leak_ratio_ = std::clamp( + leak_ratio_ + kLeakAlpha * (ratio - leak_ratio_), + kLeakMinimum, + kLeakMaximum); + } + return true; + } + + // Above the leak line: treat as the child speaking over the TTS. The frame + // flows to the server, and enough of them in a row raises the reversible + // pause. The leak estimate is deliberately not trained on these frames. + if (consecutive_speech_frames_ < 255) { + ++consecutive_speech_frames_; + } + streak_peak_rms_ = std::max(streak_peak_rms_, out_rms); + if (consecutive_speech_frames_ >= kUplinkPassStreak) { + // Plausible voice: open (or extend) the segment window so the whole + // utterance reaches the server in one piece. + uplink_pass_until_us_ = now_us + kUplinkPassWindowUs; + } + // Candidates only where the pause-probe has value: gate seeded, the + // reference loud enough that echo could explain the energy, past the + // per-window AEC convergence holdoff, and not inside the re-adaptation + // window a reference trim opens. The trigger itself is shape-based: + // a sustained streak whose peak reached voice level — residual plateaus + // never peak, speech always does. Everything else still uploads and is + // the server's call. + if (!candidate_active_ && + leak_seeded_ && + reference_active && + window_ref_active_frames_ >= kCandidateHoldoffFrames && + now_us >= alignment_settle_until_us_.load( + std::memory_order_relaxed) && + !candidate_needs_quiet_ && + now_us >= candidate_rearm_until_us_ && + consecutive_speech_frames_ >= kCandidateFrames && + streak_peak_rms_ >= kCandidateStrongRms) { + candidate_active_ = true; + probe_silence_frames_ = 0; + candidate_deadline_us_ = now_us + kCandidateTimeoutUs; + portENTER_CRITICAL(&metrics_lock_); + metrics_.barge_in_candidates++; + portEXIT_CRITICAL(&metrics_lock_); + ESP_LOGI(kTag, + "barge-in candidate raised out_rms=%lu peak=%lu ref_rms=%lu " + "leak=%.2f", + static_cast(out_rms), + static_cast(streak_peak_rms_), + static_cast(reference_rms), + static_cast(leak_ratio_)); + Publish(AppEvent::Make(AppEventType::kBargeInCandidate)); + } + if (now_us < uplink_pass_until_us_) { + return false; + } + if (consecutive_speech_frames_ == 1 && !candidate_active_) { + // Single-frame excursions over the leak line are the signature of a + // syllable-onset residual spike (the adaptive filter under-cancels + // transients); real speech sustains. Withhold the first frame and + // pass from the second on — costs 60 ms of a genuine barge-in onset, + // which the server's ASR tolerates, and removes the last rhythmic + // residual ticks from the uplink. + return true; + } + return false; +} + +bool VoiceFrontend::PopReference(int16_t* output) +{ + std::lock_guard lock(reference_mutex_); + if (!buffers_ || reference_count_ == 0) { + // Ring drained: the next burst must re-prime before serving, or the + // whole burst runs echo-misaligned (see reference_primed_). + reference_primed_ = false; + std::fill_n(output, kFrameSamples, 0); + return false; + } + if (!reference_primed_) { + if (reference_count_ < kReferencePrimeFrames) { + // The echo of these first frames is still inside the ~90 ms TX + // DMA and has not reached the microphone; serving them now would + // pair the AEC with a reference the echo lags by more than the + // 64 ms filter span. Field data: ref_depth >= ~2 tracked + // erl 16-20 dB, depth < 1 tracked erl <= 8 dB — every playback + // gap drained the ring and the following burst leaked rhythmic + // TTS residual into the uplink until depth recovered by luck. + std::fill_n(output, kFrameSamples, 0); + return false; + } + reference_primed_ = true; + } + std::memcpy( + output, + buffers_->reference_ring[reference_read_].data(), + kFrameSamples * sizeof(int16_t)); + reference_read_ = + (reference_read_ + 1) % kReferenceDepth; + reference_count_--; + return true; +} + +void VoiceFrontend::ClearReference() +{ + std::lock_guard lock(reference_mutex_); + reference_read_ = 0; + reference_write_ = 0; + reference_count_ = 0; + reference_primed_ = false; +} + +uint32_t VoiceFrontend::FrameRms( + const int16_t* samples, + size_t sample_count) +{ + if (samples == nullptr || sample_count == 0) { + return 0; + } + uint64_t energy = 0; + for (size_t index = 0; index < sample_count; ++index) { + const int32_t value = samples[index]; + energy += static_cast(value * value); + } + return static_cast( + std::sqrt( + static_cast(energy) / + static_cast(sample_count))); +} + +void VoiceFrontend::AccumulateFrameStats( + AudioPolicy policy, + uint32_t microphone_rms, + uint32_t processed_rms, + uint32_t reference_rms, + bool has_reference) +{ + const uint64_t now_us = + static_cast(esp_timer_get_time()); + uint32_t depth = 0; + { + std::lock_guard lock(reference_mutex_); + depth = static_cast(reference_count_); + } + + portENTER_CRITICAL(&metrics_lock_); + if (last_frame_us_ != 0 && now_us > last_frame_us_) { + const uint32_t period_us = + static_cast(now_us - last_frame_us_); + frame_stats_.period_us_sum += period_us; + frame_stats_.period_us_max = + std::max(frame_stats_.period_us_max, period_us); + } + last_frame_us_ = now_us; + frame_stats_.frames++; + frame_stats_.policy = policy; + frame_stats_.microphone_rms_sum += microphone_rms; + frame_stats_.processed_rms_sum += processed_rms; + frame_stats_.reference_rms_sum += reference_rms; + frame_stats_.microphone_rms_peak = + std::max(frame_stats_.microphone_rms_peak, microphone_rms); + frame_stats_.processed_rms_peak = + std::max(frame_stats_.processed_rms_peak, processed_rms); + frame_stats_.reference_rms_peak = + std::max(frame_stats_.reference_rms_peak, reference_rms); + if (has_reference) { + frame_stats_.reference_present_frames++; + } + if (reference_rms >= kReferenceActiveRms) { + frame_stats_.reference_active_frames++; + } + frame_stats_.reference_depth_sum += depth; + frame_stats_.reference_depth_peak = + std::max(frame_stats_.reference_depth_peak, depth); + if (vad_.speech_active()) { + frame_stats_.vad_speech_frames++; + } + frame_stats_.agc_gain = dsp_.AgcGain(); + frame_stats_.aec_active = dsp_.EchoCancellationActive(); + frame_stats_.ns_active = + dsp_.NoiseSuppressionActive() && !dsp_.BargeInProfile(); + frame_stats_.barge_in_profile = dsp_.BargeInProfile(); + portEXIT_CRITICAL(&metrics_lock_); +} + +VoiceFrameStats VoiceFrontend::ConsumeFrameStats() +{ + portENTER_CRITICAL(&metrics_lock_); + const VoiceFrameStats snapshot = frame_stats_; + const AudioPolicy policy = frame_stats_.policy; + frame_stats_ = VoiceFrameStats{}; + frame_stats_.policy = policy; + portEXIT_CRITICAL(&metrics_lock_); + return snapshot; +} + +void VoiceFrontend::Publish(const AppEvent& event) +{ + IEventPublisher* publisher = publisher_.load(); + if (publisher == nullptr || !publisher->Publish(event)) { + ESP_LOGE(kTag, "event publish failed type=%s", + ToString(event.type)); + } +} + +} // namespace borla diff --git a/main/audio/voice_frontend.h b/main/audio/voice_frontend.h new file mode 100644 index 0000000..436fea0 --- /dev/null +++ b/main/audio/voice_frontend.h @@ -0,0 +1,392 @@ +#pragma once + +#include "audio/pcm_rate_converter.h" +#include "audio/voice_activity_detector.h" +#include "audio/voice_dsp.h" +#include "audio/voice_frame_processor.h" +#include "audio/wake_word_detector.h" +#include "core/psram_object.h" +#include "ports/event_publisher.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace borla { + +struct VoiceFrontendMetrics { + uint32_t processed_frames = 0; + uint32_t reference_frames = 0; + uint32_t reference_drops = 0; + uint32_t reference_trims = 0; + uint32_t wake_detections = 0; + uint32_t aec_reference_misses = 0; + uint32_t uplink_suppressions = 0; + uint32_t self_capture_suppressions = 0; + uint32_t self_wake_suppressions = 0; + uint32_t vad_stops = 0; + uint32_t dsp_failures = 0; + // Barge-in gate: frames whose energy the leak line explained as residual + // echo and which were therefore withheld from the uplink. + uint32_t residual_gated = 0; + // Local barge-in candidates raised, and how they ended when the server + // did not decide them: probe heard silence after the pause (local reject) + // or nothing arrived at all (timeout). + uint32_t barge_in_candidates = 0; + uint32_t barge_in_local_rejects = 0; + uint32_t barge_in_timeouts = 0; +}; + +// Rolling per-frame measurements of the capture chain, accumulated by the +// capture task and drained by the diagnostics worker. The capture task only +// does arithmetic here: it must never write to the console, because a log line +// takes longer than the 60 ms frame budget it is already struggling to meet. +struct VoiceFrameStats { + uint32_t frames = 0; + uint32_t microphone_rms_sum = 0; + uint32_t processed_rms_sum = 0; + uint32_t reference_rms_sum = 0; + uint32_t microphone_rms_peak = 0; + uint32_t processed_rms_peak = 0; + uint32_t reference_rms_peak = 0; + uint32_t reference_present_frames = 0; + uint32_t reference_active_frames = 0; + uint32_t reference_depth_sum = 0; + uint32_t reference_depth_peak = 0; + uint32_t vad_speech_frames = 0; + uint32_t period_us_max = 0; + uint64_t period_us_sum = 0; + float agc_gain = 0.0F; + bool aec_active = false; + bool ns_active = false; + bool barge_in_profile = false; + AudioPolicy policy = AudioPolicy::kOff; +}; + +class VoiceFrontend final + : public IVoiceFrameProcessor, + public IPlaybackReferenceSink { +public: + bool Initialize(); + void SetEventPublisher(IEventPublisher* publisher); + void SetWakeWordEnabled(bool enabled); + void ApplyPolicy(AudioPolicy policy) override; + bool Process( + AudioPolicy policy, + const int16_t* input, + size_t sample_count, + int16_t* output, + size_t output_capacity) override; + void OnPlaybackReference( + const int16_t* samples, + size_t sample_count) override; + void ResetPlaybackReference() override; + // Frees the WakeNet instance. Only for entering BLE provisioning, where the + // BT controller needs every spare byte and the wake word is unused. Normal + // policy changes must never call this: reloading the model takes ~110 ms + // under processor_mutex_, which stalls the capture task and breaks AEC + // mic/reference lockstep. See EnsureWakeWordLoaded(). + void ReleaseWakeWord(); + VoiceFrontendMetrics Metrics() const; + void LogMetrics(const char* reason) const; + // Returns the frames measured since the previous call and clears the + // accumulator. Called by the diagnostics worker, never by the capture task. + VoiceFrameStats ConsumeFrameStats(); + +private: + static constexpr size_t kFrameSamples = 960; + static constexpr size_t kReferenceDepth = 4; + // Occupancy the ring is trimmed back to on every push, NOT the array size. + // + // The echo of a reference frame reaches the microphone about 1.5 x 60 ms + // frames after it is queued (the I2S TX DMA holds 6 x 360 samples @ 24 kHz + // = 90 ms). So the frame the AEC needs was pushed 1-2 frames ago, i.e. the + // ring should sit at an occupancy of 2-3. It used to be 8 deep with a + // drop-the-oldest overflow rule, which is the worst possible combination: + // once the capture task falls behind, the ring pins itself at full and + // every reference handed to the AEC is ~7 frames (420 ms) older than the + // echo it is supposed to cancel. The adaptive filter spans roughly + // filter_length x chunk = 4 x 16 ms, so it simply stopped cancelling and + // the speaker leaked into the uplink — the device then answered its own + // TTS. Field metrics showed 25-30% of reference frames being dropped that + // way, i.e. a permanently full ring. + // + // Trimming to the newest frames costs AEC continuity when capture lags, + // but a correctly aligned reference with occasional gaps cancels; a + // chronically skewed one cancels nothing. + static constexpr size_t kReferenceMaxLeadFrames = 3; + // A freshly refilled ring must hold this many frames before serving the + // AEC: the echo of the first pushed frames is still inside the TX DMA and + // has not reached the microphone, so serving early pairs the filter with + // a reference the echo lags by more than its 64 ms span. Field data tied + // ref_depth >= ~2 to erl 16-20 dB and depth < 1 to <= 8 dB. + static constexpr size_t kReferencePrimeFrames = 2; + static constexpr size_t kWakeAccumulatorSamples = 4096; + static constexpr uint64_t kWakeCooldownMs = 2000; + static constexpr uint32_t kReferenceActiveRms = 300; + // Frames to keep ignoring the microphone after the playback reference goes + // quiet. The reference is queued before the I2S write, so it leads the + // sound leaving the speaker by the DMA depth (6 x 240 frames @ 24 kHz = + // 60 ms) plus PA and decay. Four 60 ms frames covers that tail without + // eating into the child's answer, which may start the instant the prompt + // stops. The previous firmware used a blunt 800 ms drain, but it only did + // so before a one-shot idle probe, never inside a listening turn. + static constexpr uint8_t kSelfCaptureHangoverFrames = 4; + // How stale the last playback frame may be before the speaker counts as + // quiet. OnPlaybackReference() fires once per decoded frame, so two frame + // periods bridges normal jitter without keeping the gate open into silence. + static constexpr uint64_t kSpeakerActiveWindowUs = 120ULL * 1000ULL; + + // --- Barge-in residual gate + local candidate (kBargeInDuplex only) --- + // + // The AEC on this board converges to 17-20 dB ERL but starts every TTS + // session at 8-10 dB, and those first seconds of residual (out_rms up to + // several thousand) were being uploaded and transcribed by the server's + // ASR as user speech — the device then answered itself. Energy alone + // cannot separate residual from speech (they overlap in RMS), but residual + // is the only signal that scales with the playback reference. The gate + // therefore tracks leak = out_rms / ref_rms over frames it suppresses and + // withholds any frame whose energy the leak line explains; a frame that + // jumps clear of the line is treated as the child speaking, flows to the + // server, and after kCandidateFrames of it a local kBargeInCandidate + // reversibly pauses playback. The pause doubles as a probe: with the + // speaker silent the echo source is gone, so persistent energy means a + // real voice (now uploaded clean for the server to confirm) and instant + // silence means a false trigger, answered by a local kBargeInRejected. + // kBargeInRejected/kBargeInConfirmed guards in the reducer make a + // duplicate or late local verdict a no-op. + static constexpr float kLeakMargin = 1.5F; + static constexpr float kLeakAlpha = 0.0625F; // EMA 1/16 + // EMA clamp floor ≈ the leak at 16 dB ERL — the best this AEC sustains + // in-session, so the line has no business going lower. The first cut used + // 0.05 and the gate seeded there (see the warm-up note in the .cc), which + // made every louder-than-floor residual frame read as speech: candidates + // fired with leak=0.05 while ERL was 7 dB and each one paused playback for + // ~half a second — heard in the field as stutter. + static constexpr float kLeakMinimum = 0.15F; + static constexpr float kLeakMaximum = 6.0F; + // Seed the line no lower than this once warm-up completes. Starting high + // is self-correcting (the EMA walks it down on gated frames); starting low + // is a trap (frames above the line never train it). + static constexpr float kLeakSeedMinimum = 0.5F; + // Loud-reference frames observed before the seed is trusted: long enough + // for the echo of the first frames to actually arrive at the microphone. + static constexpr uint8_t kLeakWarmupFrames = 8; // ~0.5 s + // Absolute floors sized against the barge-in profile's noise floor, which + // is NOT the quiet-capture one: NS is off in this profile and the AGC + // (gain up to 1.8) amplifies room noise to ~250-300 RMS. The first cut + // used 200/250 and inter-sentence TTS gaps — reference near zero, AGC- + // amplified noise just over the floor — fired candidates that paused + // playback for half a second: the field symptom was intermittent playback + // stutter. Child speech through this path measures ≥2000, so 500/400 + // keeps an order-of-magnitude gap on both sides. + static constexpr uint32_t kResidualFloorRms = 500; + static constexpr uint32_t kProbeSpeechFloorRms = 400; + static constexpr uint8_t kCandidateFrames = 3; // 180 ms of speech + static constexpr uint8_t kProbeSilenceFrames = 5; // 300 ms of silence + // Nothing from the server and no probe verdict after this long: resume + // playback rather than leaving it paused forever. The reducer ignores the + // resulting kBargeInRejected if the server decided meanwhile. + static constexpr uint64_t kCandidateTimeoutUs = 1500ULL * 1000ULL; + // After a candidate is locally rejected or times out, no new candidate + // may be raised until this much time has passed AND at least one frame + // fell back below the leak line. Without it, the same sustained energy + // re-raised immediately: field log showed one TTS session paused four + // times for ~4.8 s total (three 1.5 s timeouts back to back) while the + // server kept streaming — the 48-slot queue overflowed and ~1.8 s of + // audio was dropped mid-sentence. During the hold the uplink still + // flows, so the server's own abort arbitration stays fully armed. + static constexpr uint64_t kCandidateRearmUs = 2000ULL * 1000ULL; + // No candidate may be raised during the first ~0.9 s of loud reference + // in each duplex window: the AEC re-converges at every session start + // (erl ~8-10 dB vs 17-25 dB converged) and its elevated residual crosses + // a leak line trained on the converged state. Field log: four candidate + // pauses in one run, ALL within 1 s of a session start, none + // mid-sentence. Real speech in that window still uploads and the server + // can abort; only the local reversible pause waits. + static constexpr uint16_t kCandidateHoldoffFrames = 15; + // A candidate additionally needs the over-line streak's PEAK to reach + // this level. Peak, not consecutive level: real speech is an envelope — + // syllable peaks with dips between them — and "N consecutive frames all + // loud" is unsatisfiable for it (field: with a consecutive-1100 rule the + // gate raised zero candidates for genuine interjections; duplex read as + // dead). Residual is the opposite shape, a plateau. The level is + // calibrated against double-talk reality: the AEC attenuates near-end + // speech while the far end plays (field tap: the child's voice sat + // entirely below the leak line during TTS), so voice peaks at the gate + // land near 900-1500, not the 2000-9000 seen without playback. False + // positives are held off by the trim-settle window + holdoff + rearm, + // not by this line alone. + static constexpr uint32_t kCandidateStrongRms = 900; + // A reference-ring trim jumps the reference timeline by a whole frame + // (60 ms > the 64 ms AEC filter span): the filter is misaligned until it + // re-adapts, and its residual reads as room energy. No candidate until + // the echo path has settled; uplink gating is untouched. + static constexpr uint64_t kAlignmentSettleUs = 2000ULL * 1000ULL; + // Segment-level uplink gating. Per-frame RMS censorship shreds speech: + // only the frames over the leak line survived, so the server's VAD/ASR + // received disconnected 60 ms shards and its whole two-phase arbitration + // starved (field tap: the child's voice was ENTIRELY absent from the + // uplink during TTS). Once a streak of kUplinkPassStreak over-line + // frames shows plausible voice, pass EVERYTHING for the next + // kUplinkPassWindowUs — envelope dips included — and keep extending + // while frames stay over the line. Suppression resumes when the window + // lapses, so the steady-state uplink stays as silent as before; the + // cost is a sub-second residual tail after a burst that opened a window. + static constexpr uint64_t kUplinkPassWindowUs = 800ULL * 1000ULL; + static constexpr uint8_t kUplinkPassStreak = 2; + + // The wake accumulator (8 KB) and the AEC reference ring (15 KB) used to + // sit in the CompositionRoot's .bss, i.e. 23 KB of internal RAM held for + // the whole uptime. Internal RAM is the scarce pool on this board: the BT + // controller needs ~53 KB and the WiFi driver ~36 KB, and BLE provisioning + // has to hold both at once when it re-attaches WiFi to test credentials. + // Both buffers are only touched by the capture and playback tasks, whose + // stacks already live in PSRAM, so moving them there costs nothing that + // matters and buys back the headroom. + struct ScratchBuffers { + std::array wake_accumulator{}; + std::array< + std::array, + kReferenceDepth> + reference_ring{}; + // Post-AEC, pre-AGC copy of the frame for WakeNet. The AGC pumps + // hard during music+speech double-talk (gain swinging 0.9-1.8 inside + // one phrase) and a phrase chopped by gain steps is what WakeNet + // misses; idle detection feeds the raw microphone and never sees + // this, which is why it stays sensitive. + std::array wake_tap{}; + }; + + bool WakeRequired(AudioPolicy policy) const; + bool AecRequired(AudioPolicy policy) const; + // Loads the WakeNet model at most once per boot. Deliberately lazy rather + // than eager: BLE provisioning runs with AudioPolicy::kOff from boot, so + // the model never loads there and the BT controller keeps the internal RAM + // that esp_wifi_deinit() freed for it. + bool EnsureWakeWordLoaded(); + void FeedWakeWord( + const int16_t* samples, + size_t sample_count); + bool PopReference(int16_t* output); + void ClearReference(); + // Runs the residual gate and the local candidate state machine for one + // kBargeInDuplex frame. Returns true when the frame must be withheld from + // the uplink. Called with processor_mutex_ held. + bool UpdateBargeInGate( + uint32_t out_rms, + uint32_t reference_rms, + bool has_reference, + bool speaker_active, + uint64_t now_us); + void ResolveCandidateLocked( + AppEventType verdict, + const char* reason, + uint64_t now_us); + static uint32_t FrameRms( + const int16_t* samples, + size_t sample_count); + void AccumulateFrameStats( + AudioPolicy policy, + uint32_t microphone_rms, + uint32_t processed_rms, + uint32_t reference_rms, + bool has_reference); + void Publish(const AppEvent& event); + static void WakeScanTaskEntry(void* context); + [[noreturn]] void RunWakeScan(); + void QueueWakeAudio(const int16_t* samples); + + std::atomic publisher_{nullptr}; + mutable std::mutex processor_mutex_; + AudioPolicy policy_ = AudioPolicy::kOff; + WakeWordDetector wake_word_; + VoiceDsp dsp_; + VoiceActivityDetector vad_; + std::unique_ptr> + buffers_; + // --- Wake-word scan task (core 1) --- + // On paper AEC (10-15 ms avg) plus WakeNet (~14 ms) fitted the 60 ms + // capture budget; in the field the worst cases stacked to 59-84 ms of + // process time (period_avg 66-70 ms): the microphone backlogged, the + // reference ring pinned at its trim ceiling (ref_trims 4-9/window) and + // the echo alignment wobbled — audible as residual ticks in the uplink. + // Detection therefore runs on its own core-1 task fed through this + // queue; the capture task only copies one frame and moves on. + // wake_accumulator_/cooldown are owned by the scan task; wake_mutex_ + // serializes Detect against model load/release. + static constexpr size_t kWakeQueueFrames = 6; + static constexpr uint32_t kWakeScanStackBytes = 12 * 1024; + QueueHandle_t wake_queue_ = nullptr; + TaskHandle_t wake_task_ = nullptr; + std::mutex wake_mutex_; + std::atomic wake_reset_pending_{false}; + size_t wake_accumulator_count_ = 0; + uint64_t wake_cooldown_until_ms_ = 0; + uint8_t self_capture_hangover_ = 0; + // Barge-in gate state. All owned by the capture task under + // processor_mutex_. leak_ratio_ survives policy changes on purpose: the + // echo path barely moves between TTS sessions, so the next session starts + // with a trained gate instead of re-learning through a dirty window. + float leak_ratio_ = 0.0F; + bool leak_seeded_ = false; + uint8_t leak_warmup_frames_ = 0; + // The last two reference RMS values. Residual lags the reference by the + // TX DMA depth (~1.5 frames), so a frame's echo is explained by the + // loudest of the last three reference frames, never by the instantaneous + // one alone. + uint32_t previous_reference_rms_[2] = {0, 0}; + bool candidate_active_ = false; + uint64_t candidate_rearm_until_us_ = 0; + bool candidate_needs_quiet_ = false; + uint16_t window_ref_active_frames_ = 0; + uint8_t consecutive_speech_frames_ = 0; + uint32_t streak_peak_rms_ = 0; + uint64_t uplink_pass_until_us_ = 0; + std::atomic alignment_settle_until_us_{0}; + uint8_t probe_silence_frames_ = 0; + uint64_t candidate_deadline_us_ = 0; + // Timestamp of the most recent frame handed to the speaker. Written by the + // playback task, read by the capture task. + // + // This replaced "is the popped reference frame loud?" as the self-playback + // test. That question is unanswerable when the reference ring is empty — + // and it routinely is, because the ring gets cleared on every policy change + // and playback session start, and trimmed on every push. Field log showed + // ref_present=0 for the whole wake-acknowledgement window, so the guard + // never armed and the VAD treated the device's own "我在" as the child + // answering: speech_started 348 ms into the prompt, speech_ended 568 ms + // after it stopped, turn closed 1.4 s after the wake word. The child had to + // speak instantly or say the wake word again. + std::atomic last_playback_frame_us_{0}; + + // Each ring slot is a 1920-byte frame. Copying that under a spinlock kept + // interrupts disabled for tens of microseconds on every capture and + // playback frame; both callers are tasks, so a mutex is the right lock. + mutable std::mutex reference_mutex_; + size_t reference_read_ = 0; + size_t reference_write_ = 0; + size_t reference_count_ = 0; + bool reference_primed_ = false; + //Pcm24kTo16kConverter reference_converter_; + Pcm48kTo16kConverter reference_converter_; + + + mutable portMUX_TYPE metrics_lock_ = + portMUX_INITIALIZER_UNLOCKED; + VoiceFrontendMetrics metrics_{}; + VoiceFrameStats frame_stats_{}; + uint64_t last_frame_us_ = 0; + bool initialized_ = false; + bool wake_word_enabled_ = true; +}; + +} // namespace borla diff --git a/main/audio/wake_word_detector.cc b/main/audio/wake_word_detector.cc new file mode 100644 index 0000000..36e4ce4 --- /dev/null +++ b/main/audio/wake_word_detector.cc @@ -0,0 +1,103 @@ +#include "audio/wake_word_detector.h" + +#include +#include +#include +#include + +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "WakeWord2"; +constexpr const char* kBorlaModelHint = "ni3hao3bo1le4"; + +} // namespace + +WakeWordDetector::~WakeWordDetector() +{ + Deinitialize(); +} + +bool WakeWordDetector::Initialize() +{ + if (handle_ != nullptr) { + return true; + } + srmodel_list_t* models = esp_srmodel_init("model"); + if (models == nullptr) { + ESP_LOGE(kTag, "model partition initialization failed"); + return false; + } + char* selected = esp_srmodel_filter( + models, ESP_WN_PREFIX, kBorlaModelHint); + if (selected == nullptr) { + selected = esp_srmodel_filter( + models, ESP_WN_PREFIX, nullptr); + } + if (selected == nullptr) { + ESP_LOGE(kTag, "no WakeNet model in model partition"); + esp_srmodel_deinit(models); + return false; + } + std::snprintf( + model_name_.data(), model_name_.size(), "%s", selected); + interface_ = esp_wn_handle_from_name(model_name_.data()); + if (interface_ == nullptr) { + ESP_LOGE(kTag, "WakeNet interface lookup failed"); + esp_srmodel_deinit(models); + return false; + } + handle_ = interface_->create( + model_name_.data(), DET_MODE_90); + esp_srmodel_deinit(models); + if (handle_ == nullptr) { + ESP_LOGE(kTag, "WakeNet instance creation failed"); + interface_ = nullptr; + return false; + } + auto* model = static_cast(handle_); + chunk_samples_ = static_cast( + interface_->get_samp_chunksize(model)); + const int sample_rate = interface_->get_samp_rate(model); + if (chunk_samples_ == 0 || sample_rate != 16000) { + ESP_LOGE(kTag, "invalid model format rate=%d chunk=%u", + sample_rate, + static_cast(chunk_samples_)); + Deinitialize(); + return false; + } + ESP_LOGI(kTag, "ready model=%s chunk=%u rate=%d", + model_name_.data(), + static_cast(chunk_samples_), + sample_rate); + return true; +} + +void WakeWordDetector::Deinitialize() +{ + if (interface_ != nullptr && handle_ != nullptr) { + interface_->destroy( + static_cast(handle_)); + } + interface_ = nullptr; + handle_ = nullptr; + chunk_samples_ = 0; +} + +bool WakeWordDetector::Detect( + const int16_t* samples, + size_t sample_count) +{ + if (interface_ == nullptr || handle_ == nullptr || + samples == nullptr || sample_count != chunk_samples_) { + return false; + } + const int result = interface_->detect( + static_cast(handle_), + const_cast(samples)); + return result > 0; +} + +} // namespace borla diff --git a/main/audio/wake_word_detector.h b/main/audio/wake_word_detector.h new file mode 100644 index 0000000..8503777 --- /dev/null +++ b/main/audio/wake_word_detector.h @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include + +#include + +namespace borla { + +class WakeWordDetector final { +public: + ~WakeWordDetector(); + + bool Initialize(); + void Deinitialize(); + bool Detect(const int16_t* samples, size_t sample_count); + bool initialized() const { return handle_ != nullptr; } + size_t ChunkSamples() const { return chunk_samples_; } + const char* ModelName() const { return model_name_.data(); } + +private: + const esp_wn_iface_t* interface_ = nullptr; + void* handle_ = nullptr; + size_t chunk_samples_ = 0; + std::array model_name_{}; +}; + +} // namespace borla diff --git a/main/configuration/remote_behavior_config.cc b/main/configuration/remote_behavior_config.cc new file mode 100644 index 0000000..b963534 --- /dev/null +++ b/main/configuration/remote_behavior_config.cc @@ -0,0 +1,212 @@ +#include "configuration/remote_behavior_config.h" + +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "RemoteBehavior2"; +constexpr const char* kButtonNamespace = "btn_cfg"; +constexpr const char* kTripleClickKey = "c3"; +constexpr const char* kQuadrupleClickKey = "c4"; +constexpr const char* kConnectionNamespace = "conn_err"; +constexpr const char* kServerPromptKey = "srv"; +constexpr const char* kNetworkPromptKey = "net"; + +template +bool ReadValue( + const char* name_space, + const char* key, + Parser parser, + Value* output) +{ + nvs_handle_t handle = 0; + const esp_err_t open = + nvs_open(name_space, NVS_READONLY, &handle); + if (open == ESP_ERR_NVS_NOT_FOUND) { + return true; + } + if (open != ESP_OK) { + return false; + } + std::array value{}; + size_t size = value.size(); + const esp_err_t read = + nvs_get_str(handle, key, value.data(), &size); + nvs_close(handle); + if (read == ESP_ERR_NVS_NOT_FOUND) { + return true; + } + if (read != ESP_OK || !parser(value.data(), output)) { + // A stored value that is missing, oversized or unparsable only means + // this one behaviour keeps its default. Reporting failure here would + // escalate to kFatalError and leave the device stuck in kFaulted. + ESP_LOGW(kTag, "ignored invalid NVS value ns=%s key=%s error=%s", + name_space, key, esp_err_to_name(read)); + return true; + } + return true; +} + +bool WriteValues( + const char* name_space, + const char* first_key, + const char* first_value, + const char* second_key, + const char* second_value) +{ + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(name_space, NVS_READWRITE, &handle); + if (result == ESP_OK && first_value != nullptr) { + result = nvs_set_str(handle, first_key, first_value); + } + if (result == ESP_OK && second_value != nullptr) { + result = nvs_set_str(handle, second_key, second_value); + } + if (result == ESP_OK) { + result = nvs_commit(handle); + } + if (handle != 0) { + nvs_close(handle); + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "NVS update failed ns=%s error=%s", + name_space, esp_err_to_name(result)); + return false; + } + return true; +} + +} // namespace + +bool NvsRemoteBehaviorConfig::Load() +{ + ButtonAction triple = ButtonAction::kFriendMode; + ButtonAction quadruple = ButtonAction::kNetworkSwitch; + LocalPrompt server = LocalPrompt::kServerError; + LocalPrompt network = LocalPrompt::kNoNetwork; + const bool valid = + ReadValue( + kButtonNamespace, + kTripleClickKey, + ParseButtonAction, + &triple) && + ReadValue( + kButtonNamespace, + kQuadrupleClickKey, + ParseButtonAction, + &quadruple) && + ReadValue( + kConnectionNamespace, + kServerPromptKey, + ParseConnectionPrompt, + &server) && + ReadValue( + kConnectionNamespace, + kNetworkPromptKey, + ParseConnectionPrompt, + &network); + triple_click_.store(triple); + quadruple_click_.store(quadruple); + server_unreachable_.store(server); + no_network_.store(network); + return valid; +} + +ButtonAction NvsRemoteBehaviorConfig::ResolveButtonAction( + uint8_t click_count) const +{ + if (click_count == 3) { + return triple_click_.load(); + } + if (click_count == 4) { + return quadruple_click_.load(); + } + return ButtonAction::kUnspecified; +} + +LocalPrompt NvsRemoteBehaviorConfig::ServerUnreachablePrompt() const +{ + return server_unreachable_.load(); +} + +LocalPrompt NvsRemoteBehaviorConfig::NoNetworkPrompt() const +{ + return no_network_.load(); +} + +bool NvsRemoteBehaviorConfig::UpdateButtonActions( + ButtonAction triple_click, + ButtonAction quadruple_click) +{ + const char* triple = triple_click == ButtonAction::kUnspecified + ? nullptr + : ToString(triple_click); + const char* quadruple = + quadruple_click == ButtonAction::kUnspecified + ? nullptr + : ToString(quadruple_click); + if (triple == nullptr && quadruple == nullptr) { + return true; + } + if (!WriteValues( + kButtonNamespace, + kTripleClickKey, + triple, + kQuadrupleClickKey, + quadruple)) { + return false; + } + if (triple != nullptr) { + triple_click_.store(triple_click); + } + if (quadruple != nullptr) { + quadruple_click_.store(quadruple_click); + } + return true; +} + +bool NvsRemoteBehaviorConfig::UpdateConnectionPrompts( + bool has_server_unreachable, + LocalPrompt server_unreachable, + bool has_no_network, + LocalPrompt no_network) +{ + if ((has_server_unreachable && + !IsAllowedConnectionPrompt(server_unreachable)) || + (has_no_network && + !IsAllowedConnectionPrompt(no_network))) { + return false; + } + const char* server = has_server_unreachable + ? ToString(server_unreachable) + : nullptr; + const char* network = has_no_network + ? ToString(no_network) + : nullptr; + if (server == nullptr && network == nullptr) { + return true; + } + if (!WriteValues( + kConnectionNamespace, + kServerPromptKey, + server, + kNetworkPromptKey, + network)) { + return false; + } + if (server != nullptr) { + server_unreachable_.store(server_unreachable); + } + if (network != nullptr) { + no_network_.store(no_network); + } + return true; +} + +} // namespace borla diff --git a/main/configuration/remote_behavior_config.h b/main/configuration/remote_behavior_config.h new file mode 100644 index 0000000..51cc760 --- /dev/null +++ b/main/configuration/remote_behavior_config.h @@ -0,0 +1,37 @@ +#pragma once + +#include "ports/remote_behavior_config.h" + +#include + +namespace borla { + +class NvsRemoteBehaviorConfig final : public IRemoteBehaviorConfig { +public: + bool Load(); + + ButtonAction ResolveButtonAction( + uint8_t click_count) const override; + LocalPrompt ServerUnreachablePrompt() const override; + LocalPrompt NoNetworkPrompt() const override; + bool UpdateButtonActions( + ButtonAction triple_click, + ButtonAction quadruple_click) override; + bool UpdateConnectionPrompts( + bool has_server_unreachable, + LocalPrompt server_unreachable, + bool has_no_network, + LocalPrompt no_network) override; + +private: + std::atomic triple_click_{ + ButtonAction::kFriendMode}; + std::atomic quadruple_click_{ + ButtonAction::kNetworkSwitch}; + std::atomic server_unreachable_{ + LocalPrompt::kServerError}; + std::atomic no_network_{ + LocalPrompt::kNoNetwork}; +}; + +} // namespace borla diff --git a/main/connectivity/cellular_transport.h b/main/connectivity/cellular_transport.h new file mode 100644 index 0000000..b85cb2f --- /dev/null +++ b/main/connectivity/cellular_transport.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +inline constexpr size_t kCellularIpv4Capacity = 16; +inline constexpr size_t kCellularImeiCapacity = 24; +inline constexpr size_t kCellularOperatorCapacity = 32; + +enum class CellularTransportEventType : uint8_t { + kStarted, + kGotIp, + kDisconnected, +}; + +struct CellularTransportEvent { + CellularTransportEventType type = CellularTransportEventType::kStarted; + uint16_t reason = 0; +}; + +struct CellularLinkInfo { + bool modem_present = false; + bool registered = false; + bool online = false; + int8_t csq = -1; + uint8_t registration_status = 0; + std::array ipv4{}; + std::array imei{}; + std::array operator_name{}; +}; + +class ICellularTransportObserver { +public: + virtual ~ICellularTransportObserver() = default; + virtual void OnCellularTransportEvent( + const CellularTransportEvent& event) = 0; +}; +//2026-9-9 ckkj add: 新增探测结果枚举,用于表示模块是否在位 +enum class CellularProbeResult : uint8_t { + kPresent, + kAbsent, + // 探测本身没能执行(如内部 RAM 不足装不下探测 UART),不代表模块不在位。 + kUnknown, +}; +class ICellularTransport { +public: + virtual ~ICellularTransport() = default; + + virtual bool Start(ICellularTransportObserver& observer) = 0; + virtual void Stop() = 0; + //virtual bool ProbePresent() = 0; + virtual CellularProbeResult ProbePresent() = 0; + virtual CellularLinkInfo GetLinkInfo() const = 0; +}; + +} // namespace borla diff --git a/main/connectivity/connectivity_manager.cc b/main/connectivity/connectivity_manager.cc new file mode 100644 index 0000000..746204d --- /dev/null +++ b/main/connectivity/connectivity_manager.cc @@ -0,0 +1,429 @@ +#include "connectivity/connectivity_manager.h" + +#include "core/playback_types.h" + +#include + +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "Connectivity2"; +constexpr uint16_t kLocalConnectRequestFailure = 0xFFFE; +//2026-9-6 ckkj add: DualNetworkTransport 主动切网断开 WiFi 的标记 reason。 +constexpr uint16_t kBearerswitchReason = 0xF101; +ConnectivityPhase ToPhase(ConnectivityPolicyState state) +{ + switch (state) { + case ConnectivityPolicyState::kStopped: + return ConnectivityPhase::kStopped; + case ConnectivityPolicyState::kCredentialsMissing: + return ConnectivityPhase::kCredentialsMissing; + case ConnectivityPolicyState::kStartingTransport: + return ConnectivityPhase::kStartingTransport; + case ConnectivityPolicyState::kConnecting: + return ConnectivityPhase::kConnecting; + case ConnectivityPolicyState::kWaitingRetry: + return ConnectivityPhase::kWaitingRetry; + case ConnectivityPolicyState::kOnline: + return ConnectivityPhase::kOnline; + } + return ConnectivityPhase::kStopped; +} + +} // namespace + +ConnectivityManager::ConnectivityManager(IWifiTransport& transport, + IWifiCredentialStore& credentials, ReconnectBackoffConfig retry_config) + : transport_(transport) + , credential_store_(credentials) + , policy_(retry_config) +{ +} + +bool ConnectivityManager::Initialize() +{ + if (initialized_) { + return true; + } + + queue_ = xQueueCreateStatic(kQueueDepth, sizeof(ManagerEvent), + queue_storage_.data(), &queue_control_); + if (queue_ == nullptr) { + ESP_LOGE(kTag, "manager queue creation failed"); + return false; + } + stop_completed_ = xSemaphoreCreateBinaryStatic(&stop_completed_control_); + if (stop_completed_ == nullptr) { + ESP_LOGE(kTag, "stop completion semaphore creation failed"); + return false; + } + + const esp_timer_create_args_t timer_args = { + .callback = &ConnectivityManager::RetryTimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "wifi_retry2", + .skip_unhandled_events = true, + }; + const esp_err_t timer_result = esp_timer_create(&timer_args, &retry_timer_); + if (timer_result != ESP_OK) { + ESP_LOGE(kTag, "retry timer creation failed: %s", + esp_err_to_name(timer_result)); + return false; + } + + const BaseType_t task_result = xTaskCreate(&ConnectivityManager::TaskEntry, + "connectivity2", task_stack_budget::kConnectivityManagerBytes, this, + kTaskPriority, &task_); + if (task_result != pdPASS) { + task_ = nullptr; + ESP_LOGE(kTag, "manager task creation failed"); + esp_timer_delete(retry_timer_); + retry_timer_ = nullptr; + return false; + } + + initialized_ = true; + ESP_LOGI(kTag, + "manager initialized queue=%u stack_bytes=%u memory=internal", + static_cast(kQueueDepth), + static_cast(task_stack_budget::kConnectivityManagerBytes)); + return true; +} + +void ConnectivityManager::Start() +{ + // 2026-9-7 ckkj add: BLE 好友模式挂起期间忽略启动请求, + // 否则重连效果会把 WiFi 驱动拉起来与 BT 控制器抢占内部 RAM。 + if (ble_suspended_.load()) { + ESP_LOGW(kTag, "start ignored: suspended for BLE friend mode"); + return; + }/////end + if (!Post({ ManagerEventType::kStart, 0 })) { + ESP_LOGE(kTag, "failed to enqueue start"); + } +} + +// 2026-9-7 ckkj add: BLE 好友模式启动前静默挂起网络。BT 控制器需要 ~65KB +// 内部 RAM,与已初始化的 WiFi 驱动无法共存:上次三击好友模式 BLE_INIT +// "Malloc failed" 后在 controller 内部 r_co_list_pop_front 直接 panic, +// 错误检查来不及执行,唯一可靠手段是启动前腾出内存。Stop() 是同步的且 +// policy_.Stop() 会经 kStopTransport → DualNetworkTransport → +// wifi_.ReleaseDriver() 拆除驱动,且不发布断开事件(静默);随后再显式 +// 兑底拆一次驱动(幂等),返回时 BLE 可用内存已就绪。 +void ConnectivityManager::SuspendForBle() +{ + bool expected = false; + if (!ble_suspended_.compare_exchange_strong(expected, true)) { + return; + } + Stop(); + transport_.ReleaseDriver(); + online_.store(false); + ESP_LOGI(kTag, "network suspended for BLE internal_free=%u largest=%u", + static_cast(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL))); +} + +// 好友模式结束(配对成功/失败/超时)后恢复正常重连。BleFriendExchange +// 在 nimble_port_deinit() 释放 BT 内存之后才回调,此处再拉起 WiFi 安全。 +void ConnectivityManager::ResumeAfterBle() +{ + bool expected = true; + if (!ble_suspended_.compare_exchange_strong(expected, false)) { + return; + } + ESP_LOGI(kTag, "network resume after BLE"); + Start(); +}/////add end + +void ConnectivityManager::Stop() +{ + if (!initialized_ || stop_completed_ == nullptr) { + return; + } + xSemaphoreTake(stop_completed_, 0); + if (!Post({ ManagerEventType::kStop, 0 })) { + ESP_LOGE(kTag, "failed to enqueue stop"); + return; + } + // Handling kStop calls DualNetworkTransport::Stop(), which itself waits up + // to 5 s for its own worker. The outer wait must outlast that, otherwise a + // slow-but-successful stop always reports a bogus timeout here. + if (xSemaphoreTake(stop_completed_, pdMS_TO_TICKS(8000)) != pdTRUE) { + ESP_LOGE(kTag, "timed out waiting for WiFi transport stop"); + } +} + +void ConnectivityManager::SwitchNetwork() +{ + if (!transport_.RequestNetworkSwitch()) { + ESP_LOGW(kTag, "active transport does not support network switch"); + } +} + +ConnectivityDiagnostics ConnectivityManager::GetDiagnostics() const +{ + portENTER_CRITICAL(&diagnostics_lock_); + const ConnectivityDiagnostics snapshot = diagnostics_; + portEXIT_CRITICAL(&diagnostics_lock_); + return snapshot; +} + +void ConnectivityManager::OnWifiTransportEvent(const WifiTransportEvent& event) +{ + ManagerEvent manager_event; + switch (event.type) { + case WifiTransportEventType::kStarted: + manager_event.type = ManagerEventType::kTransportReady; + break; + case WifiTransportEventType::kGotIp: + manager_event.type = ManagerEventType::kGotIp; + break; + case WifiTransportEventType::kDisconnected: + manager_event.type = ManagerEventType::kDisconnected; + manager_event.disconnect_reason = event.disconnect_reason; + break; + case WifiTransportEventType::kReconnectRequested: + manager_event.type = ManagerEventType::kRetryNow; + break; + case WifiTransportEventType::kCellularOn: + PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0, + static_cast(LocalPrompt::kNet4gOn), + static_cast(PlaybackPriority::kSystem))); + return; + case WifiTransportEventType::kCellularOff: + PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0, + static_cast(LocalPrompt::kNet4gOff), + static_cast(PlaybackPriority::kSystem))); + return; + case WifiTransportEventType::kCellularUnavailable: + PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0, + static_cast(LocalPrompt::kNet4gNoWifi), + static_cast(PlaybackPriority::kSystem))); + return; + case WifiTransportEventType::kCellularBootOn: + PublishAppEvent(AppEvent::Make(AppEventType::kLocalPromptRequested, 0, + static_cast(LocalPrompt::kNet4gBootOn), + static_cast(PlaybackPriority::kSystem))); + return; + } + if (!Post(manager_event)) { + ESP_LOGE(kTag, "transport event queue full type=%u", + static_cast(event.type)); + } +} + +void ConnectivityManager::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void ConnectivityManager::RetryTimerCallback(void* context) +{ + auto* self = static_cast(context); + if (!self->Post({ ManagerEventType::kRetryElapsed, 0 })) { + ESP_LOGE(kTag, "retry timer event queue full"); + } +} + +bool ConnectivityManager::Post(const ManagerEvent& event) +{ + return initialized_ && queue_ != nullptr + && xQueueSend(queue_, &event, 0) == pdTRUE; +} + +[[noreturn]] void ConnectivityManager::Run() +{ + ESP_LOGI(kTag, "manager task started"); + while (true) { + ManagerEvent event; + if (xQueueReceive(queue_, &event, portMAX_DELAY) == pdTRUE) { + Handle(event); + } + } +} + +void ConnectivityManager::Handle(const ManagerEvent& event) +{ + ConnectivityPolicyResult result; + switch (event.type) { + case ManagerEventType::kStart: + if (policy_.state() == ConnectivityPolicyState::kStopped) { + credentials_.fill(WifiCredential {}); + credential_count_ = credential_store_.Load( + credentials_.data(), credentials_.size()); + } + result = policy_.Start(credential_count_); + break; + case ManagerEventType::kStop: + result = policy_.Stop(); + break; + case ManagerEventType::kTransportReady: + result = policy_.OnTransportReady(); + break; + case ManagerEventType::kTransportStartFailed: + result = policy_.OnTransportStartFailed(esp_random()); + break; + case ManagerEventType::kGotIp: + result = policy_.OnGotIp(); + break; + case ManagerEventType::kDisconnected: + //result = policy_.OnDisconnected(event.disconnect_reason, esp_random()); + //2026-9-6 ckkj add: 0xF101 是切网动作主动断开 WiFi,非故障, + //不触发 WiFi 自动重试,避免与 4G 启动抢内部 RAM 导致 PPP UART 安装失败。 + if (event.disconnect_reason != kBearerswitchReason) { + result = policy_.OnDisconnected(event.disconnect_reason, esp_random()); + } + break; + case ManagerEventType::kRetryElapsed: + result = policy_.OnRetryElapsed(); + break; + case ManagerEventType::kRetryNow: + if (retry_timer_ != nullptr) { + const esp_err_t stop_result = esp_timer_stop(retry_timer_); + if (stop_result != ESP_OK && stop_result != ESP_ERR_INVALID_STATE) { + ESP_LOGW(kTag, "immediate retry timer cancel failed: %s", + esp_err_to_name(stop_result)); + } + } + result = policy_.OnRetryElapsed(); + break; + } + Execute(result); + RefreshDiagnostics(); + if (event.type == ManagerEventType::kStop && stop_completed_ != nullptr) { + xSemaphoreGive(stop_completed_); + } +} + +void ConnectivityManager::Execute(const ConnectivityPolicyResult& result) +{ + for (size_t index = 0; index < result.action_count; ++index) { + Execute(result.actions[index]); + } +} + +void ConnectivityManager::Execute(const ConnectivityAction& action) +{ + switch (action.type) { + case ConnectivityActionType::kStartTransport: + if (!transport_.Start(*this)) { + Post({ ManagerEventType::kTransportStartFailed, 0 }); + } + return; + case ConnectivityActionType::kStopTransport: + transport_.Stop(); + return; + case ConnectivityActionType::kConnectCredential: + if (action.credential_index >= credential_count_ + || !transport_.Connect(credentials_[action.credential_index])) { + Post({ + ManagerEventType::kDisconnected, + kLocalConnectRequestFailure, + }); + } + return; + case ConnectivityActionType::kScheduleRetry: { + if (retry_timer_ == nullptr) { + return; + } + const esp_err_t stop_result = esp_timer_stop(retry_timer_); + if (stop_result != ESP_OK && stop_result != ESP_ERR_INVALID_STATE) { + ESP_LOGW(kTag, "retry timer stop failed: %s", + esp_err_to_name(stop_result)); + } + const esp_err_t start_result = esp_timer_start_once( + retry_timer_, static_cast(action.delay_ms) * 1000ULL); + if (start_result != ESP_OK) { + ESP_LOGE(kTag, "retry timer start failed delay=%lu: %s", + static_cast(action.delay_ms), + esp_err_to_name(start_result)); + } else { + ESP_LOGI(kTag, "retry scheduled delay=%lu ms attempt=%lu", + static_cast(action.delay_ms), + static_cast(policy_.retry_attempt_count())); + } + return; + } + case ConnectivityActionType::kCancelRetry: + if (retry_timer_ != nullptr) { + const esp_err_t result = esp_timer_stop(retry_timer_); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { + ESP_LOGW(kTag, "retry timer cancel failed: %s", + esp_err_to_name(result)); + } + } + return; + case ConnectivityActionType::kPublishConnected: { + const WifiLinkInfo link = transport_.GetLinkInfo(); + ESP_LOGI(kTag, "online ssid=%s ip=%s rssi=%d channel=%u", + link.ssid.data(), link.ipv4.data(), static_cast(link.rssi_dbm), + static_cast(link.channel)); + PublishAppEvent(AppEvent::Make( + AppEventType::kNetworkConnected, 0, link.rssi_dbm, link.channel)); + return; + } + case ConnectivityActionType::kPublishDisconnected: + ESP_LOGW(kTag, "offline reason=%u", + static_cast(action.disconnect_reason)); + PublishAppEvent(AppEvent::Make( + AppEventType::kNetworkDisconnected, 0, action.disconnect_reason)); + if (remote_behavior_config_ != nullptr) { + PublishAppEvent( + AppEvent::Make(AppEventType::kLocalPromptRequested, 0, + static_cast( + remote_behavior_config_->NoNetworkPrompt()), + static_cast(PlaybackPriority::kSystem))); + } + return; + case ConnectivityActionType::kRequestProvisioning: + ESP_LOGW(kTag, "no saved WiFi credentials; provisioning requested"); + PublishAppEvent(AppEvent::Make(AppEventType::kProvisioningRequested)); + return; + } +} + +void ConnectivityManager::RefreshDiagnostics() +{ + const WifiLinkInfo link = transport_.GetLinkInfo(); + ConnectivityDiagnostics next; + next.phase = ToPhase(policy_.state()); + next.online = policy_.state() == ConnectivityPolicyState::kOnline; + next.rssi_dbm = link.rssi_dbm; + next.channel = link.channel; + next.last_disconnect_reason = policy_.last_disconnect_reason() != 0 + ? policy_.last_disconnect_reason() + : link.last_disconnect_reason; + next.retry_attempt_count = policy_.retry_attempt_count(); + next.active_credential_index = policy_.credential_index(); + next.credential_count = policy_.credential_count(); + next.ssid = link.ssid; + next.ipv4 = link.ipv4; + + portENTER_CRITICAL(&diagnostics_lock_); + diagnostics_ = next; + portEXIT_CRITICAL(&diagnostics_lock_); + online_.store(next.online); +} + +void ConnectivityManager::PublishAppEvent(const AppEvent& event) +{ + if (publisher_ == nullptr) { + ESP_LOGE( + kTag, "event publisher unavailable event=%s", ToString(event.type)); + return; + } + if (!publisher_->Publish(event)) { + ESP_LOGE( + kTag, "application event rejected event=%s", ToString(event.type)); + } +} + +} // namespace borla diff --git a/main/connectivity/connectivity_manager.h b/main/connectivity/connectivity_manager.h new file mode 100644 index 0000000..47756a7 --- /dev/null +++ b/main/connectivity/connectivity_manager.h @@ -0,0 +1,107 @@ +#pragma once + +#include "connectivity/connectivity_policy.h" +#include "connectivity/wifi_credential_store.h" +#include "connectivity/wifi_transport.h" +#include "core/task_stack_budget.h" +#include "ports/connectivity_manager.h" +#include "ports/event_publisher.h" +#include "ports/remote_behavior_config.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace borla { + +class ConnectivityManager final : public IConnectivityManager, + public IWifiTransportObserver { +public: + ConnectivityManager(IWifiTransport& transport, + IWifiCredentialStore& credentials, ReconnectBackoffConfig retry_config); + + bool Initialize(); + void SetEventPublisher(IEventPublisher* publisher) + { + publisher_ = publisher; + } + void SetRemoteBehaviorConfig(IRemoteBehaviorConfig* config) + { + remote_behavior_config_ = config; + } + + void Start() override; + void Stop() override; + void SwitchNetwork() override; + // 2026-9-7 ckkj add: BLE 好友模式前后静默挂起/恢复网络,释放 WiFi 驱动内存。 + void SuspendForBle() override; + void ResumeAfterBle() override;////////// + bool IsOnline() const override { return online_.load(); } + ConnectivityDiagnostics GetDiagnostics() const override; + + void OnWifiTransportEvent(const WifiTransportEvent& event) override; + +private: + enum class ManagerEventType : uint8_t { + kStart, + kStop, + kTransportReady, + kTransportStartFailed, + kGotIp, + kDisconnected, + kRetryElapsed, + kRetryNow, + }; + + struct ManagerEvent { + ManagerEventType type = ManagerEventType::kStart; + uint16_t disconnect_reason = 0; + }; + + static constexpr size_t kQueueDepth = 24; + static constexpr UBaseType_t kTaskPriority = 4; + + static void TaskEntry(void* context); + static void RetryTimerCallback(void* context); + + bool Post(const ManagerEvent& event); + [[noreturn]] void Run(); + void Handle(const ManagerEvent& event); + void Execute(const ConnectivityPolicyResult& result); + void Execute(const ConnectivityAction& action); + void RefreshDiagnostics(); + void PublishAppEvent(const AppEvent& event); + + IWifiTransport& transport_; + IWifiCredentialStore& credential_store_; + ConnectivityPolicy policy_; + IEventPublisher* publisher_ = nullptr; + IRemoteBehaviorConfig* remote_behavior_config_ = nullptr; + std::array credentials_ {}; + size_t credential_count_ = 0; + + QueueHandle_t queue_ = nullptr; + StaticQueue_t queue_control_ {}; + alignas(ManagerEvent) std::array queue_storage_ {}; + TaskHandle_t task_ = nullptr; + SemaphoreHandle_t stop_completed_ = nullptr; + StaticSemaphore_t stop_completed_control_ {}; + esp_timer_handle_t retry_timer_ = nullptr; + bool initialized_ = false; + + std::atomic online_ { false }; + std::atomic ble_suspended_ { false };//2026-9-7 ckkj add + mutable portMUX_TYPE diagnostics_lock_ = portMUX_INITIALIZER_UNLOCKED; + ConnectivityDiagnostics diagnostics_ {}; +}; + +} // namespace borla diff --git a/main/connectivity/connectivity_policy.cc b/main/connectivity/connectivity_policy.cc new file mode 100644 index 0000000..644187e --- /dev/null +++ b/main/connectivity/connectivity_policy.cc @@ -0,0 +1,164 @@ +#include "connectivity/connectivity_policy.h" + +namespace borla { +namespace { + +ConnectivityAction Action(ConnectivityActionType type) +{ + ConnectivityAction action; + action.type = type; + return action; +} + +} // namespace + +ConnectivityPolicy::ConnectivityPolicy(ReconnectBackoffConfig config) + : backoff_(config) +{ +} + +ConnectivityPolicyResult ConnectivityPolicy::Start(size_t credential_count) +{ + ConnectivityPolicyResult result; + if (state_ != ConnectivityPolicyState::kStopped) { + return result; + } + + credential_count_ = credential_count; + credential_index_ = 0; + last_disconnect_reason_ = 0; + transport_ready_ = false; + backoff_.Reset(); + + if (credential_count_ == 0) { + state_ = ConnectivityPolicyState::kCredentialsMissing; + result.Add(Action(ConnectivityActionType::kRequestProvisioning)); + return result; + } + + state_ = ConnectivityPolicyState::kStartingTransport; + result.Add(Action(ConnectivityActionType::kStartTransport)); + return result; +} + +ConnectivityPolicyResult ConnectivityPolicy::Stop() +{ + ConnectivityPolicyResult result; + if (state_ == ConnectivityPolicyState::kStopped) { + return result; + } + + result.Add(Action(ConnectivityActionType::kCancelRetry)); + result.Add(Action(ConnectivityActionType::kStopTransport)); + state_ = ConnectivityPolicyState::kStopped; + credential_count_ = 0; + credential_index_ = 0; + last_disconnect_reason_ = 0; + transport_ready_ = false; + backoff_.Reset(); + return result; +} + +ConnectivityPolicyResult ConnectivityPolicy::OnTransportReady() +{ + ConnectivityPolicyResult result; + if (state_ != ConnectivityPolicyState::kStartingTransport || + credential_count_ == 0) { + return result; + } + + transport_ready_ = true; + state_ = ConnectivityPolicyState::kConnecting; + ConnectivityAction connect = + Action(ConnectivityActionType::kConnectCredential); + connect.credential_index = credential_index_; + result.Add(connect); + return result; +} + +ConnectivityPolicyResult ConnectivityPolicy::OnTransportStartFailed( + uint32_t entropy) +{ + if (state_ != ConnectivityPolicyState::kStartingTransport) { + return {}; + } + transport_ready_ = false; + return ScheduleRetry(false, 0, entropy); +} + +ConnectivityPolicyResult ConnectivityPolicy::OnDisconnected( + uint16_t reason, + uint32_t entropy) +{ + if (state_ == ConnectivityPolicyState::kStopped || + state_ == ConnectivityPolicyState::kCredentialsMissing || + state_ == ConnectivityPolicyState::kWaitingRetry) { + return {}; + } + + const bool was_online = state_ == ConnectivityPolicyState::kOnline; + if (credential_count_ > 0) { + credential_index_ = (credential_index_ + 1U) % credential_count_; + } + return ScheduleRetry(was_online, reason, entropy); +} + +ConnectivityPolicyResult ConnectivityPolicy::OnRetryElapsed() +{ + ConnectivityPolicyResult result; + if (state_ != ConnectivityPolicyState::kWaitingRetry) { + return result; + } + + if (!transport_ready_) { + state_ = ConnectivityPolicyState::kStartingTransport; + result.Add(Action(ConnectivityActionType::kStartTransport)); + return result; + } + + state_ = ConnectivityPolicyState::kConnecting; + ConnectivityAction connect = + Action(ConnectivityActionType::kConnectCredential); + connect.credential_index = credential_index_; + result.Add(connect); + return result; +} + +ConnectivityPolicyResult ConnectivityPolicy::OnGotIp() +{ + ConnectivityPolicyResult result; + if (state_ != ConnectivityPolicyState::kConnecting) { + return result; + } + + state_ = ConnectivityPolicyState::kOnline; + backoff_.Reset(); + result.Add(Action(ConnectivityActionType::kCancelRetry)); + result.Add(Action(ConnectivityActionType::kPublishConnected)); + return result; +} + +ConnectivityPolicyResult ConnectivityPolicy::ScheduleRetry( + bool publish_disconnected, + uint16_t reason, + uint32_t entropy) +{ + ConnectivityPolicyResult result; + state_ = ConnectivityPolicyState::kWaitingRetry; + last_disconnect_reason_ = reason; + + if (publish_disconnected) { + ConnectivityAction disconnected = + Action(ConnectivityActionType::kPublishDisconnected); + disconnected.disconnect_reason = reason; + result.Add(disconnected); + } + + ConnectivityAction schedule = + Action(ConnectivityActionType::kScheduleRetry); + schedule.delay_ms = backoff_.NextDelayMs(entropy); + result.Add(schedule); + return result; +} + +} // namespace borla diff --git a/main/connectivity/connectivity_policy.h b/main/connectivity/connectivity_policy.h new file mode 100644 index 0000000..fa42044 --- /dev/null +++ b/main/connectivity/connectivity_policy.h @@ -0,0 +1,94 @@ +#pragma once + +#include "connectivity/reconnect_backoff.h" + +#include +#include +#include + +namespace borla { + +enum class ConnectivityPolicyState : uint8_t { + kStopped, + kCredentialsMissing, + kStartingTransport, + kConnecting, + kWaitingRetry, + kOnline, +}; + +enum class ConnectivityActionType : uint8_t { + kStartTransport, + kStopTransport, + kConnectCredential, + kScheduleRetry, + kCancelRetry, + kPublishConnected, + kPublishDisconnected, + kRequestProvisioning, +}; + +struct ConnectivityAction { + ConnectivityActionType type = ConnectivityActionType::kStartTransport; + size_t credential_index = 0; + uint32_t delay_ms = 0; + uint16_t disconnect_reason = 0; +}; + +struct ConnectivityPolicyResult { + std::array actions{}; + size_t action_count = 0; + + bool Add(const ConnectivityAction& action) + { + if (action_count >= actions.size()) { + return false; + } + actions[action_count++] = action; + return true; + } +}; + +class ConnectivityPolicy final { +public: + explicit ConnectivityPolicy( + ReconnectBackoffConfig config = ReconnectBackoffConfig{}); + + ConnectivityPolicyResult Start(size_t credential_count); + ConnectivityPolicyResult Stop(); + ConnectivityPolicyResult OnTransportReady(); + ConnectivityPolicyResult OnTransportStartFailed(uint32_t entropy); + ConnectivityPolicyResult OnDisconnected( + uint16_t reason, + uint32_t entropy); + ConnectivityPolicyResult OnRetryElapsed(); + ConnectivityPolicyResult OnGotIp(); + + ConnectivityPolicyState state() const { return state_; } + size_t credential_count() const { return credential_count_; } + size_t credential_index() const { return credential_index_; } + uint16_t last_disconnect_reason() const + { + return last_disconnect_reason_; + } + uint32_t retry_attempt_count() const + { + return backoff_.attempt_count(); + } + bool transport_ready() const { return transport_ready_; } + +private: + ConnectivityPolicyResult ScheduleRetry( + bool publish_disconnected, + uint16_t reason, + uint32_t entropy); + + ReconnectBackoff backoff_; + ConnectivityPolicyState state_ = ConnectivityPolicyState::kStopped; + size_t credential_count_ = 0; + size_t credential_index_ = 0; + uint16_t last_disconnect_reason_ = 0; + bool transport_ready_ = false; +}; + +} // namespace borla diff --git a/main/connectivity/dual_network_policy.cc b/main/connectivity/dual_network_policy.cc new file mode 100644 index 0000000..a337b1e --- /dev/null +++ b/main/connectivity/dual_network_policy.cc @@ -0,0 +1,292 @@ +#include "connectivity/dual_network_policy.h" + +namespace borla { + +DualNetworkPolicy::DualNetworkPolicy(DualNetworkPolicyConfig config) + : config_(config) +{ + if (config_.wifi_weak_sample_count == 0) { + config_.wifi_weak_sample_count = 1; + } + if (config_.modem_absent_sample_count == 0) { + config_.modem_absent_sample_count = 1; + } +} + +DualNetworkPolicyResult DualNetworkPolicy::OnModemPresence( + ModemPresence observed, + uint64_t now_ms) +{ + DualNetworkPolicyResult result; + if (!started_ || observed == ModemPresence::kUnknown) { + // An unusable probe (UART driver refused to install) must not be read + // as "the switch was turned off". + if (selected_bearer_ == NetworkBearer::kWifi && + online_bearer_ != NetworkBearer::kWifi) { + result.Add(DualNetworkActionType::kStartWifi); + }//2026-9-8 ckkj add + return result; + } + + if (stable_modem_presence_ == ModemPresence::kUnknown) { + stable_modem_presence_ = observed; + modem_absent_streak_ = 0; + if (observed == ModemPresence::kPresent) { + // Booted with the switch left on while running on WiFi: the modem + // is burning power for nothing, so say so once. + result.Add(DualNetworkActionType::kPromptCellularBootOn); + } + return result; + } + + if (observed == ModemPresence::kPresent) { + modem_absent_streak_ = 0; + if (stable_modem_presence_ != ModemPresence::kPresent) { + stable_modem_presence_ = ModemPresence::kPresent; + modem_unavailable_announced_ = false; + result.Add(DualNetworkActionType::kPromptCellularOn); + } + return result; + } + + if (stable_modem_presence_ != ModemPresence::kAbsent) { + if (modem_absent_streak_ < UINT8_MAX) { + ++modem_absent_streak_; + } + if (modem_absent_streak_ >= config_.modem_absent_sample_count) { + stable_modem_presence_ = ModemPresence::kAbsent; + modem_absent_streak_ = 0; + result.Add(DualNetworkActionType::kPromptCellularOff); + } + } + (void)now_ms; + return result; +} + +DualNetworkPolicyResult DualNetworkPolicy::NotifyWifiLostWithoutModem( + uint64_t now_ms) +{ + DualNetworkPolicyResult result; + if (!started_ || + selected_bearer_ != NetworkBearer::kWifi || + online_bearer_ == NetworkBearer::kWifi || + stable_modem_presence_ != ModemPresence::kAbsent) { + return result; + } + // Same threshold the automatic failover uses. Announcing earlier would + // fire during a normal boot (WiFi not up yet) and on every brief blip; + // this only speaks once the device would otherwise have switched to 4G + // and found the modem unpowered. + if (wifi_disconnected_since_ms_ == 0 || + now_ms < wifi_disconnected_since_ms_ || + now_ms - wifi_disconnected_since_ms_ < + config_.wifi_disconnect_failover_ms) { + return result; + } + if (modem_unavailable_announced_ && + now_ms >= modem_unavailable_announced_ms_ && + now_ms - modem_unavailable_announced_ms_ < + config_.modem_unavailable_repeat_ms) { + return result; + } + modem_unavailable_announced_ = true; + modem_unavailable_announced_ms_ = now_ms; + result.Add(DualNetworkActionType::kPromptCellularUnavailable); + return result; +} + +DualNetworkPolicyResult DualNetworkPolicy::Start( + bool has_wifi_credentials, + uint64_t now_ms) +{ + DualNetworkPolicyResult result; + if (started_) { + return result; + } + started_ = true; + selected_since_ms_ = now_ms; + if (!has_wifi_credentials) { + selected_bearer_ = NetworkBearer::kNone; + result.Add(DualNetworkActionType::kRequestProvisioning); + return result; + } + selected_bearer_ = NetworkBearer::kWifi; + result.Add(DualNetworkActionType::kStartWifi); + return result; +} + +DualNetworkPolicyResult DualNetworkPolicy::Stop() +{ + DualNetworkPolicyResult result; + if (!started_) { + return result; + } + if (selected_bearer_ == NetworkBearer::kWifi) { + result.Add(DualNetworkActionType::kStopWifi); + } else if (selected_bearer_ == NetworkBearer::kCellular) { + result.Add(DualNetworkActionType::kStopCellular); + } + started_ = false; + selected_bearer_ = NetworkBearer::kNone; + online_bearer_ = NetworkBearer::kNone; + wifi_disconnected_since_ms_ = 0; + weak_sample_count_ = 0; + stable_modem_presence_ = ModemPresence::kUnknown; + modem_absent_streak_ = 0; + modem_unavailable_announced_ = false; + modem_unavailable_announced_ms_ = 0; + return result; +} + +DualNetworkPolicyResult DualNetworkPolicy::OnWifiOnline(uint64_t now_ms) +{ + if (!started_ || selected_bearer_ != NetworkBearer::kWifi) { + return {}; + } + online_bearer_ = NetworkBearer::kWifi; + selected_since_ms_ = now_ms; + wifi_disconnected_since_ms_ = 0; + weak_sample_count_ = 0; + return {}; +} + +DualNetworkPolicyResult DualNetworkPolicy::OnWifiDisconnected( + uint64_t now_ms) +{ + if (!started_ || selected_bearer_ != NetworkBearer::kWifi) { + return {}; + } + online_bearer_ = NetworkBearer::kNone; + if (wifi_disconnected_since_ms_ == 0) { + wifi_disconnected_since_ms_ = now_ms == 0 ? 1 : now_ms; + } + weak_sample_count_ = 0; + return {}; +} + +DualNetworkPolicyResult DualNetworkPolicy::OnCellularOnline( + uint64_t now_ms) +{ + if (!started_ || selected_bearer_ != NetworkBearer::kCellular) { + return {}; + } + online_bearer_ = NetworkBearer::kCellular; + selected_since_ms_ = now_ms; + return {}; +} + +DualNetworkPolicyResult DualNetworkPolicy::OnCellularDisconnected( + uint64_t now_ms) +{ + if (!started_ || selected_bearer_ != NetworkBearer::kCellular) { + return {}; + } + online_bearer_ = NetworkBearer::kNone; + return SwitchToWifi(now_ms, false); +} + +DualNetworkPolicyResult DualNetworkPolicy::OnMonitor( + uint64_t now_ms, + int8_t wifi_rssi_dbm, + ModemPresence modem) +{ + if (!started_ || selected_bearer_ != NetworkBearer::kWifi || + modem == ModemPresence::kAbsent) { + return {}; + } + + if (online_bearer_ == NetworkBearer::kWifi) { + if (wifi_rssi_dbm != 0 && + wifi_rssi_dbm != -127 && + wifi_rssi_dbm < config_.wifi_weak_rssi_dbm) { + if (weak_sample_count_ < UINT8_MAX) { + ++weak_sample_count_; + } + } else { + weak_sample_count_ = 0; + } + if (weak_sample_count_ >= config_.wifi_weak_sample_count) { + return SwitchToCellular(now_ms, false); + } + return {}; + } + + if (wifi_disconnected_since_ms_ != 0 && + now_ms >= wifi_disconnected_since_ms_ && + now_ms - wifi_disconnected_since_ms_ >= + config_.wifi_disconnect_failover_ms) { + return SwitchToCellular(now_ms, false); + } + return {}; +} + +DualNetworkPolicyResult DualNetworkPolicy::RequestManualSwitch( + uint64_t now_ms, + ModemPresence modem) +{ + if (!started_) { + return {}; + } + if (selected_bearer_ == NetworkBearer::kCellular) { + return SwitchToWifi(now_ms, true); + } + if (modem == ModemPresence::kAbsent) { + DualNetworkPolicyResult result; + result.Add(DualNetworkActionType::kPromptCellularUnavailable); + return result; + } + return SwitchToCellular(now_ms, true); +} + +DualNetworkPolicyResult DualNetworkPolicy::SwitchToCellular( + uint64_t now_ms, + bool prompt) +{ + DualNetworkPolicyResult result; + if (selected_bearer_ == NetworkBearer::kCellular) { + return result; + } + if (online_bearer_ != NetworkBearer::kNone) { + result.Add(DualNetworkActionType::kNotifyDisconnected); + } + result.Add(DualNetworkActionType::kStopWifi); + result.Add(DualNetworkActionType::kStartCellular); + result.Add(DualNetworkActionType::kRequestReconnect); + if (prompt) { + result.Add(DualNetworkActionType::kPromptCellularOn); + } + selected_bearer_ = NetworkBearer::kCellular; + online_bearer_ = NetworkBearer::kNone; + selected_since_ms_ = now_ms; + wifi_disconnected_since_ms_ = 0; + weak_sample_count_ = 0; + return result; +} + +DualNetworkPolicyResult DualNetworkPolicy::SwitchToWifi( + uint64_t now_ms, + bool prompt) +{ + DualNetworkPolicyResult result; + if (selected_bearer_ == NetworkBearer::kWifi) { + return result; + } + if (online_bearer_ != NetworkBearer::kNone) { + result.Add(DualNetworkActionType::kNotifyDisconnected); + } + result.Add(DualNetworkActionType::kStopCellular); + result.Add(DualNetworkActionType::kStartWifi); + result.Add(DualNetworkActionType::kRequestReconnect); + if (prompt) { + result.Add(DualNetworkActionType::kPromptCellularOff); + } + selected_bearer_ = NetworkBearer::kWifi; + online_bearer_ = NetworkBearer::kNone; + selected_since_ms_ = now_ms; + wifi_disconnected_since_ms_ = now_ms == 0 ? 1 : now_ms; + weak_sample_count_ = 0; + return result; +} + +} // namespace borla + diff --git a/main/connectivity/dual_network_policy.h b/main/connectivity/dual_network_policy.h new file mode 100644 index 0000000..b5f383f --- /dev/null +++ b/main/connectivity/dual_network_policy.h @@ -0,0 +1,133 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +enum class NetworkBearer : uint8_t { + kNone, + kWifi, + kCellular, +}; + +enum class ModemPresence : uint8_t { + kUnknown, + kAbsent, + kPresent, +}; + +struct DualNetworkPolicyConfig { + uint32_t wifi_disconnect_failover_ms = 30000; + int8_t wifi_weak_rssi_dbm = -80; + uint8_t wifi_weak_sample_count = 6; + // The 4G switch cuts modem power directly, so the only way to sense it is + // whether the modem answers AT. An OFF reading needs two consecutive + // misses (UART jitter produces false absences); an ON reading is accepted + // immediately because an AT reply cannot be noise. + uint8_t modem_absent_sample_count = 2; + // Re-announce "no WiFi and 4G is off" at most this often. The WiFi monitor + // fires every few seconds while disconnected. + uint32_t modem_unavailable_repeat_ms = 120000; +}; + +enum class DualNetworkActionType : uint8_t { + kStartWifi, + kStopWifi, + kStartCellular, + kStopCellular, + kNotifyDisconnected, + kRequestReconnect, + kRequestProvisioning, + kPromptCellularOn, + kPromptCellularOff, + kPromptCellularUnavailable, + kPromptCellularBootOn, +}; + +struct DualNetworkAction { + DualNetworkActionType type = DualNetworkActionType::kStartWifi; +}; + +struct DualNetworkPolicyResult { + std::array actions{}; + size_t action_count = 0; + + bool Add(DualNetworkActionType type) + { + if (action_count >= actions.size()) { + return false; + } + actions[action_count++].type = type; + return true; + } +}; + +class DualNetworkPolicy final { +public: + explicit DualNetworkPolicy( + DualNetworkPolicyConfig config = DualNetworkPolicyConfig{}); + + DualNetworkPolicyResult Start( + bool has_wifi_credentials, + uint64_t now_ms); + DualNetworkPolicyResult Stop(); + DualNetworkPolicyResult OnWifiOnline(uint64_t now_ms); + DualNetworkPolicyResult OnWifiDisconnected(uint64_t now_ms); + DualNetworkPolicyResult OnCellularOnline(uint64_t now_ms); + DualNetworkPolicyResult OnCellularDisconnected(uint64_t now_ms); + DualNetworkPolicyResult OnMonitor( + uint64_t now_ms, + int8_t wifi_rssi_dbm, + ModemPresence modem); + DualNetworkPolicyResult RequestManualSwitch( + uint64_t now_ms, + ModemPresence modem); + + // Physical 4G switch sensing, independent of bearer selection: flipping + // the switch only announces itself, it never moves the device between + // WiFi and cellular. Fed by every modem probe while WiFi is the bearer. + // first known reading, present -> kPromptCellularBootOn + // absent -> present -> kPromptCellularOn + // present -> absent (debounced) -> kPromptCellularOff + DualNetworkPolicyResult OnModemPresence( + ModemPresence observed, + uint64_t now_ms); + + // WiFi is down and the modem is not powered: tell the parent to flip the + // switch. Rate-limited by modem_unavailable_repeat_ms. + DualNetworkPolicyResult NotifyWifiLostWithoutModem(uint64_t now_ms); + + NetworkBearer selected_bearer() const { return selected_bearer_; } + ModemPresence stable_modem_presence() const + { + return stable_modem_presence_; + } + NetworkBearer online_bearer() const { return online_bearer_; } + bool started() const { return started_; } + uint8_t weak_sample_count() const { return weak_sample_count_; } + +private: + DualNetworkPolicyResult SwitchToCellular( + uint64_t now_ms, + bool prompt); + DualNetworkPolicyResult SwitchToWifi( + uint64_t now_ms, + bool prompt); + + DualNetworkPolicyConfig config_; + NetworkBearer selected_bearer_ = NetworkBearer::kNone; + NetworkBearer online_bearer_ = NetworkBearer::kNone; + uint64_t wifi_disconnected_since_ms_ = 0; + uint64_t selected_since_ms_ = 0; + uint8_t weak_sample_count_ = 0; + bool started_ = false; + ModemPresence stable_modem_presence_ = ModemPresence::kUnknown; + uint8_t modem_absent_streak_ = 0; + uint64_t modem_unavailable_announced_ms_ = 0; + bool modem_unavailable_announced_ = false; +}; + +} // namespace borla + diff --git a/main/connectivity/dual_network_transport.cc b/main/connectivity/dual_network_transport.cc new file mode 100644 index 0000000..4c86e32 --- /dev/null +++ b/main/connectivity/dual_network_transport.cc @@ -0,0 +1,437 @@ +#include "connectivity/dual_network_transport.h" + +#include +#include + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "DualNetwork2"; +constexpr uint16_t kBearerSwitchReason = 0xF101; + +} // namespace + +DualNetworkTransport::DualNetworkTransport(IWifiTransport& wifi, + ICellularTransport& cellular, DualNetworkPolicyConfig config) + : wifi_(wifi) + , cellular_(cellular) + , config_(config) + , policy_(config) +{ +} + +bool DualNetworkTransport::Initialize() +{ + if (initialized_) { + return true; + } + queue_ = xQueueCreateStatic( + kQueueDepth, sizeof(Event), queue_storage_.data(), &queue_control_); + stop_completed_ = xSemaphoreCreateBinaryStatic(&stop_completed_control_); + if (queue_ == nullptr || stop_completed_ == nullptr) { + ESP_LOGE(kTag, "failed to allocate static control objects"); + return false; + } + + const esp_timer_create_args_t timer_args = { + .callback = &DualNetworkTransport::MonitorTimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "dual_net_mon", + .skip_unhandled_events = true, + }; + if (esp_timer_create(&timer_args, &monitor_timer_) != ESP_OK) { + ESP_LOGE(kTag, "monitor timer creation failed"); + return false; + } + + const BaseType_t task_result = xTaskCreate(&DualNetworkTransport::TaskEntry, + "dual_network2", task_stack_budget::kDualNetworkBytes, this, 4, &task_); + if (task_result != pdPASS) { + task_ = nullptr; + esp_timer_delete(monitor_timer_); + monitor_timer_ = nullptr; + return false; + } + initialized_ = true; + ESP_LOGI(kTag, "initialized queue=%u stack_bytes=%u memory=internal", + static_cast(kQueueDepth), + static_cast(task_stack_budget::kDualNetworkBytes)); + return true; +} + +bool DualNetworkTransport::Start(IWifiTransportObserver& observer) +{ + if (!initialized_ && !Initialize()) { + return false; + } + portENTER_CRITICAL(&state_lock_); + upstream_ = &observer; + portEXIT_CRITICAL(&state_lock_); + return Post({ EventType::kStart, 0, {} }); +} + +void DualNetworkTransport::Stop() +{ + if (!initialized_) { + return; + } + xSemaphoreTake(stop_completed_, 0); + if (!Post({ EventType::kStop, 0, {} })) { + return; + } + if (xSemaphoreTake(stop_completed_, pdMS_TO_TICKS(5000)) != pdTRUE) { + ESP_LOGE(kTag, "timed out stopping network transports"); + } +} +// 2026-9-7 ckkj add: 转发拆除内部 WiFi 驱动释放内部 RAM。幂等( +// EspWifiTransport 内部有 driver_initialized_ 检查),供 BLE 好友模式 +// 挂起时调用;仅在 Stop() 同步完成后调用,内部任务已空闲,无竞态。 +void DualNetworkTransport::ReleaseDriver() +{ + wifi_.ReleaseDriver(); + wifi_ready_ = false; +}//// +bool DualNetworkTransport::Connect(const WifiCredential& credential) +{ + if (!credential.IsValid()) { + return false; + } + Event event; + event.type = EventType::kConnect; + event.credential = credential; + return Post(event); +} + +bool DualNetworkTransport::Scan( + WifiNetwork* output, size_t capacity, size_t* count) +{ + return wifi_.Scan(output, capacity, count); +} + +WifiLinkInfo DualNetworkTransport::GetLinkInfo() const +{ + if (selected_bearer_.load() != NetworkBearer::kCellular) { + return wifi_.GetLinkInfo(); + } + const CellularLinkInfo cellular = cellular_.GetLinkInfo(); + WifiLinkInfo link; + link.online = cellular.online; + link.rssi_dbm = cellular.csq >= 0 && cellular.csq <= 31 + ? static_cast(-113 + (2 * cellular.csq)) + : -127; + // std::strncpy(link.ssid.data(), "cellular", link.ssid.size() - 1); + // std::strncpy(link.ipv4.data(), cellular.ipv4.data(), link.ipv4.size() - 1); + snprintf(link.ssid.data(), link.ssid.size(), "%s", "cellular"); + snprintf(link.ipv4.data(),link.ipv4.size(),"%s",reinterpret_cast(cellular.ipv4.data())); + + return link; +} + +bool DualNetworkTransport::RequestNetworkSwitch() +{ + return Post({ EventType::kManualSwitch, 0, {} }); +} + +void DualNetworkTransport::OnWifiTransportEvent(const WifiTransportEvent& event) +{ + Event converted; + switch (event.type) { + case WifiTransportEventType::kStarted: + converted.type = EventType::kWifiStarted; + break; + case WifiTransportEventType::kGotIp: + converted.type = EventType::kWifiGotIp; + break; + case WifiTransportEventType::kDisconnected: + converted.type = EventType::kWifiDisconnected; + converted.reason = event.disconnect_reason; + break; + case WifiTransportEventType::kReconnectRequested: + case WifiTransportEventType::kCellularOn: + case WifiTransportEventType::kCellularOff: + case WifiTransportEventType::kCellularUnavailable: + case WifiTransportEventType::kCellularBootOn: + return; + } + Post(converted); +} + +void DualNetworkTransport::OnCellularTransportEvent( + const CellularTransportEvent& event) +{ + Event converted; + switch (event.type) { + case CellularTransportEventType::kStarted: + converted.type = EventType::kCellularStarted; + break; + case CellularTransportEventType::kGotIp: + converted.type = EventType::kCellularGotIp; + break; + case CellularTransportEventType::kDisconnected: + converted.type = EventType::kCellularDisconnected; + converted.reason = event.reason; + break; + } + Post(converted); +} + +void DualNetworkTransport::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void DualNetworkTransport::MonitorTimerCallback(void* context) +{ + static_cast(context)->Post( + { EventType::kMonitor, 0, {} }); +} + +[[noreturn]] void DualNetworkTransport::Run() +{ + while (true) { + Event event; + if (xQueueReceive(queue_, &event, portMAX_DELAY) == pdTRUE) { + Handle(event); + } + } +} + +bool DualNetworkTransport::Post(const Event& event) +{ + return initialized_ && queue_ != nullptr + && xQueueSend(queue_, &event, 0) == pdTRUE; +} + +void DualNetworkTransport::Handle(const Event& event) +{ + const uint64_t now_ms = NowMs(); + switch (event.type) { + case EventType::kStart: + initial_started_published_ = false; + Execute(policy_.Start(true, now_ms)); + if (monitor_timer_ != nullptr) { + const esp_err_t result = esp_timer_start_periodic(monitor_timer_, + static_cast(kMonitorIntervalMs) * 1000ULL); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { + ESP_LOGW(kTag, "monitor timer start failed: %s", + esp_err_to_name(result)); + } + } + break; + case EventType::kStop: + if (monitor_timer_ != nullptr) { + const esp_err_t result = esp_timer_stop(monitor_timer_); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { + ESP_LOGW(kTag, "monitor timer stop failed: %s", + esp_err_to_name(result)); + } + } + Execute(policy_.Stop()); + pending_wifi_connect_ = false; + wifi_ready_ = false; + selected_bearer_.store(NetworkBearer::kNone); + portENTER_CRITICAL(&state_lock_); + upstream_ = nullptr; + portEXIT_CRITICAL(&state_lock_); + xSemaphoreGive(stop_completed_); + break; + case EventType::kConnect: + pending_credential_ = event.credential; + if (policy_.selected_bearer() == NetworkBearer::kWifi) { + if (wifi_ready_) { + if (!wifi_.Connect(pending_credential_)) { + PublishUpstream({ + WifiTransportEventType::kDisconnected, + 0xF102, + }); + } + } else { + pending_wifi_connect_ = true; + } + } + break; + case EventType::kWifiStarted: + wifi_ready_ = true; + if (!initial_started_published_) { + initial_started_published_ = true; + PublishUpstream({ WifiTransportEventType::kStarted, 0 }); + } + if (pending_wifi_connect_) { + pending_wifi_connect_ = false; + if (!wifi_.Connect(pending_credential_)) { + PublishUpstream({ + WifiTransportEventType::kDisconnected, + 0xF102, + }); + } + } + break; + case EventType::kWifiGotIp: + policy_.OnWifiOnline(now_ms); + selected_bearer_.store(NetworkBearer::kWifi); + PublishUpstream({ WifiTransportEventType::kGotIp, 0 }); + break; + case EventType::kWifiDisconnected: + policy_.OnWifiDisconnected(now_ms); + PublishUpstream({ + WifiTransportEventType::kDisconnected, + event.reason, + }); + break; + case EventType::kCellularStarted: + modem_presence_ = ModemPresence::kPresent; + break; + case EventType::kCellularGotIp: + policy_.OnCellularOnline(now_ms); + selected_bearer_.store(NetworkBearer::kCellular); + PublishUpstream({ WifiTransportEventType::kGotIp, 0 }); + break; + case EventType::kCellularDisconnected: + PublishUpstream({ + WifiTransportEventType::kDisconnected, + event.reason, + }); + Execute(policy_.OnCellularDisconnected(now_ms)); + break; + case EventType::kMonitor: { + const WifiLinkInfo link = wifi_.GetLinkInfo(); + if (policy_.selected_bearer() == NetworkBearer::kWifi && !link.online + && (last_modem_probe_ms_ == 0 || now_ms - last_modem_probe_ms_ >= kModemProbeIntervalMs)) + { + // Probe unconditionally (not only when WiFi is degraded): the + // 4G switch is a physical control the user can flip at any time + // and the announcement is the only feedback they get. Cadence is + // kModemProbeIntervalMs because each probe drives the AT UART. + // modem_presence_ = cellular_.ProbePresent() ? ModemPresence::kPresent + // : ModemPresence::kAbsent; + const CellularProbeResult probe = cellular_.ProbePresent(); + last_modem_probe_ms_ = now_ms; + //Execute(policy_.OnModemPresence(modem_presence_, now_ms));//2026-9-7 ckkj mod + if (probe != CellularProbeResult::kUnknown) { + modem_presence_ = probe == CellularProbeResult::kPresent + ? ModemPresence::kPresent + : ModemPresence::kAbsent; + Execute(policy_.OnModemPresence(modem_presence_, now_ms)); + } + } + // The policy owns the "long enough to matter" judgement; it uses the + // same disconnect deadline as the automatic failover. + Execute(policy_.NotifyWifiLostWithoutModem(now_ms)); + Execute(policy_.OnMonitor(now_ms, link.rssi_dbm, modem_presence_)); + break; + } + case EventType::kManualSwitch: + if (policy_.selected_bearer() == NetworkBearer::kWifi) { + // modem_presence_ = cellular_.ProbePresent() ? ModemPresence::kPresent + // : ModemPresence::kAbsent; + const CellularProbeResult probe = cellular_.ProbePresent(); + last_modem_probe_ms_ = now_ms; + // kUnknown(内存不足探测没跑成)按在位处理:切换流程先释放 WiFi + // 驱动腾出内存,真实结果由 cellular_.Start() 给出;若模块确实 + // 不在位,OnCellularDisconnected 会兜底回退 WiFi。 + modem_presence_ = probe == CellularProbeResult::kAbsent + ? ModemPresence::kAbsent + : ModemPresence::kPresent;//2026-9-9 ckkj mod + last_modem_probe_ms_ = now_ms; + } + Execute(policy_.RequestManualSwitch(now_ms, modem_presence_)); + break; + } + selected_bearer_.store(policy_.selected_bearer()); +} + +void DualNetworkTransport::Execute(const DualNetworkPolicyResult& result) +{ + for (size_t index = 0; index < result.action_count; ++index) { + Execute(result.actions[index].type); + } +} + +void DualNetworkTransport::Execute(DualNetworkActionType action) +{ + switch (action) { + case DualNetworkActionType::kStartWifi: + wifi_ready_ = false; + if (!wifi_.Start(*this)) { + PublishUpstream({ + WifiTransportEventType::kDisconnected, + 0xF103, + }); + } + return; + case DualNetworkActionType::kStopWifi: + //wifi_.Stop(); + // 2026-9-6 ckkj fix: 切 4G 时仅 Stop() 不释放 WiFi 驱动的几十 KB + // 内部 RAM,堆最大连续块被压到 ~3KB,PPP UART(4096B)永远安装失败 + // (largest=3072)。ReleaseDriver() 彻底拆除驱动释放内存, + // 4G->WiFi 回切时 Start() 会自动重建驱动(BLE 配网已验证此流程)。 + wifi_.ReleaseDriver();//// 释放 WiFi 驱动内存 + wifi_ready_ = false; + return; + case DualNetworkActionType::kStartCellular: + if (!cellular_.Start(*this)) { + Post({ EventType::kCellularDisconnected, 0xF104, {} }); + } + return; + case DualNetworkActionType::kStopCellular: + cellular_.Stop(); + return; + case DualNetworkActionType::kNotifyDisconnected: + PublishUpstream({ + WifiTransportEventType::kDisconnected, + kBearerSwitchReason, + }); + return; + case DualNetworkActionType::kRequestReconnect: + PublishUpstream({ + WifiTransportEventType::kReconnectRequested, + 0, + }); + return; + case DualNetworkActionType::kRequestProvisioning: + PublishUpstream({ + WifiTransportEventType::kDisconnected, + 0xF105, + }); + return; + case DualNetworkActionType::kPromptCellularOn: + PublishUpstream({ WifiTransportEventType::kCellularOn, 0 }); + return; + case DualNetworkActionType::kPromptCellularOff: + PublishUpstream({ WifiTransportEventType::kCellularOff, 0 }); + return; + case DualNetworkActionType::kPromptCellularUnavailable: + PublishUpstream({ + WifiTransportEventType::kCellularUnavailable, + 0, + }); + return; + case DualNetworkActionType::kPromptCellularBootOn: + PublishUpstream({ + WifiTransportEventType::kCellularBootOn, + 0, + }); + return; + } +} + +void DualNetworkTransport::PublishUpstream(const WifiTransportEvent& event) +{ + portENTER_CRITICAL(&state_lock_); + IWifiTransportObserver* const observer = upstream_; + portEXIT_CRITICAL(&state_lock_); + if (observer != nullptr) { + observer->OnWifiTransportEvent(event); + } +} + +uint64_t DualNetworkTransport::NowMs() const +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace borla diff --git a/main/connectivity/dual_network_transport.h b/main/connectivity/dual_network_transport.h new file mode 100644 index 0000000..93a78da --- /dev/null +++ b/main/connectivity/dual_network_transport.h @@ -0,0 +1,104 @@ +#pragma once + +#include "connectivity/cellular_transport.h" +#include "connectivity/dual_network_policy.h" +#include "connectivity/wifi_transport.h" +#include "core/task_stack_budget.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace borla { + +class DualNetworkTransport final : public IWifiTransport, + public IWifiTransportObserver, + public ICellularTransportObserver { +public: + DualNetworkTransport(IWifiTransport& wifi, ICellularTransport& cellular, + DualNetworkPolicyConfig config); + + bool Initialize(); + bool Start(IWifiTransportObserver& observer) override; + void Stop() override; + // 2026-9-7 ckkj add: 彻底拆除内部 WiFi 驱动释放内部 RAM(BLE 好友模式 + // 挂起时由 ConnectivityManager 调用);不发布事件,下一步 Start() 重建驱动。 + void ReleaseDriver() override;//// + bool Connect(const WifiCredential& credential) override; + bool Scan(WifiNetwork* output, size_t capacity, size_t* count) override; + WifiLinkInfo GetLinkInfo() const override; + bool RequestNetworkSwitch() override; + + void OnWifiTransportEvent(const WifiTransportEvent& event) override; + void OnCellularTransportEvent(const CellularTransportEvent& event) override; + + NetworkBearer SelectedBearer() const { return selected_bearer_.load(); } + +private: + enum class EventType : uint8_t { + kStart, + kStop, + kConnect, + kWifiStarted, + kWifiGotIp, + kWifiDisconnected, + kCellularStarted, + kCellularGotIp, + kCellularDisconnected, + kMonitor, + kManualSwitch, + }; + + struct Event { + EventType type = EventType::kStart; + uint16_t reason = 0; + WifiCredential credential {}; + }; + + static constexpr size_t kQueueDepth = 20; + static constexpr uint32_t kMonitorIntervalMs = 5000; + static constexpr uint32_t kModemProbeIntervalMs = 30000; + + static void TaskEntry(void* context); + static void MonitorTimerCallback(void* context); + [[noreturn]] void Run(); + bool Post(const Event& event); + void Handle(const Event& event); + void Execute(const DualNetworkPolicyResult& result); + void Execute(DualNetworkActionType action); + void PublishUpstream(const WifiTransportEvent& event); + uint64_t NowMs() const; + + IWifiTransport& wifi_; + ICellularTransport& cellular_; + DualNetworkPolicyConfig config_; + DualNetworkPolicy policy_; + + mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED; + IWifiTransportObserver* upstream_ = nullptr; + WifiCredential pending_credential_ {}; + bool pending_wifi_connect_ = false; + bool wifi_ready_ = false; + bool initial_started_published_ = false; + ModemPresence modem_presence_ = ModemPresence::kUnknown; + uint64_t last_modem_probe_ms_ = 0; + + QueueHandle_t queue_ = nullptr; + StaticQueue_t queue_control_ {}; + alignas(Event) + std::array queue_storage_ {}; + TaskHandle_t task_ = nullptr; + SemaphoreHandle_t stop_completed_ = nullptr; + StaticSemaphore_t stop_completed_control_ {}; + esp_timer_handle_t monitor_timer_ = nullptr; + bool initialized_ = false; + std::atomic selected_bearer_ { NetworkBearer::kNone }; +}; + +} // namespace borla diff --git a/main/connectivity/ml307_at_parser.cc b/main/connectivity/ml307_at_parser.cc new file mode 100644 index 0000000..32e9eee --- /dev/null +++ b/main/connectivity/ml307_at_parser.cc @@ -0,0 +1,90 @@ +#include "connectivity/ml307_at_parser.h" + +#include +#include + +namespace borla { + +bool ParseMl307Registration( + const char* response, + CellularRegistration* registration) +{ + if (response == nullptr || registration == nullptr) { + return false; + } + const char* marker = std::strstr(response, "+CEREG:"); + if (marker == nullptr) { + return false; + } + unsigned mode = 0; + unsigned status = 0; + const int fields = + std::sscanf(marker, "+CEREG: %u,%u", &mode, &status); + if (fields == 1) { + status = mode; + mode = 0; + } else if (fields != 2) { + return false; + } + if (mode > UINT8_MAX || status > UINT8_MAX) { + return false; + } + registration->mode = static_cast(mode); + registration->status = static_cast(status); + return true; +} + +bool ParseMl307SignalQuality(const char* response, int8_t* csq) +{ + if (response == nullptr || csq == nullptr) { + return false; + } + const char* marker = std::strstr(response, "+CSQ:"); + if (marker == nullptr) { + return false; + } + int value = -1; + if (std::sscanf(marker, "+CSQ: %d", &value) != 1 || + !((value >= 0 && value <= 31) || value == 99)) { + return false; + } + *csq = value == 99 ? -1 : static_cast(value); + return true; +} + +bool CopyMl307ResponseLine( + const char* response, + const char* prefix, + char* output, + size_t output_capacity) +{ + if (response == nullptr || prefix == nullptr || output == nullptr || + output_capacity == 0) { + return false; + } + const char* begin = + prefix[0] == '\0' ? response : std::strstr(response, prefix); + if (begin == nullptr) { + return false; + } + begin += std::strlen(prefix); + while (*begin == ' ' || *begin == ':' || *begin == '"' || + *begin == '\r' || *begin == '\n') { + ++begin; + } + const char* end = begin; + while (*end != '\0' && *end != '\r' && *end != '\n' && + *end != '"') { + ++end; + } + const size_t size = static_cast(end - begin); + if (size == 0 || size >= output_capacity) { + return false; + } + std::memset(output, 0, output_capacity); + std::memcpy(output, begin, size); + return true; +} + +} // namespace borla + diff --git a/main/connectivity/ml307_at_parser.h b/main/connectivity/ml307_at_parser.h new file mode 100644 index 0000000..27d698c --- /dev/null +++ b/main/connectivity/ml307_at_parser.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +namespace borla { + +struct CellularRegistration { + uint8_t mode = 0; + uint8_t status = 0; + + bool IsRegistered() const + { + return status == 1 || status == 5; + } +}; + +bool ParseMl307Registration( + const char* response, + CellularRegistration* registration); +bool ParseMl307SignalQuality( + const char* response, + int8_t* csq); +bool CopyMl307ResponseLine( + const char* response, + const char* prefix, + char* output, + size_t output_capacity); + +} // namespace borla + diff --git a/main/connectivity/reconnect_backoff.cc b/main/connectivity/reconnect_backoff.cc new file mode 100644 index 0000000..e505285 --- /dev/null +++ b/main/connectivity/reconnect_backoff.cc @@ -0,0 +1,62 @@ +#include "connectivity/reconnect_backoff.h" + +#include +#include +#include + +namespace borla { + +ReconnectBackoff::ReconnectBackoff(ReconnectBackoffConfig config) + : config_(Normalize(config)) +{ +} + +uint32_t ReconnectBackoff::NextDelayMs(uint32_t entropy) +{ + if (current_base_delay_ms_ == 0) { + current_base_delay_ms_ = config_.initial_delay_ms; + } else { + const uint64_t multiplied = + static_cast(current_base_delay_ms_) * + config_.multiplier; + current_base_delay_ms_ = static_cast( + std::min(multiplied, config_.maximum_delay_ms)); + } + ++attempt_count_; + + const uint32_t jitter_range = static_cast( + (static_cast(current_base_delay_ms_) * + config_.jitter_percent) / + 100U); + if (jitter_range == 0) { + return current_base_delay_ms_; + } + + const uint64_t bucket_count = + static_cast(jitter_range) * 2U + 1U; + const int64_t offset = + static_cast(entropy % bucket_count) - + static_cast(jitter_range); + const int64_t jittered = + static_cast(current_base_delay_ms_) + offset; + return static_cast(std::max(1, jittered)); +} + +void ReconnectBackoff::Reset() +{ + current_base_delay_ms_ = 0; + attempt_count_ = 0; +} + +ReconnectBackoffConfig ReconnectBackoff::Normalize( + ReconnectBackoffConfig config) +{ + config.initial_delay_ms = std::max(1, config.initial_delay_ms); + config.maximum_delay_ms = + std::max(config.initial_delay_ms, config.maximum_delay_ms); + config.multiplier = std::max(1, config.multiplier); + config.jitter_percent = std::min(50, config.jitter_percent); + return config; +} + +} // namespace borla diff --git a/main/connectivity/reconnect_backoff.h b/main/connectivity/reconnect_backoff.h new file mode 100644 index 0000000..f44f88a --- /dev/null +++ b/main/connectivity/reconnect_backoff.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +namespace borla { + +struct ReconnectBackoffConfig { + uint32_t initial_delay_ms = 1000; + uint32_t maximum_delay_ms = 60000; + uint8_t multiplier = 2; + uint8_t jitter_percent = 20; +}; + +class ReconnectBackoff final { +public: + explicit ReconnectBackoff( + ReconnectBackoffConfig config = ReconnectBackoffConfig{}); + + uint32_t NextDelayMs(uint32_t entropy); + void Reset(); + + uint32_t attempt_count() const { return attempt_count_; } + uint32_t current_base_delay_ms() const { return current_base_delay_ms_; } + const ReconnectBackoffConfig& config() const { return config_; } + +private: + static ReconnectBackoffConfig Normalize( + ReconnectBackoffConfig config); + + ReconnectBackoffConfig config_; + uint32_t current_base_delay_ms_ = 0; + uint32_t attempt_count_ = 0; +}; + +} // namespace borla diff --git a/main/connectivity/wifi_credential_store.cc b/main/connectivity/wifi_credential_store.cc new file mode 100644 index 0000000..d71400c --- /dev/null +++ b/main/connectivity/wifi_credential_store.cc @@ -0,0 +1,229 @@ +#include "connectivity/wifi_credential_store.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "WifiCredentials2"; +constexpr const char* kNvsNamespace = "wifi"; + +void MakeKey(const char* prefix, size_t index, char* output, size_t size) +{ + if (index == 0) { + std::snprintf(output, size, "%s", prefix); + } else { + std::snprintf(output, size, "%s%u", prefix, + static_cast(index)); + } +} + +bool SameSsid(const WifiCredential& credential, const char* ssid) +{ + return ssid != nullptr && + std::strncmp( + credential.ssid.data(), ssid, credential.ssid.size()) == 0; +} + +} // namespace + +size_t NvsWifiCredentialStore::Load( + WifiCredential* output, + size_t capacity) const +{ + if (output == nullptr || capacity == 0) { + return 0; + } + + nvs_handle_t handle = 0; + const esp_err_t open_result = + nvs_open(kNvsNamespace, NVS_READONLY, &handle); + if (open_result == ESP_ERR_NVS_NOT_FOUND) { + return 0; + } + if (open_result != ESP_OK) { + ESP_LOGE(kTag, "open namespace failed: %s", + esp_err_to_name(open_result)); + return 0; + } + + size_t count = 0; + for (size_t index = 0; + index < kMaxSavedWifiCredentials && count < capacity; + ++index) { + char ssid_key[16]{}; + char password_key[16]{}; + MakeKey("ssid", index, ssid_key, sizeof(ssid_key)); + MakeKey("password", index, password_key, sizeof(password_key)); + + WifiCredential credential; + size_t ssid_size = credential.ssid.size(); + size_t password_size = credential.password.size(); + if (nvs_get_str( + handle, ssid_key, credential.ssid.data(), &ssid_size) != + ESP_OK) { + continue; + } + if (nvs_get_str( + handle, password_key, credential.password.data(), + &password_size) != ESP_OK) { + continue; + } + if (!credential.IsValid()) { + ESP_LOGW(kTag, "ignored invalid credential slot=%u", + static_cast(index)); + continue; + } + output[count++] = credential; + } + + nvs_close(handle); + ESP_LOGI(kTag, "loaded %u saved WiFi credential(s)", + static_cast(count)); + return count; +} + +bool NvsWifiCredentialStore::SaveAndPromote( + const WifiCredential& credential) +{ + if (!credential.IsValid()) { + ESP_LOGE(kTag, "refused invalid WiFi credential"); + return false; + } + + std::array credentials{}; + size_t count = Load(credentials.data(), credentials.size()); + size_t existing = count; + for (size_t index = 0; index < count; ++index) { + if (SameSsid(credentials[index], credential.ssid.data())) { + existing = index; + break; + } + } + + if (existing < count) { + for (size_t index = existing; index > 0; --index) { + credentials[index] = credentials[index - 1]; + } + } else { + count = std::min(count + 1U, credentials.size()); + for (size_t index = count - 1; index > 0; --index) { + credentials[index] = credentials[index - 1]; + } + } + credentials[0] = credential; + + if (!SaveAll(credentials.data(), count)) { + return false; + } + ESP_LOGI(kTag, "saved WiFi credential ssid=%s", + credential.ssid.data()); + return true; +} + +bool NvsWifiCredentialStore::Remove(const char* ssid) +{ + if (ssid == nullptr || ssid[0] == '\0') { + return false; + } + + std::array credentials{}; + size_t count = Load(credentials.data(), credentials.size()); + size_t remove_index = count; + for (size_t index = 0; index < count; ++index) { + if (SameSsid(credentials[index], ssid)) { + remove_index = index; + break; + } + } + if (remove_index == count) { + return false; + } + + for (size_t index = remove_index; index + 1 < count; ++index) { + credentials[index] = credentials[index + 1]; + } + --count; + if (!SaveAll(credentials.data(), count)) { + return false; + } + ESP_LOGI(kTag, "removed WiFi credential ssid=%s", ssid); + return true; +} + +bool NvsWifiCredentialStore::Clear() +{ + return SaveAll(nullptr, 0); +} + +bool NvsWifiCredentialStore::SaveAll( + const WifiCredential* credentials, + size_t count) const +{ + if ((credentials == nullptr && count != 0) || + count > kMaxSavedWifiCredentials) { + return false; + } + + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNvsNamespace, NVS_READWRITE, &handle); + if (result != ESP_OK) { + ESP_LOGE(kTag, "open writable namespace failed: %s", + esp_err_to_name(result)); + return false; + } + + for (size_t index = 0; index < kMaxSavedWifiCredentials; ++index) { + char ssid_key[16]{}; + char password_key[16]{}; + MakeKey("ssid", index, ssid_key, sizeof(ssid_key)); + MakeKey("password", index, password_key, sizeof(password_key)); + if (index < count) { + result = nvs_set_str( + handle, ssid_key, credentials[index].ssid.data()); + if (result == ESP_OK) { + result = nvs_set_str( + handle, password_key, + credentials[index].password.data()); + } + } else { + const esp_err_t ssid_result = nvs_erase_key(handle, ssid_key); + const esp_err_t password_result = + nvs_erase_key(handle, password_key); + if (ssid_result != ESP_OK && + ssid_result != ESP_ERR_NVS_NOT_FOUND) { + result = ssid_result; + } + if (password_result != ESP_OK && + password_result != ESP_ERR_NVS_NOT_FOUND) { + result = password_result; + } + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "write credential slot=%u failed: %s", + static_cast(index), + esp_err_to_name(result)); + nvs_close(handle); + return false; + } + } + + result = nvs_commit(handle); + nvs_close(handle); + if (result != ESP_OK) { + ESP_LOGE(kTag, "commit credentials failed: %s", + esp_err_to_name(result)); + return false; + } + return true; +} + +} // namespace borla diff --git a/main/connectivity/wifi_credential_store.h b/main/connectivity/wifi_credential_store.h new file mode 100644 index 0000000..0482048 --- /dev/null +++ b/main/connectivity/wifi_credential_store.h @@ -0,0 +1,32 @@ +#pragma once + +#include "connectivity/wifi_types.h" + +#include + +namespace borla { + +class IWifiCredentialStore { +public: + virtual ~IWifiCredentialStore() = default; + + virtual size_t Load(WifiCredential* output, size_t capacity) const = 0; + virtual bool SaveAndPromote(const WifiCredential& credential) = 0; + virtual bool Remove(const char* ssid) = 0; + virtual bool Clear() = 0; +}; + +class NvsWifiCredentialStore final : public IWifiCredentialStore { +public: + size_t Load(WifiCredential* output, size_t capacity) const override; + bool SaveAndPromote(const WifiCredential& credential) override; + bool Remove(const char* ssid) override; + bool Clear() override; + +private: + bool SaveAll( + const WifiCredential* credentials, + size_t count) const; +}; + +} // namespace borla diff --git a/main/connectivity/wifi_transport.h b/main/connectivity/wifi_transport.h new file mode 100644 index 0000000..7489420 --- /dev/null +++ b/main/connectivity/wifi_transport.h @@ -0,0 +1,69 @@ +#pragma once + +#include "connectivity/wifi_types.h" + +#include +#include + +namespace borla { + +enum class WifiTransportEventType : uint8_t { + kStarted, + kGotIp, + kDisconnected, + kReconnectRequested, + kCellularOn, + kCellularOff, + kCellularUnavailable, + kCellularBootOn, +}; + +struct WifiTransportEvent { + WifiTransportEventType type = WifiTransportEventType::kStarted; + uint16_t disconnect_reason = 0; +}; + +class IWifiTransportObserver { +public: + virtual ~IWifiTransportObserver() = default; + virtual void OnWifiTransportEvent( + const WifiTransportEvent& event) = 0; +}; + +class IWifiTransport { +public: + virtual ~IWifiTransport() = default; + + virtual bool Start(IWifiTransportObserver& observer) = 0; + virtual void Stop() = 0; + // Stop() only halts the driver; it keeps tens of KB of internal RAM in + // static/dynamic packet buffers. ReleaseDriver() tears the driver all the + // way down so that memory is available to something else — currently the + // BLE controller, which needs ~65 KB internal and cannot coexist with an + // idle-but-initialised WiFi driver on this board. The next Start() brings + // the driver back up. Default is a no-op for transports without one. + virtual void ReleaseDriver() {} + // Selects a trimmed buffer configuration for the next InitializeDriver(). + // + // The default profile wants ~36 KB of internal RAM, most of it 10 static + // 1600-byte RX buffers. That is unaffordable in exactly one place: BLE + // provisioning, where the BT controller already holds ~53 KB and the + // driver has to come back up to test the credential the phone just sent. + // Field log: free=44287 at that moment, esp_wifi_init consumed 34 KB and + // then failed on the tenth RX buffer with ESP_ERR_NO_MEM, so the app + // reported "connection failed" on a perfectly good password. + // + // That link only has to associate and pull a DHCP lease before the driver + // is stopped again and the phone reboots the device, so throughput is + // irrelevant there. Everywhere else the default profile stays. + virtual void UseLowMemoryProfile(bool enabled) { (void)enabled; } + virtual bool Connect(const WifiCredential& credential) = 0; + virtual bool Scan( + WifiNetwork* output, + size_t capacity, + size_t* count) = 0; + virtual WifiLinkInfo GetLinkInfo() const = 0; + virtual bool RequestNetworkSwitch() { return false; } +}; + +} // namespace borla diff --git a/main/connectivity/wifi_types.h b/main/connectivity/wifi_types.h new file mode 100644 index 0000000..f156cc0 --- /dev/null +++ b/main/connectivity/wifi_types.h @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include + +namespace borla { + +inline constexpr size_t kWifiSsidCapacity = 33; +inline constexpr size_t kWifiPasswordCapacity = 65; +inline constexpr size_t kWifiIpv4Capacity = 16; +inline constexpr size_t kMaxSavedWifiCredentials = 10; +inline constexpr size_t kMaxProvisioningScanResults = 20; + +inline size_t BoundedStringLength(const char* value, size_t capacity) +{ + if (value == nullptr) { + return capacity; + } + size_t length = 0; + while (length < capacity && value[length] != '\0') { + ++length; + } + return length; +} + +struct WifiCredential { + std::array ssid{}; + std::array password{}; + + bool Set(const char* new_ssid, const char* new_password) + { + if (new_ssid == nullptr || new_password == nullptr) { + return false; + } + + const size_t ssid_length = + BoundedStringLength(new_ssid, kWifiSsidCapacity); + const size_t password_length = + BoundedStringLength(new_password, kWifiPasswordCapacity); + if (ssid_length == 0 || ssid_length >= kWifiSsidCapacity || + password_length >= kWifiPasswordCapacity) { + return false; + } + + ssid.fill('\0'); + password.fill('\0'); + std::memcpy(ssid.data(), new_ssid, ssid_length); + std::memcpy(password.data(), new_password, password_length); + return true; + } + + bool IsValid() const + { + return ssid[0] != '\0' && + BoundedStringLength(ssid.data(), ssid.size()) < ssid.size() && + BoundedStringLength(password.data(), password.size()) < + password.size(); + } +}; + +struct WifiLinkInfo { + bool online = false; + int8_t rssi_dbm = -127; + uint8_t channel = 0; + uint16_t last_disconnect_reason = 0; + std::array ssid{}; + std::array ipv4{}; +}; + +struct WifiNetwork { + std::array ssid{}; + int8_t rssi_dbm = -127; + uint8_t auth_mode = 0; +}; + +} // namespace borla diff --git a/main/core/app_effect.cc b/main/core/app_effect.cc new file mode 100644 index 0000000..ef10b10 --- /dev/null +++ b/main/core/app_effect.cc @@ -0,0 +1,90 @@ +#include "core/app_effect.h" + +namespace borla { + +const char* ToString(AppEffectType type) +{ + switch (type) { + case AppEffectType::kStartAudio: + return "start_audio"; + case AppEffectType::kStopAudio: + return "stop_audio"; + case AppEffectType::kStartConnectivity: + return "start_connectivity"; + case AppEffectType::kStopConnectivity: + return "stop_connectivity"; + case AppEffectType::kSwitchNetwork: + return "switch_network"; + case AppEffectType::kOpenRealtime: + return "open_realtime"; + case AppEffectType::kCloseRealtime: + return "close_realtime"; + case AppEffectType::kSendStartListening: + return "send_start_listening"; + case AppEffectType::kSendStopListening: + return "send_stop_listening"; + case AppEffectType::kSendAbortSpeaking: + return "send_abort_speaking"; + case AppEffectType::kSendGoodbye: + return "send_goodbye"; + case AppEffectType::kSendAcceptCall: + return "send_accept_call"; + case AppEffectType::kSendHangupCall: + return "send_hangup_call"; + case AppEffectType::kSendButtonClick: + return "send_button_click"; + case AppEffectType::kSendLocalPlaybackStarted: + return "send_local_playback_started"; + case AppEffectType::kSendLocalPlaybackDone: + return "send_local_playback_done"; + case AppEffectType::kBeginRemotePlayback: + return "begin_remote_playback"; + case AppEffectType::kEndPlaybackInput: + return "end_playback_input"; + case AppEffectType::kPlayLocalPrompt: + return "play_local_prompt"; + case AppEffectType::kPlayDetachedPrompt: + return "play_detached_prompt"; + case AppEffectType::kApplyAudioPolicy: + return "apply_audio_policy"; + case AppEffectType::kSetAudioVolume: + return "set_audio_volume"; + case AppEffectType::kSetWakeWordEnabled: + return "set_wake_word_enabled"; + case AppEffectType::kSetBargeInEnabled: + return "set_barge_in_enabled"; + case AppEffectType::kPausePlayback: + return "pause_playback"; + case AppEffectType::kResumePlayback: + return "resume_playback"; + case AppEffectType::kCancelPlayback: + return "cancel_playback"; + case AppEffectType::kSetLed: + return "set_led"; + case AppEffectType::kShowTemporaryLedAlert: + return "show_temporary_led_alert"; + case AppEffectType::kStartFriendMode: + return "start_friend_mode"; + case AppEffectType::kStopFriendMode: + return "stop_friend_mode"; + case AppEffectType::kEnterProvisioning: + return "enter_provisioning"; + case AppEffectType::kStartUpgrade: + return "start_upgrade"; + case AppEffectType::kReboot: + return "reboot"; + case AppEffectType::kEnterSoftOff: + return "enter_soft_off"; + case AppEffectType::kStartAlert: + return "start_alert"; + case AppEffectType::kStopAlert: + return "stop_alert"; + case AppEffectType::kRequestConnectionErrorPrompt: + return "request_connection_error_prompt"; + case AppEffectType::kReportError: + return "report_error"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/core/app_effect.h b/main/core/app_effect.h new file mode 100644 index 0000000..25e72e6 --- /dev/null +++ b/main/core/app_effect.h @@ -0,0 +1,172 @@ +#pragma once + +#include "core/playback_types.h" +#include "core/runtime_state.h" + +#include +#include +#include + +namespace borla { + +enum class AppEffectType : uint8_t { + kStartAudio, + kStopAudio, + kStartConnectivity, + kStopConnectivity, + kSwitchNetwork, + kOpenRealtime, + kCloseRealtime, + kSendStartListening, + kSendStopListening, + kSendAbortSpeaking, + kSendGoodbye, + kSendAcceptCall, + kSendHangupCall, + kSendButtonClick, + kSendLocalPlaybackStarted, + kSendLocalPlaybackDone, + kBeginRemotePlayback, + kEndPlaybackInput, + kPlayLocalPrompt, + kPlayDetachedPrompt, + kApplyAudioPolicy, + kSetAudioVolume, + kSetWakeWordEnabled, + kSetBargeInEnabled, + kPausePlayback, + kResumePlayback, + kCancelPlayback, + kSetLed, + kShowTemporaryLedAlert, + kStartFriendMode, + kStopFriendMode, + kEnterProvisioning, + kStartUpgrade, + kReboot, + kEnterSoftOff, + kStartAlert, + kStopAlert, + kRequestConnectionErrorPrompt, + kReportError, +}; + +struct AppEffect { + AppEffectType type = AppEffectType::kReportError; + uint32_t correlation_id = 0; + AudioPolicy audio_policy = AudioPolicy::kOff; + LedPattern led_pattern = LedPattern::kOff; + PlaybackPriority playback_priority = PlaybackPriority::kConversation; + ConversationInterruptSource interrupt_source = + ConversationInterruptSource::kUserInitiated; + LocalPrompt local_prompt = LocalPrompt::kBoot; + int16_t prompt_selector = -1; + AlertKind alert_kind = AlertKind::kReminder; + + static AppEffect Simple(AppEffectType type, uint32_t correlation_id = 0) + { + AppEffect effect; + effect.type = type; + effect.correlation_id = correlation_id; + return effect; + } + + static AppEffect Audio(AudioPolicy policy) + { + AppEffect effect; + effect.type = AppEffectType::kApplyAudioPolicy; + effect.audio_policy = policy; + return effect; + } + + static AppEffect Abort(ConversationInterruptSource source) + { + AppEffect effect; + effect.type = AppEffectType::kSendAbortSpeaking; + effect.interrupt_source = source; + return effect; + } + + static AppEffect Led(LedPattern pattern) + { + AppEffect effect; + effect.type = AppEffectType::kSetLed; + effect.led_pattern = pattern; + return effect; + } + + static AppEffect RemotePlayback( + AppEffectType type, + PlaybackSessionId session_id, + PlaybackPriority priority = PlaybackPriority::kConversation) + { + AppEffect effect; + effect.type = type; + effect.correlation_id = session_id; + effect.playback_priority = priority; + return effect; + } + + static AppEffect Prompt( + LocalPrompt prompt, + PlaybackPriority priority = PlaybackPriority::kLocalPrompt, + int16_t selector = -1) + { + AppEffect effect; + effect.type = AppEffectType::kPlayLocalPrompt; + effect.local_prompt = prompt; + effect.playback_priority = priority; + effect.prompt_selector = selector; + return effect; + } + + static AppEffect DetachedPrompt( + LocalPrompt prompt, + PlaybackPriority priority = PlaybackPriority::kLocalPrompt) + { + AppEffect effect; + effect.type = AppEffectType::kPlayDetachedPrompt; + effect.local_prompt = prompt; + effect.playback_priority = priority; + return effect; + } + + static AppEffect LocalPlaybackState( + AppEffectType type, + LocalPrompt prompt) + { + AppEffect effect; + effect.type = type; + effect.local_prompt = prompt; + return effect; + } + + static AppEffect Alert(AlertKind kind) + { + AppEffect effect; + effect.type = AppEffectType::kStartAlert; + effect.alert_kind = kind; + return effect; + } +}; + +constexpr size_t kMaxEffectsPerTransition = 10; + +struct TransitionResult { + RuntimeState next; + std::array effects{}; + size_t effect_count = 0; + + bool AddEffect(const AppEffect& effect) + { + if (effect_count >= effects.size()) { + return false; + } + effects[effect_count++] = effect; + return true; + } +}; + +const char* ToString(AppEffectType type); + +} // namespace borla diff --git a/main/core/app_event.cc b/main/core/app_event.cc new file mode 100644 index 0000000..cf16d9e --- /dev/null +++ b/main/core/app_event.cc @@ -0,0 +1,116 @@ +#include "core/app_event.h" + +namespace borla { + +const char* ToString(AppEventType type) +{ + switch (type) { + case AppEventType::kBootRequested: + return "boot_requested"; + case AppEventType::kNetworkConnected: + return "network_connected"; + case AppEventType::kNetworkDisconnected: + return "network_disconnected"; + case AppEventType::kRealtimeConnected: + return "realtime_connected"; + case AppEventType::kRealtimeDisconnected: + return "realtime_disconnected"; + case AppEventType::kRealtimeProtocolError: + return "realtime_protocol_error"; + case AppEventType::kButtonClicked: + return "button_clicked"; + case AppEventType::kButtonLongPressed: + return "button_long_pressed"; + case AppEventType::kAudioVolumeRequested: + return "audio_volume_requested"; + case AppEventType::kWakeWordControlRequested: + return "wake_word_control_requested"; + case AppEventType::kBargeInControlRequested: + return "barge_in_control_requested"; + case AppEventType::kRemoteIdleSleepRequested: + return "remote_idle_sleep_requested"; + case AppEventType::kLedAlertRequested: + return "led_alert_requested"; + case AppEventType::kWakeWordDetected: + return "wake_word_detected"; + case AppEventType::kBargeInCandidate: + return "barge_in_candidate"; + case AppEventType::kBargeInRejected: + return "barge_in_rejected"; + case AppEventType::kBargeInConfirmed: + return "barge_in_confirmed"; + case AppEventType::kConversationStopRequested: + return "conversation_stop_requested"; + case AppEventType::kTtsStarted: + return "tts_started"; + case AppEventType::kTtsStreamEnded: + return "tts_stream_ended"; + case AppEventType::kPlaybackPreempted: + return "playback_preempted"; + case AppEventType::kPlaybackDrained: + return "playback_drained"; + case AppEventType::kPlaybackFailed: + return "playback_failed"; + case AppEventType::kLocalPromptRequested: + return "local_prompt_requested"; + case AppEventType::kLocalPromptStarted: + return "local_prompt_started"; + case AppEventType::kLocalSequenceRequested: + return "local_sequence_requested"; + case AppEventType::kLocalSequenceStarted: + return "local_sequence_started"; + case AppEventType::kActivationReplayDue: + return "activation_replay_due"; + case AppEventType::kShutdownPromptRequested: + return "shutdown_prompt_requested"; + case AppEventType::kUserActivityDetected: + return "user_activity_detected"; + case AppEventType::kIdleCheckDue: + return "idle_check_due"; + case AppEventType::kIdleResponseExpired: + return "idle_response_expired"; + case AppEventType::kIdleGoodbyeDue: + return "idle_goodbye_due"; + case AppEventType::kReminderDue: + return "reminder_due"; + case AppEventType::kAlarmDue: + return "alarm_due"; + case AppEventType::kFirstDayAlarmDue: + return "first_day_alarm_due"; + case AppEventType::kAlertFinished: + return "alert_finished"; + case AppEventType::kLowBatteryWarning: + return "low_battery_warning"; + case AppEventType::kCriticalBattery: + return "critical_battery"; + case AppEventType::kOutgoingCall: + return "outgoing_call"; + case AppEventType::kIncomingCall: + return "incoming_call"; + case AppEventType::kCallConnected: + return "call_connected"; + case AppEventType::kCallEnded: + return "call_ended"; + case AppEventType::kFriendModeEnded: + return "friend_mode_ended"; + case AppEventType::kProvisioningRequested: + return "provisioning_requested"; + case AppEventType::kProvisioningWifiSaved: + return "provisioning_wifi_saved"; + case AppEventType::kProvisioningCompleted: + return "provisioning_completed"; + case AppEventType::kUpgradeRequested: + return "upgrade_requested"; + case AppEventType::kUpgradeCompleted: + return "upgrade_completed"; + case AppEventType::kUpgradeFailed: + return "upgrade_failed"; + case AppEventType::kSoftOffRequested: + return "soft_off_requested"; + case AppEventType::kFatalError: + return "fatal_error"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/core/app_event.h b/main/core/app_event.h new file mode 100644 index 0000000..dff863c --- /dev/null +++ b/main/core/app_event.h @@ -0,0 +1,86 @@ +#pragma once + +#include +#include + +namespace borla { + +enum class AppEventType : uint8_t { + kBootRequested, + kNetworkConnected, + kNetworkDisconnected, + kRealtimeConnected, + kRealtimeDisconnected, + kRealtimeProtocolError, + kButtonClicked, + kButtonLongPressed, + kAudioVolumeRequested, + kWakeWordControlRequested, + kBargeInControlRequested, + kRemoteIdleSleepRequested, + kLedAlertRequested, + kWakeWordDetected, + kBargeInCandidate, + kBargeInRejected, + kBargeInConfirmed, + kConversationStopRequested, + kTtsStarted, + kTtsStreamEnded, + kPlaybackPreempted, + kPlaybackDrained, + kPlaybackFailed, + kLocalPromptRequested, + kLocalPromptStarted, + kLocalSequenceRequested, + kLocalSequenceStarted, + kActivationReplayDue, + kShutdownPromptRequested, + kUserActivityDetected, + kIdleCheckDue, + kIdleResponseExpired, + kIdleGoodbyeDue, + kReminderDue, + kAlarmDue, + kFirstDayAlarmDue, + kAlertFinished, + kLowBatteryWarning, + kCriticalBattery, + kOutgoingCall, + kIncomingCall, + kCallConnected, + kCallEnded, + kFriendModeEnded, + kProvisioningRequested, + // Credentials were accepted and written to NVS. Provisioning stays active + // afterwards: the miniprogram still owns the reboot that leaves this mode. + kProvisioningWifiSaved, + kProvisioningCompleted, + kUpgradeRequested, + kUpgradeCompleted, + kUpgradeFailed, + kSoftOffRequested, + kFatalError, +}; + +// Control-plane event only. Raw audio and JSON payloads must stay in their +// respective data planes. Keeping this type trivially copyable makes it safe +// for a statically allocated FreeRTOS queue. +struct AppEvent { + AppEventType type = AppEventType::kBootRequested; + uint32_t correlation_id = 0; + int32_t value = 0; + uint32_t flags = 0; + + static AppEvent Make(AppEventType type, uint32_t correlation_id = 0, + int32_t value = 0, uint32_t flags = 0) + { + return AppEvent{type, correlation_id, value, flags}; + } +}; + +static_assert(std::is_trivially_copyable::value, + "AppEvent must remain safe for FreeRTOS queue copies"); + +const char* ToString(AppEventType type); + +} // namespace borla diff --git a/main/core/playback_types.cc b/main/core/playback_types.cc new file mode 100644 index 0000000..84ddddc --- /dev/null +++ b/main/core/playback_types.cc @@ -0,0 +1,122 @@ +#include "core/playback_types.h" + +namespace borla { + +const char* ToString(PlaybackSource source) +{ + switch (source) { + case PlaybackSource::kRemoteTts: + return "remote_tts"; + case PlaybackSource::kRemoteMusic: + return "remote_music"; + case PlaybackSource::kLocalPrompt: + return "local_prompt"; + case PlaybackSource::kAlarm: + return "alarm"; + case PlaybackSource::kCall: + return "call"; + } + return "unknown"; +} + +const char* ToString(PlaybackPriority priority) +{ + switch (priority) { + case PlaybackPriority::kBackground: + return "background"; + case PlaybackPriority::kConversation: + return "conversation"; + case PlaybackPriority::kLocalPrompt: + return "local_prompt"; + case PlaybackPriority::kSystem: + return "system"; + case PlaybackPriority::kAlarm: + return "alarm"; + case PlaybackPriority::kCall: + return "call"; + } + return "unknown"; +} + +const char* ToString(LocalPrompt prompt) +{ + switch (prompt) { + case LocalPrompt::kActivationDevice: + return "activation_device"; + case LocalPrompt::kDeviceAlreadyBound: + return "device_already_bound"; + case LocalPrompt::kServerError: + return "server_error"; + case LocalPrompt::kAlarmWake: + return "alarm_wake"; + case LocalPrompt::kAlarmSet: + return "alarm_set"; + case LocalPrompt::kNoNetwork: + return "no_network"; + case LocalPrompt::kProvisioning: + return "provisioning"; + case LocalPrompt::kWakeResponse: + return "wake_response"; + case LocalPrompt::kStoryExpired: + return "story_expired"; + case LocalPrompt::kIdleCheck: + return "idle_check"; + case LocalPrompt::kIdleGoodbye: + return "idle_goodbye"; + case LocalPrompt::kSnoreLight: + return "snore_light"; + case LocalPrompt::kWifiSuccess: + return "wifi_success"; + case LocalPrompt::kWelcome: + return "welcome"; + case LocalPrompt::kShutdown: + return "shutdown"; + case LocalPrompt::kBoot: + return "boot"; + case LocalPrompt::kError: + return "error"; + case LocalPrompt::kLowBattery20: + return "low_battery_20"; + case LocalPrompt::kLowBattery10: + return "low_battery_10"; + case LocalPrompt::kNet4gBootOn: + return "net4g_boot_on"; + case LocalPrompt::kNet4gOff: + return "net4g_off"; + case LocalPrompt::kNet4gOn: + return "net4g_on"; + case LocalPrompt::kNet4gNoWifi: + return "net4g_no_wifi"; + case LocalPrompt::kCallWait: + return "call_wait"; + case LocalPrompt::kCallRing: + return "call_ring"; + case LocalPrompt::kCallConnected: + return "call_connected"; + case LocalPrompt::kCallEnded: + return "call_ended"; + case LocalPrompt::kDigit0: + return "digit_0"; + case LocalPrompt::kDigit1: + return "digit_1"; + case LocalPrompt::kDigit2: + return "digit_2"; + case LocalPrompt::kDigit3: + return "digit_3"; + case LocalPrompt::kDigit4: + return "digit_4"; + case LocalPrompt::kDigit5: + return "digit_5"; + case LocalPrompt::kDigit6: + return "digit_6"; + case LocalPrompt::kDigit7: + return "digit_7"; + case LocalPrompt::kDigit8: + return "digit_8"; + case LocalPrompt::kDigit9: + return "digit_9"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/core/playback_types.h b/main/core/playback_types.h new file mode 100644 index 0000000..715b13f --- /dev/null +++ b/main/core/playback_types.h @@ -0,0 +1,102 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +using PlaybackSessionId = uint32_t; + +enum class PlaybackSource : uint8_t { + kRemoteTts, + kRemoteMusic, + kLocalPrompt, + kAlarm, + kCall, +}; + +enum class PlaybackPriority : uint8_t { + kBackground = 20, + kConversation = 40, + kLocalPrompt = 60, + kSystem = 80, + kAlarm = 100, + kCall = 120, +}; + +enum class AlertKind : uint8_t { + kReminder, + kAlarm, +}; + +enum class LocalPrompt : uint8_t { + kActivationDevice, + kDeviceAlreadyBound, + kServerError, + kAlarmWake, + kAlarmSet, + kNoNetwork, + kProvisioning, + kWakeResponse, + kStoryExpired, + kIdleCheck, + kIdleGoodbye, + kSnoreLight, + kWifiSuccess, + kWelcome, + kShutdown, + kBoot, + kError, + kLowBattery20, + kLowBattery10, + kNet4gBootOn, + kNet4gOff, + kNet4gOn, + kNet4gNoWifi, + kCallWait, + kCallRing, + kCallConnected, + kCallEnded, + kDigit0, + kDigit1, + kDigit2, + kDigit3, + kDigit4, + kDigit5, + kDigit6, + kDigit7, + kDigit8, + kDigit9, +}; + +inline constexpr size_t kMaxLocalPromptSequenceItems = 16; + +struct LocalPromptSequenceItem { + LocalPrompt prompt = LocalPrompt::kError; + int16_t selector = -1; +}; + +struct LocalPromptSequence { + std::array< + LocalPromptSequenceItem, + kMaxLocalPromptSequenceItems> items{}; + size_t count = 0; + + bool Empty() const { return count == 0; } + bool Contains(LocalPrompt prompt) const + { + for (size_t index = 0; index < count; ++index) { + if (items[index].prompt == prompt) { + return true; + } + } + return false; + } +}; + +const char* ToString(PlaybackSource source); +const char* ToString(PlaybackPriority priority); +const char* ToString(LocalPrompt prompt); + +} // namespace borla diff --git a/main/core/psram_object.h b/main/core/psram_object.h new file mode 100644 index 0000000..4e562bd --- /dev/null +++ b/main/core/psram_object.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +#include + +namespace borla { + +template +struct PsramObjectDeleter { + void operator()(T* object) const + { + if (object != nullptr) { + object->~T(); + heap_caps_free(object); + } + } +}; + +template +std::unique_ptr> MakePsramObject() +{ + void* memory = heap_caps_malloc( + sizeof(T), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (memory == nullptr) { + return {}; + } + return std::unique_ptr>( + new (memory) T()); +} + +} // namespace borla diff --git a/main/core/remote_behavior.cc b/main/core/remote_behavior.cc new file mode 100644 index 0000000..f61634c --- /dev/null +++ b/main/core/remote_behavior.cc @@ -0,0 +1,69 @@ +#include "core/remote_behavior.h" + +#include + +namespace borla { + +const char* ToString(ButtonAction action) +{ + switch (action) { + case ButtonAction::kUnspecified: + return ""; + case ButtonAction::kFriendMode: + return "friend_mode"; + case ButtonAction::kNetworkSwitch: + return "network_switch"; + case ButtonAction::kNothing: + return "nothing"; + } + return ""; +} + +bool ParseButtonAction(const char* value, ButtonAction* action) +{ + if (value == nullptr || action == nullptr) { + return false; + } + if (std::strcmp(value, "friend_mode") == 0) { + *action = ButtonAction::kFriendMode; + return true; + } + if (std::strcmp(value, "network_switch") == 0) { + *action = ButtonAction::kNetworkSwitch; + return true; + } + if (std::strcmp(value, "nothing") == 0) { + *action = ButtonAction::kNothing; + return true; + } + return false; +} + +bool IsAllowedConnectionPrompt(LocalPrompt prompt) +{ + return prompt == LocalPrompt::kServerError || + prompt == LocalPrompt::kNoNetwork || + prompt == LocalPrompt::kError; +} + +bool ParseConnectionPrompt(const char* value, LocalPrompt* prompt) +{ + if (value == nullptr || prompt == nullptr) { + return false; + } + if (std::strcmp(value, "server_error") == 0) { + *prompt = LocalPrompt::kServerError; + return true; + } + if (std::strcmp(value, "no_network") == 0) { + *prompt = LocalPrompt::kNoNetwork; + return true; + } + if (std::strcmp(value, "error") == 0) { + *prompt = LocalPrompt::kError; + return true; + } + return false; +} + +} // namespace borla diff --git a/main/core/remote_behavior.h b/main/core/remote_behavior.h new file mode 100644 index 0000000..7994b71 --- /dev/null +++ b/main/core/remote_behavior.h @@ -0,0 +1,22 @@ +#pragma once + +#include "core/playback_types.h" + +#include + +namespace borla { + +enum class ButtonAction : uint8_t { + kUnspecified = 0, + kFriendMode, + kNetworkSwitch, + kNothing, +}; + +const char* ToString(ButtonAction action); +bool ParseButtonAction(const char* value, ButtonAction* action); + +bool IsAllowedConnectionPrompt(LocalPrompt prompt); +bool ParseConnectionPrompt(const char* value, LocalPrompt* prompt); + +} // namespace borla diff --git a/main/core/runtime_state.cc b/main/core/runtime_state.cc new file mode 100644 index 0000000..2024799 --- /dev/null +++ b/main/core/runtime_state.cc @@ -0,0 +1,216 @@ +#include "core/runtime_state.h" + +namespace borla { + +StateValidation ValidateRuntimeState(const RuntimeState& state) +{ + if (state.realtime == RealtimeState::kOpen && + state.connectivity != ConnectivityState::kOnline) { + return {false, "open realtime channel requires online connectivity"}; + } + + if (state.conversation != ConversationState::kIdle && + state.lifecycle != LifecycleState::kRunning) { + return {false, "active conversation requires running lifecycle"}; + } + + if (state.conversation == ConversationState::kSpeaking && + state.playback == PlaybackState::kIdle) { + return {false, "speaking requires an active playback session"}; + } + + if (state.playback != PlaybackState::kIdle && + state.playback_session_id == 0 && + !state.pending_soft_off_after_playback && + !state.idle_check_prompt) { + return {false, "active playback requires a non-zero session id"}; + } + + if (state.local_prompt_active && + state.playback == PlaybackState::kIdle) { + return {false, "active local prompt requires playback"}; + } + + if (state.idle_sleeping && + (state.lifecycle != LifecycleState::kRunning || + state.realtime != RealtimeState::kClosed || + state.conversation != ConversationState::kIdle || + state.call != CallState::kInactive || + state.playback != PlaybackState::kIdle)) { + return {false, "idle sleep requires running offline media state"}; + } + + if (state.idle_check_prompt && + (state.lifecycle != LifecycleState::kRunning || + state.playback != PlaybackState::kDraining)) { + return {false, "idle check requires draining prompt playback"}; + } + + if (state.alert_ringing && + state.lifecycle != LifecycleState::kRunning) { + return {false, "alert ringing requires running lifecycle"}; + } + + if (state.call != CallState::kInactive && + state.lifecycle != LifecycleState::kRunning) { + return {false, "call requires running lifecycle"}; + } + + if (state.friend_mode && + (state.lifecycle != LifecycleState::kRunning || + state.realtime != RealtimeState::kClosed || + state.conversation != ConversationState::kIdle || + state.call != CallState::kInactive || + state.playback != PlaybackState::kIdle || + state.alert_ringing)) { + return {false, "friend mode requires exclusive idle media state"}; + } + + const bool exclusive_lifecycle = + state.lifecycle == LifecycleState::kProvisioning || + state.lifecycle == LifecycleState::kUpgrading || + state.lifecycle == LifecycleState::kShuttingDown || + state.lifecycle == LifecycleState::kSoftOff || + state.lifecycle == LifecycleState::kFaulted; + + const bool shutdown_prompt_playing = + state.lifecycle == LifecycleState::kShuttingDown && + state.pending_soft_off_after_playback && + state.realtime == RealtimeState::kClosed && + state.conversation == ConversationState::kIdle && + state.call == CallState::kInactive && + state.playback == PlaybackState::kDraining; + + if (exclusive_lifecycle && !shutdown_prompt_playing && + (state.realtime != RealtimeState::kClosed || + state.conversation != ConversationState::kIdle || + state.call != CallState::kInactive || + state.playback != PlaybackState::kIdle)) { + return {false, "exclusive lifecycle requires inactive realtime and media state"}; + } + + if (state.pending_soft_off_after_playback && + !shutdown_prompt_playing) { + return {false, "pending soft-off requires shutdown prompt playback"}; + } + + return {true, "ok"}; +} + +#define BORLA_ENUM_TO_STRING_CASE(value) \ + case value: \ + return #value + +const char* ToString(LifecycleState state) +{ + switch (state) { + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kCold); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kStarting); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kRunning); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kProvisioning); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kUpgrading); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kShuttingDown); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kSoftOff); + BORLA_ENUM_TO_STRING_CASE(LifecycleState::kFaulted); + } + return "LifecycleState::unknown"; +} + +const char* ToString(ConnectivityState state) +{ + switch (state) { + BORLA_ENUM_TO_STRING_CASE(ConnectivityState::kOffline); + BORLA_ENUM_TO_STRING_CASE(ConnectivityState::kConnecting); + BORLA_ENUM_TO_STRING_CASE(ConnectivityState::kOnline); + } + return "ConnectivityState::unknown"; +} + +const char* ToString(RealtimeState state) +{ + switch (state) { + BORLA_ENUM_TO_STRING_CASE(RealtimeState::kClosed); + BORLA_ENUM_TO_STRING_CASE(RealtimeState::kOpening); + BORLA_ENUM_TO_STRING_CASE(RealtimeState::kOpen); + } + return "RealtimeState::unknown"; +} + +const char* ToString(ConversationState state) +{ + switch (state) { + BORLA_ENUM_TO_STRING_CASE(ConversationState::kIdle); + BORLA_ENUM_TO_STRING_CASE(ConversationState::kListening); + BORLA_ENUM_TO_STRING_CASE(ConversationState::kSpeaking); + } + return "ConversationState::unknown"; +} + +const char* ToString(CallState state) +{ + switch (state) { + BORLA_ENUM_TO_STRING_CASE(CallState::kInactive); + BORLA_ENUM_TO_STRING_CASE(CallState::kRinging); + BORLA_ENUM_TO_STRING_CASE(CallState::kCalling); + BORLA_ENUM_TO_STRING_CASE(CallState::kActive); + } + return "CallState::unknown"; +} + +const char* ToString(PlaybackState state) +{ + switch (state) { + BORLA_ENUM_TO_STRING_CASE(PlaybackState::kIdle); + BORLA_ENUM_TO_STRING_CASE(PlaybackState::kStreaming); + BORLA_ENUM_TO_STRING_CASE(PlaybackState::kDraining); + } + return "PlaybackState::unknown"; +} + +const char* ToString(AudioPolicy policy) +{ + switch (policy) { + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kOff); + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kWakeWordOnly); + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kWakeWordDuplex); + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kConversationCapture); + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kBargeInDuplex); + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kCallDuplex); + BORLA_ENUM_TO_STRING_CASE(AudioPolicy::kPlaybackOnly); + } + return "AudioPolicy::unknown"; +} + +const char* ToString(ConversationInterruptSource source) +{ + switch (source) { + BORLA_ENUM_TO_STRING_CASE( + ConversationInterruptSource::kUserInitiated); + BORLA_ENUM_TO_STRING_CASE( + ConversationInterruptSource::kWakeWordDetected); + } + return "ConversationInterruptSource::unknown"; +} + +const char* ToString(LedPattern pattern) +{ + switch (pattern) { + BORLA_ENUM_TO_STRING_CASE(LedPattern::kOff); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kStarting); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kConnecting); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kIdle); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kListening); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kSpeaking); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kRinging); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kCalling); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kFriendMode); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kProvisioning); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kUpgrading); + BORLA_ENUM_TO_STRING_CASE(LedPattern::kError); + } + return "LedPattern::unknown"; +} + +#undef BORLA_ENUM_TO_STRING_CASE + +} // namespace borla diff --git a/main/core/runtime_state.h b/main/core/runtime_state.h new file mode 100644 index 0000000..a7e83e5 --- /dev/null +++ b/main/core/runtime_state.h @@ -0,0 +1,119 @@ +#pragma once + +#include "core/playback_types.h" + +#include + +namespace borla { + +enum class LifecycleState : uint8_t { + kCold, + kStarting, + kRunning, + kProvisioning, + kUpgrading, + kShuttingDown, + kSoftOff, + kFaulted, +}; + +enum class ConnectivityState : uint8_t { + kOffline, + kConnecting, + kOnline, +}; + +enum class RealtimeState : uint8_t { + kClosed, + kOpening, + kOpen, +}; + +enum class ConversationState : uint8_t { + kIdle, + kListening, + kSpeaking, +}; + +enum class CallState : uint8_t { + kInactive, + kRinging, + kCalling, + kActive, +}; + +enum class PlaybackState : uint8_t { + kIdle, + kStreaming, + kDraining, +}; + +enum class AudioPolicy : uint8_t { + kOff, + kWakeWordOnly, + kWakeWordDuplex, + kConversationCapture, + kBargeInDuplex, + kCallDuplex, + kPlaybackOnly, +}; + +enum class ConversationInterruptSource : uint8_t { + kUserInitiated, + kWakeWordDetected, +}; + +enum class LedPattern : uint8_t { + kOff, + kStarting, + kConnecting, + kIdle, + kListening, + kSpeaking, + kRinging, + kCalling, + kFriendMode, + kProvisioning, + kUpgrading, + kError, +}; + +struct RuntimeState { + LifecycleState lifecycle = LifecycleState::kCold; + ConnectivityState connectivity = ConnectivityState::kOffline; + RealtimeState realtime = RealtimeState::kClosed; + ConversationState conversation = ConversationState::kIdle; + CallState call = CallState::kInactive; + PlaybackState playback = PlaybackState::kIdle; + + uint32_t playback_session_id = 0; + bool pending_conversation_start = false; + bool pending_soft_off_after_playback = false; + bool idle_sleeping = false; + bool idle_check_prompt = false; + bool alert_ringing = false; + bool friend_mode = false; + bool pending_alert = false; + AlertKind pending_alert_kind = AlertKind::kReminder; + bool local_prompt_active = false; + LocalPrompt active_local_prompt = LocalPrompt::kError; +}; + +struct StateValidation { + bool valid; + const char* reason; +}; + +StateValidation ValidateRuntimeState(const RuntimeState& state); + +const char* ToString(LifecycleState state); +const char* ToString(ConnectivityState state); +const char* ToString(RealtimeState state); +const char* ToString(ConversationState state); +const char* ToString(CallState state); +const char* ToString(PlaybackState state); +const char* ToString(AudioPolicy policy); +const char* ToString(ConversationInterruptSource source); +const char* ToString(LedPattern pattern); + +} // namespace borla diff --git a/main/core/state_reducer.cc b/main/core/state_reducer.cc new file mode 100644 index 0000000..b37ce75 --- /dev/null +++ b/main/core/state_reducer.cc @@ -0,0 +1,1143 @@ +#include "core/state_reducer.h" + +#include "core/remote_behavior.h" + +namespace borla { +namespace { + +void ResetMediaState(TransitionResult& result) +{ + result.next.conversation = ConversationState::kIdle; + result.next.call = CallState::kInactive; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.pending_soft_off_after_playback = false; + result.next.idle_check_prompt = false; + result.next.idle_sleeping = false; + result.next.alert_ringing = false; + result.next.pending_alert = false; + result.next.friend_mode = false; + result.next.local_prompt_active = false; + result.next.active_local_prompt = LocalPrompt::kError; +} + +void AddIdlePolicy(TransitionResult& result) +{ + result.AddEffect(AppEffect::Audio(AudioPolicy::kWakeWordOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kIdle)); +} + +void AddListeningPolicy(TransitionResult& result) +{ + // Open the protocol's uplink gate before capture can enqueue the first + // Opus frame. Effects execute synchronously in insertion order. + result.AddEffect(AppEffect::Simple(AppEffectType::kSendStartListening)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kConversationCapture)); + result.AddEffect(AppEffect::Led(LedPattern::kListening)); +} + +void FinishLocalPrompt( + TransitionResult& result, + const RuntimeState& current) +{ + if (!current.local_prompt_active) { + return; + } + result.AddEffect(AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackDone, + current.active_local_prompt)); + result.next.local_prompt_active = false; + result.next.active_local_prompt = LocalPrompt::kError; +} + +void AddDisconnectedRecovery(TransitionResult& result) +{ + ResetMediaState(result); + result.next.realtime = RealtimeState::kClosed; + result.next.connectivity = ConnectivityState::kConnecting; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kWakeWordOnly)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStartConnectivity)); +} + +// Audible wake acknowledgement ("我在"). Deliberately a detached prompt: the +// device has already entered listening and must stay there, so this must not +// run through the kLocalPromptStarted lifecycle. Unconditional by product +// decision: every wake word gets an audible answer, even right after the +// welcome greeting already addressed the child. +void AddWakeAcknowledgement(TransitionResult& result) +{ + result.AddEffect(AppEffect::DetachedPrompt( + LocalPrompt::kWakeResponse, + PlaybackPriority::kLocalPrompt)); +} + +void RequestConversationStart(TransitionResult& result, + const RuntimeState& current, + bool allow_button_controls, + ConversationInterruptSource interrupt_source) +{ + if (current.lifecycle != LifecycleState::kRunning || + current.friend_mode) { + return; + } + + if (current.alert_ringing) { + result.next.alert_ringing = false; + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopAlert)); + } + result.next.idle_sleeping = false; + result.next.idle_check_prompt = false; + + if (current.call == CallState::kRinging) { + if (allow_button_controls) { + result.AddEffect( + AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendAcceptCall)); + } + return; + } + + if (current.call == CallState::kCalling || + current.call == CallState::kActive) { + if (allow_button_controls) { + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendHangupCall)); + } + return; + } + + if (current.conversation == ConversationState::kListening) { + if (!allow_button_controls) { + return; + } + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendStopListening)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + AddIdlePolicy(result); + return; + } + + if (current.conversation == ConversationState::kSpeaking) { + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kListening; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Abort(interrupt_source)); + AddListeningPolicy(result); + if (interrupt_source == + ConversationInterruptSource::kWakeWordDetected) { + // "你好播乐" mid-reply cuts the playback like any barge-in, but + // unlike a button press it always gets the audible "我在". + AddWakeAcknowledgement(result); + } + return; + } + + // Everything below is the idle -> conversation entry, the only place the + // legacy firmware answered the wake word out loud. + const bool acknowledge_wake = + interrupt_source == + ConversationInterruptSource::kWakeWordDetected; + + if (current.realtime == RealtimeState::kOpen) { + result.next.conversation = ConversationState::kListening; + AddListeningPolicy(result); + if (acknowledge_wake) { + AddWakeAcknowledgement(result); + } + return; + } + + result.next.pending_conversation_start = true; + if (current.connectivity == ConnectivityState::kOnline) { + result.next.realtime = RealtimeState::kOpening; + result.AddEffect(AppEffect::Simple(AppEffectType::kOpenRealtime)); + } else { + result.next.connectivity = ConnectivityState::kConnecting; + result.AddEffect( + AppEffect::Simple(AppEffectType::kStartConnectivity)); + } + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + if (acknowledge_wake) { + AddWakeAcknowledgement(result); + } +} + +void EnterProvisioning(TransitionResult& result) +{ + result.next.lifecycle = LifecycleState::kProvisioning; + result.next.connectivity = ConnectivityState::kOffline; + result.next.realtime = RealtimeState::kClosed; + result.next.pending_conversation_start = false; + ResetMediaState(result); + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect(AppEffect::Simple(AppEffectType::kSendGoodbye)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopConnectivity)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopFriendMode)); + result.AddEffect(AppEffect::Led(LedPattern::kProvisioning)); + // "请用小程序帮我连接网络". Without this the device is completely silent on + // a first boot with no credentials — the blinking LED is the only signal, + // which is not something a child or a parent reads. Detached because the + // provisioning lifecycle must keep playback at kIdle; kSystem priority so + // it wins over whatever kCancelPlayback just tore down. + result.AddEffect(AppEffect::DetachedPrompt( + LocalPrompt::kProvisioning, PlaybackPriority::kSystem)); + result.AddEffect(AppEffect::Simple(AppEffectType::kEnterProvisioning)); +} + +void EnterSoftOff(TransitionResult& result) +{ + result.next.lifecycle = LifecycleState::kShuttingDown; + result.next.connectivity = ConnectivityState::kOffline; + result.next.realtime = RealtimeState::kClosed; + result.next.pending_conversation_start = false; + ResetMediaState(result); + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect(AppEffect::Simple(AppEffectType::kSendGoodbye)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopConnectivity)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopFriendMode)); + result.AddEffect(AppEffect::Led(LedPattern::kOff)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopAudio)); + result.AddEffect(AppEffect::Simple(AppEffectType::kEnterSoftOff)); +} + +void BeginSoftOffPrompt( + TransitionResult& result, + LocalPrompt prompt) +{ + result.next.lifecycle = LifecycleState::kShuttingDown; + result.next.connectivity = ConnectivityState::kOffline; + result.next.realtime = RealtimeState::kClosed; + result.next.pending_conversation_start = false; + ResetMediaState(result); + result.next.playback = PlaybackState::kDraining; + result.next.pending_soft_off_after_playback = true; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Simple(AppEffectType::kSendGoodbye)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopConnectivity)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopFriendMode)); + result.AddEffect(AppEffect::Led(LedPattern::kOff)); + result.AddEffect( + AppEffect::Prompt( + prompt, + PlaybackPriority::kSystem)); +} + +void BeginShutdownPrompt(TransitionResult& result) +{ + BeginSoftOffPrompt(result, LocalPrompt::kShutdown); +} + +void CompleteShutdownPrompt(TransitionResult& result) +{ + result.next.lifecycle = LifecycleState::kSoftOff; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.pending_soft_off_after_playback = false; + result.AddEffect(AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect(AppEffect::Led(LedPattern::kOff)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStopAudio)); + result.AddEffect(AppEffect::Simple(AppEffectType::kEnterSoftOff)); +} + +void EnterIdleSleeping( + TransitionResult& result, + const RuntimeState& current) +{ + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.idle_check_prompt = false; + result.next.idle_sleeping = true; + result.next.realtime = RealtimeState::kClosed; + result.AddEffect(AppEffect::Simple( + AppEffectType::kSendStopListening)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendGoodbye)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Simple( + AppEffectType::kSetWakeWordEnabled, 1)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kWakeWordOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kOff)); +} + +void WakeIdleChannel(TransitionResult& result, + const RuntimeState& current) +{ + if (!current.idle_sleeping || + current.lifecycle != LifecycleState::kRunning) { + return; + } + result.next.idle_sleeping = false; + if (current.connectivity == ConnectivityState::kOnline) { + result.next.realtime = RealtimeState::kOpening; + result.AddEffect( + AppEffect::Simple(AppEffectType::kOpenRealtime)); + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + } else { + result.next.connectivity = ConnectivityState::kConnecting; + result.AddEffect( + AppEffect::Simple(AppEffectType::kStartConnectivity)); + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + } +} + +void BeginAlert(TransitionResult& result, + const RuntimeState& current, + AlertKind kind) +{ + if (current.lifecycle != LifecycleState::kRunning) { + return; + } + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.idle_check_prompt = false; + result.next.alert_ringing = true; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendStopListening)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendAbortSpeaking)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kRinging)); + result.AddEffect(AppEffect::Alert(kind)); + WakeIdleChannel(result, current); +} + +void PrepareLocalSequence( + TransitionResult& result, + const RuntimeState& current) +{ + if (current.lifecycle != LifecycleState::kRunning || + current.realtime != RealtimeState::kOpen || + current.call != CallState::kInactive || + current.friend_mode || + current.alert_ringing) { + return; + } + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.pending_conversation_start = false; + result.next.idle_check_prompt = false; + if (current.conversation == ConversationState::kListening) { + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendStopListening)); + } else if ( + current.conversation == ConversationState::kSpeaking) { + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendAbortSpeaking)); + } + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kSpeaking)); +} + +ButtonAction ResolveButtonAction(const AppEvent& event) +{ + const auto configured = + static_cast(event.flags); + if (configured == ButtonAction::kFriendMode || + configured == ButtonAction::kNetworkSwitch || + configured == ButtonAction::kNothing) { + return configured; + } + if (event.value == 3) { + return ButtonAction::kFriendMode; + } + if (event.value == 4) { + return ButtonAction::kNetworkSwitch; + } + return ButtonAction::kUnspecified; +} + +} // namespace + +TransitionResult ReduceState(const RuntimeState& current, const AppEvent& event) +{ + TransitionResult result; + result.next = current; + + switch (event.type) { + case AppEventType::kBootRequested: + if (current.lifecycle != LifecycleState::kCold) { + break; + } + result.next.lifecycle = LifecycleState::kStarting; + result.next.connectivity = ConnectivityState::kConnecting; + //result.AddEffect(AppEffect::Simple(AppEffectType::kStartConnectivity));//2026-9-7 ckkj mod + result.AddEffect(AppEffect::Simple(AppEffectType::kStartAudio)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect(AppEffect::Led(LedPattern::kStarting)); + result.AddEffect( + AppEffect::Prompt(LocalPrompt::kBoot, PlaybackPriority::kSystem)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStartConnectivity)); + break; + + case AppEventType::kNetworkConnected: + if ((current.lifecycle != LifecycleState::kStarting && + current.lifecycle != LifecycleState::kRunning) || + current.friend_mode) { + break; + } + result.next.connectivity = ConnectivityState::kOnline; + result.next.realtime = RealtimeState::kOpening; + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect(AppEffect::Simple(AppEffectType::kOpenRealtime)); + break; + + case AppEventType::kNetworkDisconnected: + if (current.lifecycle == LifecycleState::kStarting || + current.lifecycle == LifecycleState::kRunning) { + if (current.alert_ringing) { + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopAlert)); + } + if (current.friend_mode) { + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopFriendMode)); + } + AddDisconnectedRecovery(result); + } + break; + + case AppEventType::kRealtimeConnected: + // An in-flight connect can land after the device has already left the + // conversational lifecycle (upgrade, provisioning, shutdown). Accepting + // it there would force lifecycle back to kRunning mid-OTA. + if (current.connectivity != ConnectivityState::kOnline || + (current.lifecycle != LifecycleState::kStarting && + current.lifecycle != LifecycleState::kRunning)) { + break; + } + result.next.lifecycle = LifecycleState::kRunning; + result.next.realtime = RealtimeState::kOpen; + if (current.pending_alert) { + result.next.pending_alert = false; + result.next.alert_ringing = true; + result.AddEffect( + AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kRinging)); + result.AddEffect( + AppEffect::Alert(current.pending_alert_kind)); + } else if (current.pending_conversation_start) { + result.next.pending_conversation_start = false; + result.next.conversation = ConversationState::kListening; + AddListeningPolicy(result); + } else { + AddIdlePolicy(result); + } + break; + + case AppEventType::kRealtimeDisconnected: + if (current.lifecycle == LifecycleState::kStarting || + current.lifecycle == LifecycleState::kRunning) { + if (current.idle_sleeping || current.friend_mode) { + break; + } + ResetMediaState(result); + result.next.realtime = RealtimeState::kOpening; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kWakeWordOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect(AppEffect::Simple(AppEffectType::kOpenRealtime)); + } + break; + + case AppEventType::kRealtimeProtocolError: + if (current.lifecycle == LifecycleState::kStarting || + current.lifecycle == LifecycleState::kRunning) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kReportError, + event.correlation_id)); + } + break; + + case AppEventType::kButtonClicked: + { + const ButtonAction button_action = + ResolveButtonAction(event); + if (event.value == 3 || event.value == 4) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kSendButtonClick, + static_cast(event.value))); + } + if (current.friend_mode) { + if (button_action == ButtonAction::kFriendMode) { + // Keep the exclusive state until NimBLE has stopped. Opening + // realtime here can race the BLE controller shutdown. + result.AddEffect(AppEffect::Simple( + AppEffectType::kStopFriendMode)); + } + break; + } + if (event.value == 1) { + RequestConversationStart( + result, + current, + true, + ConversationInterruptSource::kUserInitiated); + } else if (event.value == 2) { + EnterProvisioning(result); + } else if (button_action == ButtonAction::kFriendMode && + current.lifecycle == LifecycleState::kRunning && + current.call == CallState::kInactive && + !current.alert_ringing && + current.playback == PlaybackState::kIdle) { + result.next.friend_mode = true; + result.next.realtime = RealtimeState::kClosed; + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.pending_conversation_start = false; + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendStopListening)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendAbortSpeaking)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Led(LedPattern::kFriendMode)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kStartFriendMode)); + } else if ( + button_action == ButtonAction::kNetworkSwitch && + current.lifecycle == LifecycleState::kRunning) { + result.next.realtime = RealtimeState::kClosed; + result.AddEffect(AppEffect::Simple(AppEffectType::kCloseRealtime));//2026-9 ckkj add + result.AddEffect(AppEffect::Simple(AppEffectType::kSwitchNetwork)); + } + break; + } + + case AppEventType::kButtonLongPressed: + // Long press must be audible before the device goes dark. The previous + // firmware played the shutdown prompt and waited up to 15 s for it to + // drain before entering soft off (borla_s3_board.cc OnLongPress); this + // went straight to kEnterSoftOff, so holding the button just killed the + // device silently and a child had no confirmation it worked. + // BeginShutdownPrompt arms pending_soft_off_after_playback, and + // kPlaybackDrained then runs CompleteShutdownPrompt. + BeginShutdownPrompt(result); + break; + + case AppEventType::kAudioVolumeRequested: + if (current.lifecycle == LifecycleState::kRunning && + event.value >= 0 && event.value <= 100) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kSetAudioVolume, + static_cast(event.value))); + } + break; + + case AppEventType::kWakeWordControlRequested: + if (current.lifecycle == LifecycleState::kRunning) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kSetWakeWordEnabled, + event.value != 0 ? 1U : 0U)); + } + break; + + case AppEventType::kBargeInControlRequested: + if (current.lifecycle == LifecycleState::kRunning) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kSetBargeInEnabled, + event.value != 0 ? 1U : 0U)); + } + break; + + case AppEventType::kRemoteIdleSleepRequested: + if (current.lifecycle == LifecycleState::kRunning && + current.call == CallState::kInactive && + !current.alert_ringing && + !current.friend_mode) { + EnterIdleSleeping(result, current); + } + break; + + case AppEventType::kLedAlertRequested: + if (current.lifecycle == LifecycleState::kRunning && + event.value >= 100 && event.value <= 60000) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kShowTemporaryLedAlert, + static_cast(event.value))); + } + break; + + case AppEventType::kWakeWordDetected: + RequestConversationStart( + result, + current, + false, + ConversationInterruptSource::kWakeWordDetected); + break; + + case AppEventType::kBargeInCandidate: + if (current.conversation == ConversationState::kSpeaking && + current.playback != PlaybackState::kIdle) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kPausePlayback)); + } + break; + + case AppEventType::kBargeInRejected: + if (current.conversation == ConversationState::kSpeaking && + current.playback != PlaybackState::kIdle) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kResumePlayback)); + } + break; + + case AppEventType::kBargeInConfirmed: + if (current.conversation == ConversationState::kSpeaking) { + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.AddEffect(AppEffect::Simple( + AppEffectType::kResumePlayback)); + result.AddEffect(AppEffect::Simple( + AppEffectType::kCancelPlayback)); + AddIdlePolicy(result); + } + break; + + case AppEventType::kConversationStopRequested: + if (current.lifecycle != LifecycleState::kRunning) { + break; + } + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.AddEffect(AppEffect::Simple(AppEffectType::kSendStopListening)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + AddIdlePolicy(result); + break; + + case AppEventType::kTtsStarted: + if (current.lifecycle != LifecycleState::kRunning || + current.realtime != RealtimeState::kOpen || + current.call != CallState::kInactive) { + break; + } + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kSpeaking; + result.next.playback = PlaybackState::kStreaming; + result.next.playback_session_id = event.correlation_id; + result.AddEffect(AppEffect::Simple( + AppEffectType::kResumePlayback)); + result.AddEffect(AppEffect::RemotePlayback( + AppEffectType::kBeginRemotePlayback, + event.correlation_id, + PlaybackPriority::kConversation)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kBargeInDuplex)); + result.AddEffect(AppEffect::Led(LedPattern::kSpeaking)); + break; + + case AppEventType::kTtsStreamEnded: + if (current.playback == PlaybackState::kStreaming && + (event.correlation_id == 0 || + event.correlation_id == current.playback_session_id)) { + result.next.playback = PlaybackState::kDraining; + result.AddEffect(AppEffect::Simple( + AppEffectType::kResumePlayback)); + result.AddEffect(AppEffect::RemotePlayback( + AppEffectType::kEndPlaybackInput, + current.playback_session_id)); + } + break; + + case AppEventType::kPlaybackPreempted: + if (current.playback != PlaybackState::kIdle && + event.correlation_id == current.playback_session_id) { + FinishLocalPrompt(result, current); + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + if (current.conversation == ConversationState::kSpeaking) { + result.next.conversation = ConversationState::kIdle; + result.AddEffect( + AppEffect::Simple(AppEffectType::kSendAbortSpeaking)); + AddIdlePolicy(result); + } + } + break; + + case AppEventType::kPlaybackDrained: + if (current.pending_soft_off_after_playback) { + FinishLocalPrompt(result, current); + CompleteShutdownPrompt(result); + break; + } + if (current.playback != PlaybackState::kIdle && + (event.correlation_id == 0 || + event.correlation_id == current.playback_session_id)) { + FinishLocalPrompt(result, current); + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + if (current.idle_check_prompt) { + result.next.idle_check_prompt = false; + } + if (current.lifecycle == LifecycleState::kRunning && + current.call == CallState::kInactive) { + if (current.realtime == RealtimeState::kOpen) { + result.next.conversation = + ConversationState::kListening; + AddListeningPolicy(result); + } else { + result.next.conversation = + ConversationState::kIdle; + AddIdlePolicy(result); + } + } + } + break; + + case AppEventType::kPlaybackFailed: + if (current.pending_soft_off_after_playback) { + FinishLocalPrompt(result, current); + result.AddEffect(AppEffect::Simple( + AppEffectType::kReportError, + event.correlation_id)); + CompleteShutdownPrompt(result); + break; + } + if (event.correlation_id == 0 || + event.correlation_id == current.playback_session_id) { + // A remote reply that dies mid-sentence must not just go quiet: + // the child gets an audible "something broke" before the device + // returns to listening. Local prompts already own their own + // failure feedback, so they are excluded. + const bool interrupted_remote_reply = + current.conversation == ConversationState::kSpeaking && + !current.local_prompt_active && + current.call == CallState::kInactive; + FinishLocalPrompt(result, current); + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.conversation = ConversationState::kIdle; + result.next.idle_check_prompt = false; + result.AddEffect(AppEffect::Simple(AppEffectType::kReportError, + event.correlation_id)); + AddIdlePolicy(result); + if (interrupted_remote_reply) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kRequestConnectionErrorPrompt)); + } + } + break; + + case AppEventType::kLocalPromptRequested: + if (current.lifecycle != LifecycleState::kStarting && + current.lifecycle != LifecycleState::kRunning) { + break; + } + if (current.lifecycle == LifecycleState::kRunning && + (current.call != CallState::kInactive || + current.alert_ringing || + current.friend_mode)) { + break; + } + { + const auto prompt = static_cast(event.value); + const auto priority = + static_cast(event.flags); + const auto selector = event.correlation_id == 0 + ? static_cast(-1) + : static_cast(event.correlation_id - 1); + if (prompt == LocalPrompt::kWelcome && + current.conversation == ConversationState::kListening) { + // The server greets every new websocket session with + // play_local welcome. When the session was opened BY the wake + // word the child already heard "我在" and the microphone is + // live — playing the greeting here cancelled that + // acknowledgement and closed the uplink for the prompt's + // whole duration. Ack it unplayed (started+done releases the + // server's playing_local lock immediately) and stay + // listening. + result.AddEffect(AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackStarted, prompt)); + result.AddEffect(AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackDone, prompt)); + break; + } + if (current.lifecycle == LifecycleState::kRunning) { + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + if (current.conversation == + ConversationState::kListening) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kSendStopListening)); + } else if (current.conversation == + ConversationState::kSpeaking) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kSendAbortSpeaking)); + } + result.AddEffect(AppEffect::Simple( + AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Led( + LedPattern::kSpeaking)); + } + result.AddEffect( + AppEffect::Prompt(prompt, priority, selector)); + } + break; + + case AppEventType::kLocalPromptStarted: + if ((current.pending_soft_off_after_playback || + current.idle_check_prompt) && + current.playback == PlaybackState::kDraining) { + result.next.playback_session_id = event.correlation_id; + result.next.local_prompt_active = true; + result.next.active_local_prompt = + static_cast(event.value); + result.AddEffect(AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackStarted, + result.next.active_local_prompt)); + } else if ( + current.lifecycle == LifecycleState::kRunning && + current.call == CallState::kInactive && + !current.alert_ringing && + !current.friend_mode && + event.correlation_id != 0) { + result.next.conversation = ConversationState::kSpeaking; + result.next.playback = PlaybackState::kDraining; + result.next.playback_session_id = event.correlation_id; + result.next.local_prompt_active = true; + result.next.active_local_prompt = + static_cast(event.value); + result.AddEffect(AppEffect::LocalPlaybackState( + AppEffectType::kSendLocalPlaybackStarted, + result.next.active_local_prompt)); + } + break; + + case AppEventType::kLocalSequenceRequested: + case AppEventType::kActivationReplayDue: + PrepareLocalSequence(result, current); + break; + + case AppEventType::kLocalSequenceStarted: + if (current.lifecycle == LifecycleState::kRunning && + current.realtime == RealtimeState::kOpen && + current.call == CallState::kInactive && + !current.friend_mode && + !current.alert_ringing) { + result.next.conversation = ConversationState::kSpeaking; + result.next.playback = PlaybackState::kDraining; + result.next.playback_session_id = event.correlation_id; + } + break; + + case AppEventType::kShutdownPromptRequested: + if (current.lifecycle == LifecycleState::kStarting || + current.lifecycle == LifecycleState::kRunning) { + BeginShutdownPrompt(result); + } + break; + + case AppEventType::kUserActivityDetected: + WakeIdleChannel(result, current); + break; + + case AppEventType::kIdleCheckDue: + if (current.lifecycle == LifecycleState::kRunning && + current.call == CallState::kInactive && + current.conversation != ConversationState::kSpeaking && + current.playback == PlaybackState::kIdle && + !current.alert_ringing) { + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kDraining; + result.next.playback_session_id = 0; + result.next.idle_check_prompt = true; + result.AddEffect( + AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kSpeaking)); + result.AddEffect(AppEffect::Prompt( + LocalPrompt::kIdleCheck, + PlaybackPriority::kSystem)); + } + break; + + case AppEventType::kIdleResponseExpired: + if (current.lifecycle == LifecycleState::kRunning && + !current.alert_ringing) { + EnterIdleSleeping(result, current); + } + break; + + case AppEventType::kIdleGoodbyeDue: + if (current.lifecycle == LifecycleState::kRunning && + current.idle_sleeping) { + BeginSoftOffPrompt( + result, LocalPrompt::kIdleGoodbye); + } + break; + + case AppEventType::kReminderDue: + if (current.friend_mode) { + result.next.pending_alert = true; + result.next.pending_alert_kind = AlertKind::kReminder; + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopFriendMode)); + break; + } + if (current.lifecycle == LifecycleState::kStarting) { + result.next.pending_alert = true; + result.next.pending_alert_kind = AlertKind::kReminder; + } else { + BeginAlert(result, current, AlertKind::kReminder); + } + break; + + case AppEventType::kAlarmDue: + if (current.friend_mode) { + result.next.pending_alert = true; + result.next.pending_alert_kind = AlertKind::kAlarm; + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopFriendMode)); + break; + } + if (current.lifecycle == LifecycleState::kStarting) { + result.next.pending_alert = true; + result.next.pending_alert_kind = AlertKind::kAlarm; + } else { + BeginAlert(result, current, AlertKind::kAlarm); + } + break; + + case AppEventType::kFirstDayAlarmDue: + WakeIdleChannel(result, current); + break; + + case AppEventType::kAlertFinished: + if (current.alert_ringing) { + result.next.alert_ringing = false; + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + AddIdlePolicy(result); + } + break; + + case AppEventType::kLowBatteryWarning: + if (current.lifecycle == LifecycleState::kRunning && + !current.alert_ringing) { + result.AddEffect(AppEffect::Prompt( + LocalPrompt::kLowBattery20, + PlaybackPriority::kSystem)); + } + break; + + case AppEventType::kCriticalBattery: + if (current.lifecycle == LifecycleState::kStarting || + current.lifecycle == LifecycleState::kRunning) { + BeginSoftOffPrompt( + result, LocalPrompt::kLowBattery10); + } + break; + + case AppEventType::kOutgoingCall: + if (current.lifecycle != LifecycleState::kRunning || + current.realtime != RealtimeState::kOpen) { + break; + } + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.call = CallState::kCalling; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kPlaybackOnly)); + result.AddEffect(AppEffect::Led(LedPattern::kCalling)); + result.AddEffect(AppEffect::Prompt( + LocalPrompt::kCallWait, + PlaybackPriority::kCall)); + break; + + case AppEventType::kIncomingCall: + if (current.lifecycle != LifecycleState::kRunning || + current.realtime != RealtimeState::kOpen) { + break; + } + FinishLocalPrompt(result, current); + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.next.call = CallState::kRinging; + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kCallDuplex)); + result.AddEffect(AppEffect::Led(LedPattern::kRinging)); + result.AddEffect(AppEffect::Prompt( + LocalPrompt::kCallRing, + PlaybackPriority::kCall)); + break; + + case AppEventType::kCallConnected: + if (current.lifecycle == LifecycleState::kRunning && + (current.call == CallState::kRinging || + current.call == CallState::kCalling)) { + result.next.call = CallState::kActive; + result.next.playback = PlaybackState::kStreaming; + result.next.playback_session_id = event.correlation_id; + result.AddEffect( + AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect(AppEffect::RemotePlayback( + AppEffectType::kBeginRemotePlayback, + event.correlation_id, + PlaybackPriority::kCall)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kCallDuplex)); + result.AddEffect(AppEffect::Led(LedPattern::kCalling)); + } + break; + + case AppEventType::kCallEnded: + if (current.call != CallState::kInactive) { + result.next.call = CallState::kInactive; + result.next.conversation = ConversationState::kIdle; + result.next.playback = PlaybackState::kIdle; + result.next.playback_session_id = 0; + result.AddEffect( + AppEffect::Simple(AppEffectType::kCancelPlayback)); + AddIdlePolicy(result); + result.AddEffect(AppEffect::Prompt( + LocalPrompt::kCallEnded, + PlaybackPriority::kSystem)); + } + break; + + case AppEventType::kFriendModeEnded: + if (!current.friend_mode) { + break; + } + result.next.friend_mode = false; + result.AddEffect( + AppEffect::Audio(AudioPolicy::kWakeWordOnly)); + if (event.correlation_id != 0) { + result.AddEffect(AppEffect::Simple( + AppEffectType::kReportError, + event.correlation_id)); + } + if (current.connectivity == ConnectivityState::kOnline) { + result.next.realtime = RealtimeState::kOpening; + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kOpenRealtime)); + } else { + result.next.connectivity = ConnectivityState::kConnecting; + result.next.realtime = RealtimeState::kClosed; + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kStartConnectivity)); + } + break; + + case AppEventType::kProvisioningRequested: + EnterProvisioning(result); + break; + + case AppEventType::kProvisioningWifiSaved: + // "配网成功啦". Stay in provisioning: the miniprogram drives the reboot + // that actually leaves this mode, exactly as the previous firmware did. + if (current.lifecycle == LifecycleState::kProvisioning) { + result.AddEffect(AppEffect::DetachedPrompt( + LocalPrompt::kWifiSuccess, PlaybackPriority::kSystem)); + } + break; + + case AppEventType::kProvisioningCompleted: + if (current.lifecycle == LifecycleState::kProvisioning) { + result.next.lifecycle = LifecycleState::kStarting; + result.next.connectivity = ConnectivityState::kConnecting; + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStartConnectivity)); + } + break; + + case AppEventType::kUpgradeRequested: + result.next.lifecycle = LifecycleState::kUpgrading; + result.next.realtime = RealtimeState::kClosed; + result.next.pending_conversation_start = false; + ResetMediaState(result); + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopFriendMode)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect(AppEffect::Simple(AppEffectType::kCloseRealtime)); + result.AddEffect(AppEffect::Led(LedPattern::kUpgrading)); + result.AddEffect(AppEffect::Simple(AppEffectType::kStartUpgrade, + event.correlation_id)); + break; + + case AppEventType::kUpgradeCompleted: + if (current.lifecycle == LifecycleState::kUpgrading) { + result.AddEffect(AppEffect::Simple(AppEffectType::kReboot)); + } + break; + + case AppEventType::kUpgradeFailed: + if (current.lifecycle == LifecycleState::kUpgrading) { + result.next.lifecycle = LifecycleState::kRunning; + result.next.realtime = RealtimeState::kOpening; + result.AddEffect(AppEffect::Simple(AppEffectType::kReportError, + event.correlation_id)); + result.AddEffect(AppEffect::Led(LedPattern::kConnecting)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kOpenRealtime)); + } + break; + + case AppEventType::kSoftOffRequested: + EnterSoftOff(result); + break; + + case AppEventType::kFatalError: + result.next.lifecycle = LifecycleState::kFaulted; + result.next.connectivity = ConnectivityState::kOffline; + result.next.realtime = RealtimeState::kClosed; + result.next.pending_conversation_start = false; + ResetMediaState(result); + result.AddEffect(AppEffect::Simple(AppEffectType::kCancelPlayback)); + result.AddEffect( + AppEffect::Simple(AppEffectType::kStopFriendMode)); + result.AddEffect(AppEffect::Audio(AudioPolicy::kOff)); + result.AddEffect(AppEffect::Led(LedPattern::kError)); + result.AddEffect(AppEffect::Simple(AppEffectType::kReportError, + event.correlation_id)); + break; + } + + return result; +} + +} // namespace borla diff --git a/main/core/state_reducer.h b/main/core/state_reducer.h new file mode 100644 index 0000000..ebbc632 --- /dev/null +++ b/main/core/state_reducer.h @@ -0,0 +1,13 @@ +#pragma once + +#include "core/app_effect.h" +#include "core/app_event.h" +#include "core/runtime_state.h" + +namespace borla { + +// Pure control-plane state transition function. It has no ESP-IDF dependency, +// performs no I/O and is therefore host-testable. +TransitionResult ReduceState(const RuntimeState& current, const AppEvent& event); + +} // namespace borla diff --git a/main/core/task_stack_budget.h b/main/core/task_stack_budget.h new file mode 100644 index 0000000..ee8c0f4 --- /dev/null +++ b/main/core/task_stack_budget.h @@ -0,0 +1,97 @@ +#pragma once + +#include + +namespace borla::task_stack_budget { + +// ESP-IDF's FreeRTOS task creation APIs on ESP32-S3 express stack depth in +// bytes. Keep the unit in each name so future changes do not accidentally +// treat these values as host FreeRTOS StackType_t words. The two large audio +// stacks are allocated from PSRAM; connectivity stacks stay in internal RAM. +inline constexpr size_t kPlaybackBytes = 36 * 1024; +// Internal RAM, and dynamically allocated so BLE provisioning gets it back +// when the audio engine is stopped. This is the one audio task with a hard +// deadline: it must finish read + AEC + wake word inside 60 ms or the I2S RX +// DMA overflows and the AEC loses microphone/reference alignment. Stack access +// is the most frequent memory operation in that code, and serving it from PSRAM +// — over a bus the encoder task is simultaneously hammering — was measured at +// 56-70 ms for the DSP stage alone. +// +// The previous firmware ran the identical work (VoiceProcessor + WakeNet) in +// 16 KB of internal RAM; 20 KB here leaves margin for the 1920-byte reference +// frame this implementation keeps on the stack. Watch capture2's +// stack_free_bytes in the diagnostics snapshot before trimming further. +// 16 KB matches the previous firmware's audio_in task for the same workload; +// the measured high-water mark here is ~6.3 KB (capture2 stack_free_bytes = +// 14172 of the earlier 20 KB, read while duplex AEC was active). +inline constexpr size_t kCaptureBytes = 10 * 1024;//16 * 1024; +// Opus encoding only; runs on the other core so it never competes with the +// capture loop's 60 ms frame budget. +// +// Sized from where the work came from, not from the task's idle footprint. +// libopus' SILK path (silk_encode_frame_FIX -> silk_find_pitch_lags_FIX -> +// silk_autocorr -> celt_pitch_xcorr) puts large arrays on the stack; the +// combined capture task that used to do this was measured at ~25 KB in use. +// A first attempt at 16 KB tripped the stack canary inside celt_pitch_xcorr_c +// on the very first encoded frame and put the device in a boot loop. A later +// trim to 24 KB tripped it again deeper in the same path (stack canary in +// silk_NSQ_del_dec_c at NSQ_del_dec.c:266, the call into +// silk_noise_shape_quantizer_del_dec, 2026-09-23): the panic backtrace spans +// 0x3c842cb0..0x3c848b60, i.e. the opus_encode() chain alone walked 24,240 of +// the 24,576 budgeted bytes before the next frame crossed the limit. This is +// PSRAM, so the headroom costs no internal RAM. +inline constexpr size_t kCaptureEncoderBytes = 32 * 1024; +// Sized from measured high-water marks after a full TLS + OTA + provisioning +// cycle, not guessed. Every byte here is .bss, i.e. it comes straight off the +// front of the main internal heap region — and that region is what BLE +// provisioning runs out of when it has to re-init the WiFi driver alongside the +// BT controller. Field numbers at the time of sizing (used / previous budget): +// connectivity2 2492 / 8192 dual_network2 3136 / 8192 +// friend_service2 960 / 4096 alarm2 1172 / 4096 +inline constexpr size_t kConnectivityManagerBytes = 5 * 1024;//6 * 1024; +inline constexpr size_t kDualNetworkBytes = 4 * 1024;//5 * 1024; +inline constexpr size_t kWebsocketTransportBytes = 10 * 1024;//12 * 1024; +inline constexpr size_t kFriendServiceBytes = 3 * 1024; +inline constexpr size_t kAlarmServiceBytes = 3 * 1024; +inline constexpr size_t kRuntimeDiagnosticsBytes = 8 * 1024; +inline constexpr size_t kLocalPromptProducerBytes = 6 * 1024; +// BLE provisioning worker: carries esp_wifi_scan_start, nimble_port_init and +// NVS credential writes on one stack, so it cannot live in PSRAM (NVS runs +// with the cache disabled) and needs real headroom. +inline constexpr size_t kBleProvisioningBytes = 8 * 1024; + +} // namespace borla::task_stack_budget + +namespace borla::task_priority { + +// The audio path is a real-time system and its priorities are load-bearing, +// not incidental. Layout adopted from the previous firmware, which ran the +// same DSP on the same silicon without stuttering (audio_service.cc:56-58): +// +// audio_in prio 8 core 0 capture + AEC + wake word +// audio_out prio 4 core 1 I2S write +// opus_codec prio 2 core 1 encode + decode +// +// The rule is that the two tasks with a hard 60 ms deadline must preempt the +// CPU-heavy one, never the reverse. This firmware originally ran all three at +// priority 5; a single Opus encode costs ~50 ms of CPU, so at equal priority it +// simply took the speaker task's slot and playback stuttered audibly. +// +// The speaker task is 6 rather than the previous firmware's 4 because it is +// not the same task. The old audio_out was a pure I2S writer — per wake-up it +// memcpy'd already-decoded PCM into the DMA, work so small that time-slicing +// against the priority-4 service crowd could not hurt it, and behind it stood +// an 8-frame decoded-PCM queue (480 ms of runway) filled by the codec task. +// Here decode+write are fused into one task whose only runway is the I2S DMA +// itself, so a 10-15 ms Opus decode delayed by round-robin against the +// UNPINNED priority-4/5 tasks (websocket2 doing TLS at 4, imu_sensor2 doing +// I2C at 5, touch/battery/alarm/reminder at 4 — all free to land on core 1) +// occasionally missed the deadline: the field symptom was intermittent +// playback stutter. 6 puts the speaker above that crowd and below capture. +// Priority inheritance covers the shared mutexes (ESP-IDF std::mutex is a +// FreeRTOS PI mutex underneath). +inline constexpr unsigned kCaptureLoop = 8; +inline constexpr unsigned kPlaybackLoop = 6; +inline constexpr unsigned kAudioCodec = 2; + +} // namespace borla::task_priority diff --git a/main/diagnostics/audio_tap.cc b/main/diagnostics/audio_tap.cc new file mode 100644 index 0000000..17d11fc --- /dev/null +++ b/main/diagnostics/audio_tap.cc @@ -0,0 +1,308 @@ +#include "diagnostics/audio_tap.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "AudioTap2"; +//constexpr uint32_t kTaskStackBytes = 6 * 1024; +constexpr unsigned kTaskPriority = 3; +constexpr uint32_t kBindRetryMs = 2000; +constexpr uint32_t kSampleRateHz = 48000;//24000; +constexpr uint32_t kUplinkRateHz = 16000; + +} // namespace + +bool AudioTap::Initialize() +{ + if (initialized_) { + return true; + } + input_.data = static_cast(heap_caps_malloc( + kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + output_.data = static_cast(heap_caps_malloc( + kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + uplink_.data = static_cast(heap_caps_malloc( + kRingBytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + if (input_.data == nullptr || output_.data == nullptr || + uplink_.data == nullptr) { + ESP_LOGE(kTag, "ring allocation failed"); + heap_caps_free(input_.data); + heap_caps_free(output_.data); + heap_caps_free(uplink_.data); + input_.data = nullptr; + output_.data = nullptr; + uplink_.data = nullptr; + return false; + } + input_.capacity = kRingBytes; + output_.capacity = kRingBytes; + uplink_.capacity = kRingBytes; + + //const BaseType_t created = xTaskCreatePinnedToCoreWithCaps( + task_ = xTaskCreateStaticPinnedToCore( + &AudioTap::TaskEntry, + "audio_tap2", + //kTaskStackBytes, + sizeof(task_stack_), + this, + kTaskPriority, + // &task_, + // tskNO_AFFINITY, + // MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + // if (created != pdPASS) { + task_stack_, + &task_control_, + 0); + if (task_ == nullptr) { + ESP_LOGE(kTag, "task creation failed"); + heap_caps_free(input_.data); + heap_caps_free(output_.data); + heap_caps_free(uplink_.data); + input_.data = nullptr; + output_.data = nullptr; + uplink_.data = nullptr; + return false; + } + initialized_ = true; + ESP_LOGI(kTag, + "recording rings armed: 3 x %u KB PSRAM, TCP port %u", + static_cast(kRingBytes / 1024), + static_cast(kPort)); + return true; +} + +void AudioTap::PushInput(const int16_t* samples, size_t sample_count) +{ + Push(input_, + reinterpret_cast(samples), + sample_count * sizeof(int16_t)); +} + +void AudioTap::PushOutput(const int16_t* samples, size_t sample_count) +{ + if (samples == nullptr) { + // Gap marker: the DAC starved between writes. Recording the silence + // keeps spk.wav on the same timeline the microphone heard — without + // it, late frames concatenate seamlessly and playout gaps become + // invisible in the file, which misread as "spk clean, mic stutters". + static const int16_t kZeroChunk[240] = {}; + size_t remaining = sample_count; + while (remaining > 0) { + const size_t chunk = + remaining < sizeof(kZeroChunk) / sizeof(kZeroChunk[0]) + ? remaining + : sizeof(kZeroChunk) / sizeof(kZeroChunk[0]); + Push(output_, + reinterpret_cast(kZeroChunk), + chunk * sizeof(int16_t)); + remaining -= chunk; + } + return; + } + Push(output_, + reinterpret_cast(samples), + sample_count * sizeof(int16_t)); +} + +void AudioTap::PushUplink(const int16_t* samples, size_t sample_count) +{ + if (samples != nullptr) { + Push(uplink_, + reinterpret_cast(samples), + sample_count * sizeof(int16_t)); + return; + } + // Suppressed or idle frame: silence keeps the uplink channel's timeline + // aligned with mic/spk so "what did the server hear at second N" is a + // direct A/B listen. + static const int16_t kZeroChunk[240] = {}; + size_t remaining = sample_count; + while (remaining > 0) { + const size_t chunk = + remaining < sizeof(kZeroChunk) / sizeof(kZeroChunk[0]) + ? remaining + : sizeof(kZeroChunk) / sizeof(kZeroChunk[0]); + Push(uplink_, + reinterpret_cast(kZeroChunk), + chunk * sizeof(int16_t)); + remaining -= chunk; + } +} + +void AudioTap::Push(Ring& ring, const uint8_t* bytes, size_t size) +{ + if (ring.data == nullptr || bytes == nullptr || size == 0) { + return; + } + const size_t head = ring.head.load(std::memory_order_relaxed); + const size_t tail = ring.tail.load(std::memory_order_acquire); + const size_t space = ring.capacity - (head - tail); + if (size > space) { + // Drop the NEW audio, keep the old: while no host is attached the + // ring must preserve the earliest sound after boot, not the latest. + ring.dropped_bytes.fetch_add( + static_cast(size), std::memory_order_relaxed); + return; + } + const size_t offset = head % ring.capacity; + const size_t first = std::min(size, ring.capacity - offset); + std::memcpy(ring.data + offset, bytes, first); + std::memcpy(ring.data, bytes + first, size - first); + ring.head.store(head + size, std::memory_order_release); +} + +void AudioTap::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void AudioTap::Run() +{ + // lwIP's TCP/IP thread is created by esp_netif_init(), which the WiFi + // transport calls well after this task starts. Touching the socket API + // before that is not an error return but an assert ("Invalid mbox") and + // a boot loop. A netif existing proves esp_netif_init() has completed. + // The rings keep buffering while we wait, so no boot audio is lost. + while (esp_netif_get_nr_of_ifs() == 0) { + vTaskDelay(pdMS_TO_TICKS(kBindRetryMs)); + } + + int listen_fd = -1; + while (true) { + listen_fd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listen_fd >= 0) { + const int reuse = 1; + ::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, + &reuse, sizeof(reuse)); + sockaddr_in address{}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_ANY); + address.sin_port = htons(kPort); + if (::bind(listen_fd, + reinterpret_cast(&address), + sizeof(address)) == 0 && + ::listen(listen_fd, 1) == 0) { + break; + } + ::close(listen_fd); + } + vTaskDelay(pdMS_TO_TICKS(kBindRetryMs)); + } + ESP_LOGI(kTag, "listening on port %u", + static_cast(kPort)); + + while (true) { + const int client_fd = ::accept(listen_fd, nullptr, nullptr); + if (client_fd < 0) { + vTaskDelay(pdMS_TO_TICKS(kBindRetryMs)); + continue; + } + ESP_LOGI(kTag, "recorder attached"); + ServeClient(client_fd); + ::close(client_fd); + ESP_LOGI(kTag, + "recorder detached dropped_in=%lu dropped_out=%lu", + static_cast( + input_.dropped_bytes.load()), + static_cast( + output_.dropped_bytes.load())); + } +} + +void AudioTap::ServeClient(int client_fd) +{ + // Hello v2: magic, version, channel count, pad, mic/spk rate, uplink + // rate. The host validates this before trusting the frame stream. + uint8_t hello[16] = {'B', 'T', 'A', 'P', 2, 3, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0}; + hello[8] = static_cast(kSampleRateHz & 0xFFU); + hello[9] = static_cast((kSampleRateHz >> 8U) & 0xFFU); + hello[10] = static_cast((kSampleRateHz >> 16U) & 0xFFU); + hello[11] = static_cast((kSampleRateHz >> 24U) & 0xFFU); + hello[12] = static_cast(kUplinkRateHz & 0xFFU); + hello[13] = static_cast((kUplinkRateHz >> 8U) & 0xFFU); + hello[14] = static_cast((kUplinkRateHz >> 16U) & 0xFFU); + hello[15] = static_cast((kUplinkRateHz >> 24U) & 0xFFU); + if (!SendAll(client_fd, hello, sizeof(hello))) { + return; + } + + while (true) { + if (!DrainAndSend(client_fd, input_, 0) || + !DrainAndSend(client_fd, output_, 1) || + !DrainAndSend(client_fd, uplink_, 2)) { + return; + } + const bool input_empty = + input_.head.load(std::memory_order_acquire) == + input_.tail.load(std::memory_order_relaxed); + const bool output_empty = + output_.head.load(std::memory_order_acquire) == + output_.tail.load(std::memory_order_relaxed); + const bool uplink_empty = + uplink_.head.load(std::memory_order_acquire) == + uplink_.tail.load(std::memory_order_relaxed); + if (input_empty && output_empty && uplink_empty) { + vTaskDelay(pdMS_TO_TICKS(kIdlePollMs)); + } + } +} + +bool AudioTap::DrainAndSend( + int socket_fd, + Ring& ring, + uint8_t channel) +{ + uint8_t record[4 + kSendChunkBytes]; + while (true) { + const size_t head = ring.head.load(std::memory_order_acquire); + const size_t tail = ring.tail.load(std::memory_order_relaxed); + const size_t available = head - tail; + if (available == 0) { + return true; + } + const size_t take = std::min(available, kSendChunkBytes); + const size_t offset = tail % ring.capacity; + const size_t first = std::min(take, ring.capacity - offset); + std::memcpy(record + 4, ring.data + offset, first); + std::memcpy(record + 4 + first, ring.data, take - first); + record[0] = channel; + record[1] = 0; + record[2] = static_cast(take & 0xFFU); + record[3] = static_cast((take >> 8U) & 0xFFU); + if (!SendAll(socket_fd, record, 4 + take)) { + return false; + } + // Advance only after the bytes are on the wire so a mid-record send + // failure re-sends the same audio to the next recorder instead of + // losing it. + ring.tail.store(tail + take, std::memory_order_release); + } +} + +bool AudioTap::SendAll(int socket_fd, const void* data, size_t size) +{ + const uint8_t* cursor = static_cast(data); + size_t remaining = size; + while (remaining > 0) { + const ssize_t sent = + ::send(socket_fd, cursor, remaining, 0); + if (sent <= 0) { + return false; + } + cursor += static_cast(sent); + remaining -= static_cast(sent); + } + return true; +} + +} // namespace borla diff --git a/main/diagnostics/audio_tap.h b/main/diagnostics/audio_tap.h new file mode 100644 index 0000000..dc36074 --- /dev/null +++ b/main/diagnostics/audio_tap.h @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include + +#include +#include + +namespace borla { + +// Debug-only boot-to-shutdown audio recorder. +// +// The device has nowhere to store an hour of PCM (no SD card, and flash is +// both too small and too slow to write from the audio path), so the tap keeps +// two ring buffers in PSRAM — everything the microphone captured and +// everything that reached the DAC, both 24 kHz mono s16 at the hardware +// boundary — and streams them over a plain TCP socket to +// tools/audio_tap_dump.py, which writes the pair of WAV files. ~32 s of +// pre-buffer per channel covers the gap between the boot prompt and the host +// connecting, so a capture started before power-on is gapless from boot; the +// files end when the device powers off and the socket dies. +// +// The push side is called from the capture and playback tasks and must never +// block or lock: each ring is single-producer/single-consumer with monotonic +// indices, and a full ring drops the NEWEST audio (keeping the oldest, which +// is what preserves the boot prompt while no host is attached). +// +// This is an open microphone on an unauthenticated LAN port. It exists behind +// CONFIG_BORLA_AUDIO_TAP for debugging sessions only and must never ship +// enabled. +class AudioTap final { +public: + bool Initialize(); + // Capture task: raw ADC output, before any DSP. + void PushInput(const int16_t* samples, size_t sample_count); + // Playback task: volume-scaled PCM, exactly what the DAC received. + void PushOutput(const int16_t* samples, size_t sample_count); + // Capture task: the server's-ear channel — post-AEC, post-gate 16 kHz + // PCM exactly as it goes to the Opus encoder. nullptr pushes silence so + // suppressed/idle frames keep the timeline aligned with the other two + // channels. + void PushUplink(const int16_t* samples, size_t sample_count); + +private: + struct Ring { + uint8_t* data = nullptr; + size_t capacity = 0; + // Monotonic byte counters; unsigned wraparound keeps head - tail + // correct. Producer owns head, the tap task owns tail. + std::atomic head{0}; + std::atomic tail{0}; + std::atomic dropped_bytes{0}; + }; + + static constexpr uint16_t kPort = 3401; + // 1.5 MB per channel = ~32 s at 24 kHz mono s16 (48 KB/s). + static constexpr size_t kRingBytes = 1536 * 1024; + // One 60 ms frame per TCP record keeps the on-stack scratch small. + static constexpr size_t kSendChunkBytes = 2880; + static constexpr uint32_t kIdlePollMs = 20; + //2026-9-23 ckkj debug for wifi mem fail + static constexpr size_t kTaskStackBytes = 6 * 1024; + static void TaskEntry(void* context); + [[noreturn]] void Run(); + void ServeClient(int client_fd); + void Push(Ring& ring, const uint8_t* bytes, size_t size); + // Sends everything currently in the ring as [channel u8, 0 u8, + // size u16 LE, payload] records. Returns false when the socket died. + bool DrainAndSend(int socket_fd, Ring& ring, uint8_t channel); + bool SendAll(int socket_fd, const void* data, size_t size); + + Ring input_; + Ring output_; + Ring uplink_; + //2026-9-23 ckkj debug for wifi mem fail + StackType_t task_stack_[kTaskStackBytes] = {}; + StaticTask_t task_control_ {}; + // + TaskHandle_t task_ = nullptr; + bool initialized_ = false; +}; + +} // namespace borla diff --git a/main/diagnostics/device_log_formatter.cc b/main/diagnostics/device_log_formatter.cc new file mode 100644 index 0000000..3f3ad29 --- /dev/null +++ b/main/diagnostics/device_log_formatter.cc @@ -0,0 +1,177 @@ +#include "diagnostics/device_log_formatter.h" + +#include "diagnostics/trace_context.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr char kStandardHeaderEnd[] = ") %s: "; +char g_device_mac[18] = "MAC-UNAVAILABLE"; +bool g_initialized = false; +bool g_mac_available = false; +bool g_at_line_start = true; +std::atomic g_clock_synchronized{false}; + +void FormatTimestamp(char* output, size_t capacity) +{ + if (output == nullptr || capacity == 0) { + return; + } + + timeval now{}; + gettimeofday(&now, nullptr); + if (g_clock_synchronized.load(std::memory_order_acquire) && + now.tv_sec >= 1700000000LL) { + tm local{}; + const time_t seconds = static_cast(now.tv_sec); + if (localtime_r(&seconds, &local) != nullptr) { + const size_t calendar_size = std::strftime( + output, + capacity, + "%Y-%m-%d %H:%M:%S", + &local); + if (calendar_size != 0 && + capacity >= calendar_size + 5) { + const unsigned milliseconds = + static_cast(now.tv_usec / 1000) % 1000; + output[calendar_size] = '.'; + output[calendar_size + 1] = static_cast( + '0' + milliseconds / 100); + output[calendar_size + 2] = static_cast( + '0' + (milliseconds / 10) % 10); + output[calendar_size + 3] = static_cast( + '0' + milliseconds % 10); + output[calendar_size + 4] = '\0'; + return; + } + } + } + + std::snprintf( + output, + capacity, + "TIME-UNSYNCED+%" PRIu32 "ms", + esp_log_timestamp()); +} + +int SumPrinted(int first, int second) +{ + if (first < 0 || second < 0) { + return -1; + } + return first + second; +} + +bool FormatEndsLine(const char* format) +{ + const size_t size = std::strlen(format); + return size != 0 && format[size - 1] == '\n'; +} + +} // namespace + +bool DeviceLogFormatter::Initialize() +{ + if (g_initialized) { + return g_mac_available; + } + + uint8_t mac[6]{}; + if (esp_read_mac(mac, ESP_MAC_WIFI_STA) == ESP_OK) { + std::snprintf( + g_device_mac, + sizeof(g_device_mac), + // Lower case to match the identity MAC and the previous firmware's + // prefix (main.cc), so one grep finds both the log lines and the + // device_id the server knows this board by. + "%02x:%02x:%02x:%02x:%02x:%02x", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + g_mac_available = true; + } + TraceContext::Initialize(g_device_mac); + g_initialized = true; + esp_log_set_vprintf(&DeviceLogFormatter::Print); + return g_mac_available; +} + +void DeviceLogFormatter::MarkClockSynchronized() +{ + g_clock_synchronized.store(true, std::memory_order_release); +} + +int DeviceLogFormatter::Print( + const char* format, + va_list arguments) +{ + if (format == nullptr) { + return -1; + } + +#if CONFIG_LOG_TIMESTAMP_SOURCE_RTOS + const char* const level_marker = std::strstr(format, " ("); + const char* const header_end = + std::strstr(format, kStandardHeaderEnd); + if (level_marker != nullptr && level_marker != format && + header_end != nullptr && level_marker < header_end) { + va_list message_arguments; + va_copy(message_arguments, arguments); + (void)va_arg(message_arguments, uint32_t); + const char* const tag = + va_arg(message_arguments, const char*); + const char level = *(level_marker - 1); + const char* const message_format = + header_end + sizeof(kStandardHeaderEnd) - 1; + char timestamp[40]{}; + FormatTimestamp(timestamp, sizeof(timestamp)); + + flockfile(stdout); + const int prefix_size = std::fprintf( + stdout, + "[%s][%s][%s] %c %s: ", + g_device_mac, + timestamp, + TraceContext::TraceId(), + level, + tag == nullptr ? "unknown" : tag); + const int message_size = std::vfprintf( + stdout, message_format, message_arguments); + g_at_line_start = FormatEndsLine(message_format); + funlockfile(stdout); + va_end(message_arguments); + return SumPrinted(prefix_size, message_size); + } +#endif + + // Some binary components emit one logical line through several vprintf + // calls. Prefix only the first fragment; prefixing every callback corrupts + // WiFi logs into several apparent lines. + flockfile(stdout); + int prefix_size = 0; + if (g_at_line_start) { + char timestamp[40]{}; + FormatTimestamp(timestamp, sizeof(timestamp)); + prefix_size = std::fprintf( + stdout, + "[%s][%s][%s] ", + g_device_mac, + timestamp, + TraceContext::TraceId()); + } + const int message_size = std::vfprintf(stdout, format, arguments); + g_at_line_start = FormatEndsLine(format); + funlockfile(stdout); + return SumPrinted(prefix_size, message_size); +} + +} // namespace borla diff --git a/main/diagnostics/device_log_formatter.h b/main/diagnostics/device_log_formatter.h new file mode 100644 index 0000000..7255a08 --- /dev/null +++ b/main/diagnostics/device_log_formatter.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace borla { + +// Installs a process-wide ESP_LOG output formatter. Runtime log lines become: +// [AA:BB:CC:DD:EE:FF][2026-07-21 14:23:09.962] I Tag: message +// Before the server synchronizes the clock, the time field explicitly reports +// TIME-UNSYNCED plus monotonic milliseconds instead of a misleading 1970 date. +class DeviceLogFormatter final { +public: + static bool Initialize(); + static void MarkClockSynchronized(); + +private: + static int Print(const char* format, va_list arguments); +}; + +} // namespace borla diff --git a/main/diagnostics/runtime_diagnostics_service.cc b/main/diagnostics/runtime_diagnostics_service.cc new file mode 100644 index 0000000..8adfd43 --- /dev/null +++ b/main/diagnostics/runtime_diagnostics_service.cc @@ -0,0 +1,206 @@ +#include "diagnostics/runtime_diagnostics_service.h" + +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "RuntimeDiagnostics2"; +constexpr UBaseType_t kLowStackWarningBytes = 512; +constexpr UBaseType_t kIpcLowStackWarningBytes = 384; + +bool IsIpcTask(const char* name) +{ + return name != nullptr && + (std::strcmp(name, "ipc0") == 0 || + std::strcmp(name, "ipc1") == 0); +} + +} // namespace + +RuntimeDiagnosticsService::~RuntimeDiagnosticsService() +{ + running_.store(false); + if (task_ != nullptr) { + vTaskDeleteWithCaps(task_); + task_ = nullptr; + } + heap_caps_free(task_statuses_); + task_statuses_ = nullptr; +} + +bool RuntimeDiagnosticsService::Initialize() +{ + if (task_ != nullptr && task_statuses_ != nullptr) { + return true; + } + + task_statuses_ = static_cast(heap_caps_calloc(kMaximumTasks, + sizeof(TaskStatus_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + if (task_statuses_ == nullptr) { + ESP_LOGE(kTag, "task snapshot buffer allocation failed"); + return false; + } + + running_.store(true); + const BaseType_t result = xTaskCreateWithCaps( + &RuntimeDiagnosticsService::TaskEntry, + "runtime_diag2", + task_stack_budget::kRuntimeDiagnosticsBytes, + this, + 2, + &task_, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + if (result != pdPASS) { + running_.store(false); + task_ = nullptr; + heap_caps_free(task_statuses_); + task_statuses_ = nullptr; + ESP_LOGE(kTag, "diagnostics worker creation failed"); + return false; + } + ESP_LOGI(kTag, "worker started stack_bytes=%u memory=PSRAM", + static_cast( + task_stack_budget::kRuntimeDiagnosticsBytes)); + return true; +} + +void RuntimeDiagnosticsService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void RuntimeDiagnosticsService::Run() +{ + uint32_t snapshot_due_ms = kInitialDelayMs; + while (running_.load()) { + vTaskDelay(pdMS_TO_TICKS(kFrameStatsPeriodMs)); + if (!running_.load()) { + break; + } + + IAudioEngine* audio = audio_.load(); + if (audio != nullptr) { + // Returns false and logs nothing while the microphone is off. + audio->LogAudioFrameStats(); + } + + elapsed_since_snapshot_ms_ += kFrameStatsPeriodMs; + if (elapsed_since_snapshot_ms_ < snapshot_due_ms) { + continue; + } + elapsed_since_snapshot_ms_ = 0; + LogSnapshot(); + ++snapshots_logged_; + snapshot_due_ms = snapshots_logged_ == 1 + ? kSecondSnapshotDelayMs + : kSnapshotPeriodMs; + } + for (;;) { + vTaskSuspend(nullptr); + } +} + +void RuntimeDiagnosticsService::SetAudioEngine(IAudioEngine* audio) +{ + audio_.store(audio); +} + +void RuntimeDiagnosticsService::LogSnapshot() +{ + IAudioEngine* audio = audio_.load(); + if (audio != nullptr && + esp_log_level_get(kTag) >= ESP_LOG_DEBUG) { + // Cumulative capture/voice counters. Steady-state they repeat the + // per-window "duplex window closed" line, so they are debug-only; the + // dynamic level check keeps them one menuconfig switch away. + audio->LogAudioMetrics("periodic"); + } + const size_t internal_free + = heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + const size_t internal_minimum = heap_caps_get_minimum_free_size( + MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + const size_t internal_largest = heap_caps_get_largest_free_block( + MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + const size_t psram_free + = heap_caps_get_free_size(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + const size_t psram_minimum + = heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + const size_t psram_largest + = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + + // A heap that is holding steady is not news. INFO is reserved for the two + // states that demand eyes: the internal low-water mark just sank (a new + // worst case happened since the last report), or free space is inside the + // zone where lwIP/TLS allocations start failing — the exact failure that + // once dropped the WebSocket mid-conversation (free=4415/min=531). + constexpr size_t kInternalFreeAlarmBytes = 20 * 1024; + const bool degraded = + internal_minimum < reported_internal_minimum_ || + internal_free < kInternalFreeAlarmBytes; + if (degraded) { + reported_internal_minimum_ = internal_minimum; + ESP_LOGI(kTag, + "heap internal free=%u min=%u largest=%u; " + "psram free=%u min=%u largest=%u", + static_cast(internal_free), + static_cast(internal_minimum), + static_cast(internal_largest), + static_cast(psram_free), + static_cast(psram_minimum), + static_cast(psram_largest)); + } else { + ESP_LOGD(kTag, + "heap internal free=%u min=%u largest=%u; " + "psram free=%u min=%u largest=%u", + static_cast(internal_free), + static_cast(internal_minimum), + static_cast(internal_largest), + static_cast(psram_free), + static_cast(psram_minimum), + static_cast(psram_largest)); + } + + const UBaseType_t expected = uxTaskGetNumberOfTasks(); + if (expected > kMaximumTasks) { + ESP_LOGW(kTag, "task snapshot skipped: tasks=%u capacity=%u", + static_cast(expected), + static_cast(kMaximumTasks)); + return; + } + + const UBaseType_t count + = uxTaskGetSystemState(task_statuses_, kMaximumTasks, nullptr); + // The stack budgets were tuned from these lines and have been stable + // since; ~30 healthy rows per snapshot were drowning the conversation + // log. Healthy tasks report at DEBUG now — only a LOW watermark, the one + // thing that demands action, stays visible by default. + ESP_LOGD(kTag, "task snapshot count=%u", static_cast(count)); + for (UBaseType_t index = 0; index < count; ++index) { + const TaskStatus_t& status = task_statuses_[index]; + const UBaseType_t warning_threshold = + IsIpcTask(status.pcTaskName) + ? kIpcLowStackWarningBytes + : kLowStackWarningBytes; + const bool low = + status.usStackHighWaterMark < warning_threshold; + if (low) { + ESP_LOGW(kTag, + "task=%s state=%u priority=%u stack_free_bytes=%u LOW", + status.pcTaskName, static_cast(status.eCurrentState), + static_cast(status.uxCurrentPriority), + static_cast(status.usStackHighWaterMark)); + } else { + ESP_LOGD(kTag, "task=%s state=%u priority=%u stack_free_bytes=%u", + status.pcTaskName, static_cast(status.eCurrentState), + static_cast(status.uxCurrentPriority), + static_cast(status.usStackHighWaterMark)); + } + } +} + +} // namespace borla diff --git a/main/diagnostics/runtime_diagnostics_service.h b/main/diagnostics/runtime_diagnostics_service.h new file mode 100644 index 0000000..34d758b --- /dev/null +++ b/main/diagnostics/runtime_diagnostics_service.h @@ -0,0 +1,59 @@ +#pragma once + +#include "core/task_stack_budget.h" +#include "ports/audio_engine.h" + +#include +#include + +#include +#include + +namespace borla { + +// Periodically reports heap health and every FreeRTOS task's remaining stack. +// The snapshot buffer and worker stack live in PSRAM so diagnostics do not run +// heavy task enumeration/logging on the shared esp_timer task. +class RuntimeDiagnosticsService final { +public: + RuntimeDiagnosticsService() = default; + ~RuntimeDiagnosticsService(); + + RuntimeDiagnosticsService(const RuntimeDiagnosticsService&) = delete; + RuntimeDiagnosticsService& operator=(const RuntimeDiagnosticsService&) + = delete; + + bool Initialize(); + // Optional. When set, each snapshot also emits the voice frontend + // counters, which are the only way to see AEC reference misses. + void SetAudioEngine(IAudioEngine* audio); + void LogSnapshot(); + +private: + static constexpr size_t kMaximumTasks = 64; + static constexpr uint32_t kInitialDelayMs = 5 * 1000; + static constexpr uint32_t kSecondSnapshotDelayMs = 25 * 1000; + static constexpr uint32_t kSnapshotPeriodMs = 5 * 60 * 1000; + // The worker now ticks fast and emits the audio frame statistics on every + // tick, because the capture DSP chain has to be watched while a + // conversation is happening, not once every five minutes. The tick is + // silent whenever the microphone is off, so an idle device stays quiet. + // The heavy heap/task snapshot keeps its original cadence. + static constexpr uint32_t kFrameStatsPeriodMs = 2 * 1000; + + static void TaskEntry(void* context); + [[noreturn]] void Run(); + + std::atomic audio_{nullptr}; + TaskHandle_t task_ = nullptr; + TaskStatus_t* task_statuses_ = nullptr; + size_t snapshots_logged_ = 0; + uint32_t elapsed_since_snapshot_ms_ = 0; + // Low-water mark of the internal heap at the last INFO-level heap report. + // The heap line only earns INFO when this drops (or free space is + // critically low); a steady heap reports at DEBUG. + size_t reported_internal_minimum_ = SIZE_MAX; + std::atomic running_{false}; +}; + +} // namespace borla diff --git a/main/diagnostics/trace_context.cc b/main/diagnostics/trace_context.cc new file mode 100644 index 0000000..13bae70 --- /dev/null +++ b/main/diagnostics/trace_context.cc @@ -0,0 +1,142 @@ +#include "diagnostics/trace_context.h" + +#include +#include + +#if __has_include() +#include +#define BORLA_TRACE_HAS_ESP_TIMER 1 +#else +#include +#define BORLA_TRACE_HAS_ESP_TIMER 0 +#endif + +namespace borla { +namespace { + +constexpr const char kUnset[] = "-"; + +char g_device_id[TraceContext::kIdCapacity] = "dev"; +char g_trace_id[TraceContext::kIdCapacity] = "-"; +char g_session_id[TraceContext::kIdCapacity] = "-"; +char g_request_id[TraceContext::kIdCapacity] = "-"; + +uint64_t MonotonicMs() +{ +#if BORLA_TRACE_HAS_ESP_TIMER + return static_cast(esp_timer_get_time() / 1000LL); +#else + using namespace std::chrono; + return static_cast( + duration_cast( + steady_clock::now().time_since_epoch()) + .count()); +#endif +} + +} // namespace + +size_t TraceContext::FormatId( + const char* prefix, + const char* device_id, + uint64_t monotonic_ms, + char* output, + size_t capacity) +{ + if (output == nullptr || capacity == 0) { + return 0; + } + const char* safe_prefix = + prefix != nullptr && prefix[0] != '\0' ? prefix : "dev"; + const char* safe_device = + device_id != nullptr && device_id[0] != '\0' ? device_id : "dev"; + const int written = std::snprintf( + output, + capacity, + "%s-%s-%llu", + safe_prefix, + safe_device, + static_cast(monotonic_ms)); + if (written < 0) { + output[0] = '\0'; + return 0; + } + // snprintf already truncated and terminated; report what actually fits so + // callers never see a length past the buffer. + return static_cast(written) < capacity + ? static_cast(written) + : capacity - 1; +} + +void TraceContext::Assign( + const char* value, + char* output, + size_t capacity) +{ + if (output == nullptr || capacity == 0) { + return; + } + if (value == nullptr || value[0] == '\0') { + std::snprintf(output, capacity, "%s", kUnset); + return; + } + std::snprintf(output, capacity, "%s", value); +} + +void TraceContext::Initialize(const char* device_id) +{ + // MAC colons would collide with the "field=value" log grammar the server + // greps, so they are folded to dashes here once. + char sanitized[kIdCapacity]{}; + std::snprintf( + sanitized, + sizeof(sanitized), + "%s", + device_id != nullptr && device_id[0] != '\0' ? device_id : "dev"); + for (size_t index = 0; sanitized[index] != '\0'; ++index) { + if (sanitized[index] == ':' || sanitized[index] == ' ') { + sanitized[index] = '-'; + } + } + std::memcpy(g_device_id, sanitized, sizeof(g_device_id)); + g_device_id[sizeof(g_device_id) - 1] = '\0'; +} + +void TraceContext::RefreshTrace(const char* prefix) +{ + FormatId( + prefix, g_device_id, MonotonicMs(), + g_trace_id, sizeof(g_trace_id)); +} + +const char* TraceContext::NewRequestId() +{ + FormatId( + "req", g_device_id, MonotonicMs(), + g_request_id, sizeof(g_request_id)); + return g_request_id; +} + +const char* TraceContext::RefreshSession() +{ + FormatId( + "s", g_device_id, MonotonicMs(), + g_session_id, sizeof(g_session_id)); + return g_session_id; +} + +void TraceContext::SetSession(const char* session_id) +{ + Assign(session_id, g_session_id, sizeof(g_session_id)); +} + +void TraceContext::SetTrace(const char* trace_id) +{ + Assign(trace_id, g_trace_id, sizeof(g_trace_id)); +} + +const char* TraceContext::TraceId() { return g_trace_id; } +const char* TraceContext::SessionId() { return g_session_id; } +const char* TraceContext::RequestId() { return g_request_id; } + +} // namespace borla diff --git a/main/diagnostics/trace_context.h b/main/diagnostics/trace_context.h new file mode 100644 index 0000000..95494b3 --- /dev/null +++ b/main/diagnostics/trace_context.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include + +namespace borla { + +// Correlation ids shared with server and backend (see docs/0019 §10.1). +// +// session connection scope · refreshed on every realtime session +// trace turn scope · refreshed when the device starts an exchange +// request call scope · refreshed per HTTP/OTA call +// +// Every id is a fixed-capacity C string with no allocation, so it is safe to +// read from a log formatter that runs on any task. Values are written only by +// the owning subsystem and read everywhere; readers may observe a value that +// is one refresh stale, which is acceptable for correlation. +class TraceContext final { +public: + static constexpr size_t kIdCapacity = 64; + + // Never null; "-" when nothing has been set yet. + static const char* TraceId(); + static const char* SessionId(); + static const char* RequestId(); + + // Seeds the device-side portion of every generated id. Called once with + // the device MAC so ids are globally attributable without a UUID library. + static void Initialize(const char* device_id); + + // Generates "--" and installs it. + static void RefreshTrace(const char* prefix); + // Returns the freshly generated id so the caller can put it in a header. + static const char* NewRequestId(); + // Mints a session id for the connection that is about to be opened, and + // returns it for the handshake header. + // + // Required because the session is connection-scoped. Without it the id is + // still "-" on the first connect (which the server would adopt verbatim, + // since "-" is a non-empty string) and is the *previous* connection's id on + // every reconnect, merging two unrelated sessions under one id. The server + // overwrites this with its own id in ServerHello, so this is a proposal, + // not a decision. + static const char* RefreshSession(); + + // Adopts an id handed down by the server (ServerHello session id). + static void SetSession(const char* session_id); + static void SetTrace(const char* trace_id); + + // Pure formatter, exposed for tests: "--", truncated + // to fit and always NUL-terminated. Returns the written length. + static size_t FormatId( + const char* prefix, + const char* device_id, + uint64_t monotonic_ms, + char* output, + size_t capacity); + +private: + static void Assign( + const char* value, + char* output, + size_t capacity); +}; + +} // namespace borla diff --git a/main/friend/friend_service.cc b/main/friend/friend_service.cc new file mode 100644 index 0000000..7bf0627 --- /dev/null +++ b/main/friend/friend_service.cc @@ -0,0 +1,266 @@ +#include "friend/friend_service.h" + +#include + +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "FriendService2"; +constexpr uint32_t kFriendStartError = 12201; +constexpr uint32_t kFriendStoreError = 12202; + +template +bool CopyString( + const char* value, + std::array* output) +{ + if (value == nullptr || output == nullptr) { + return false; + } + const size_t size = std::strlen(value); + if (size == 0 || size >= Capacity) { + return false; + } + output->fill('\0'); + std::memcpy(output->data(), value, size); + return true; +} + +} // namespace + +FriendService::FriendService( + BleFriendExchange& exchange, + IFriendStore& store, + IRealtimeProtocol& realtime,IConnectivityManager& connectivity) + : exchange_(exchange), + store_(store), + realtime_(realtime), + connectivity_(connectivity)//2026-9-7 ckkj add +{ +} + +bool FriendService::Initialize( + const DeviceIdentity& identity, + IEventPublisher& publisher) +{ + if (initialized_.load()) { + return true; + } + if (!CopyString(identity.mac, &local_mac_) || + !BuildFriendAdvertisingName( + identity.mac, + fallback_name_.data(), + fallback_name_.size()) || + !store_.Load(&snapshot_) || + !exchange_.Initialize()) { + return false; + } + queue_ = xQueueCreateStatic( + kQueueDepth, + sizeof(Command), + queue_storage_.data(), + &queue_control_); + if (queue_ == nullptr) { + return false; + } + task_ = xTaskCreateStatic( + &FriendService::TaskEntry, + "friend_service2", + task_stack_.size(), + this, + kTaskPriority, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + return false; + } + publisher_ = &publisher; + initialized_.store(true); + return true; +} + +void FriendService::Start() +{ + if (!Post({CommandType::kStart})) { + ESP_LOGE(kTag, "failed to enqueue friend start"); + } +} + +void FriendService::Stop() +{ + Post({CommandType::kStop}); +} + +void FriendService::SetDeviceName(const char* device_name) +{ + Command command; + command.type = CommandType::kSetDeviceName; + if (CopyString(device_name, &command.device_name)) { + Post(command); + } +} + +void FriendService::OnBleFriendMatched(const FriendPeer& peer) +{ + Command command; + command.type = CommandType::kMatched; + command.peer = peer; + Post(command); +} + +void FriendService::OnBleFriendExchangeStopped( + bool paired, + uint32_t error_id) +{ + Command command; + command.type = CommandType::kExchangeStopped; + command.paired = paired; + command.error_id = error_id; + Post(command); +} + +void FriendService::OnApplicationEvent( + const AppEvent& event, + const RuntimeState&) +{ + if (event.type == AppEventType::kRealtimeConnected) { + Post({CommandType::kUploadPending}); + } +} + +void FriendService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void FriendService::Run() +{ + while (true) { + Command command; + if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) { + Handle(command); + } + } +} + +bool FriendService::Post(const Command& command) +{ + return initialized_.load() && queue_ != nullptr && + xQueueSend(queue_, &command, 0) == pdTRUE; +} + +void FriendService::Handle(const Command& command) +{ + switch (command.type) { + case CommandType::kStart: + HandleStart(); + return; + case CommandType::kStop: + exchange_.Stop(); + return; + case CommandType::kMatched: + HandleMatched(command.peer); + return; + case CommandType::kExchangeStopped: + // 2026-9-7 ckkj add: BLE 会话已结束(BleFriendExchange 在 + // nimble_port_deinit 释放 BT 内存后才回调),立即恢复网络。 + connectivity_.ResumeAfterBle();///// + if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kFriendModeEnded, + command.error_id, + 0, + command.paired ? 1U : 0U)); + } + return; + case CommandType::kSetDeviceName: + HandleSetDeviceName(command.device_name.data()); + return; + case CommandType::kUploadPending: + UploadPending(); + return; + } +} + +void FriendService::HandleStart() +{ + if (exchange_.IsActive()) { + return; + } + // if (!exchange_.Start(local_mac_.data(), *this) && + // publisher_ != nullptr) { + // publisher_->Publish(AppEvent::Make( + // AppEventType::kFriendModeEnded, + // kFriendStartError)); + // 2026-9-7 ckkj add: BT 控制器需要 ~65KB 内部 RAM,与已初始化的 WiFi + // 驱动无法共存,必须在 nimble_port_init 之前拆除驱动,否则 BLE_INIT + // "Malloc failed" 后 controller 内部直接 panic。结束时在 + // kExchangeStopped 恢复;启动请求本身失败也立即恢复,避免网络永久挂起。 + connectivity_.SuspendForBle(); + if (!exchange_.Start(local_mac_.data(), *this)) { + connectivity_.ResumeAfterBle(); + if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kFriendModeEnded, + kFriendStartError)); + } + } +} + +void FriendService::HandleMatched(const FriendPeer& peer) +{ + if (!AddOrUpdateFriend(&snapshot_, peer)) { + if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, + kFriendStoreError)); + } + return; + } + snapshot_.pending_upload = peer; + snapshot_.has_pending_upload = true; + if (!store_.Save(snapshot_) && publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, + kFriendStoreError)); + } +} + +void FriendService::HandleSetDeviceName(const char* device_name) +{ + if (CopyString(device_name, &snapshot_.device_name) && + !store_.Save(snapshot_)) { + ESP_LOGE(kTag, "device name persistence failed"); + } +} + +void FriendService::UploadPending() +{ + if (!snapshot_.has_pending_upload) { + return; + } + if (!realtime_.SendFriendAdd( + local_mac_.data(), + LocalName(), + snapshot_.pending_upload.mac.data(), + snapshot_.pending_upload.name.data())) { + ESP_LOGW(kTag, "friend_add deferred until next reconnect"); + return; + } + snapshot_.has_pending_upload = false; + snapshot_.pending_upload = {}; + if (!store_.Save(snapshot_)) { + ESP_LOGE(kTag, "pending friend clear persistence failed"); + } +} + +const char* FriendService::LocalName() +{ + return snapshot_.device_name[0] != '\0' + ? snapshot_.device_name.data() + : fallback_name_.data(); +} + +} // namespace borla diff --git a/main/friend/friend_service.h b/main/friend/friend_service.h new file mode 100644 index 0000000..66b6acc --- /dev/null +++ b/main/friend/friend_service.h @@ -0,0 +1,104 @@ +#pragma once + +#include "core/task_stack_budget.h" +#include "friend/friend_store.h" +#include "platform/borla_s3/ble_friend_exchange.h" +#include "ports/application_observer.h" +#include "ports/device_platform.h" +#include "ports/device_profile_sink.h" +#include "ports/event_publisher.h" +#include "ports/friend_service.h" +#include "ports/realtime_protocol.h" +#include "ports/connectivity_manager.h" +#include +#include +#include +#include + +#include +#include +#include + +namespace borla { + +class FriendService final + : public IFriendService, + public IBleFriendExchangeObserver, + public IDeviceProfileSink, + public IApplicationObserver { +public: + FriendService( + BleFriendExchange& exchange, + IFriendStore& store, + IRealtimeProtocol& realtime, + IConnectivityManager& connectivity);//2026-9-7 ckkj add + + bool Initialize( + const DeviceIdentity& identity, + IEventPublisher& publisher); + void Start() override; + void Stop() override; + void SetDeviceName(const char* device_name) override; + void OnBleFriendMatched(const FriendPeer& peer) override; + void OnBleFriendExchangeStopped( + bool paired, + uint32_t error_id) override; + void OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) override; + +private: + enum class CommandType : uint8_t { + kStart, + kStop, + kMatched, + kExchangeStopped, + kSetDeviceName, + kUploadPending, + }; + + struct Command { + CommandType type = CommandType::kStart; + FriendPeer peer{}; + std::array device_name{}; + uint32_t error_id = 0; + bool paired = false; + }; + + static constexpr size_t kQueueDepth = 10; + static constexpr UBaseType_t kTaskPriority = 5; + + static void TaskEntry(void* context); + [[noreturn]] void Run(); + bool Post(const Command& command); + void Handle(const Command& command); + void HandleStart(); + void HandleMatched(const FriendPeer& peer); + void HandleSetDeviceName(const char* device_name); + void UploadPending(); + const char* LocalName(); + + BleFriendExchange& exchange_; + IFriendStore& store_; + IRealtimeProtocol& realtime_; + IConnectivityManager& connectivity_;//2026-9-7 ckkj add + IEventPublisher* publisher_ = nullptr; + FriendStoreSnapshot snapshot_{}; + std::array local_mac_{}; + std::array + fallback_name_{}; + + QueueHandle_t queue_ = nullptr; + StaticQueue_t queue_control_{}; + alignas(Command) + std::array + queue_storage_{}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array< + StackType_t, + task_stack_budget::kFriendServiceBytes> task_stack_{}; + std::atomic initialized_{false}; +}; + +} // namespace borla diff --git a/main/friend/friend_store.cc b/main/friend/friend_store.cc new file mode 100644 index 0000000..4eeb49d --- /dev/null +++ b/main/friend/friend_store.cc @@ -0,0 +1,313 @@ +#include "friend/friend_store.h" + +#include "core/psram_object.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "FriendStore2"; +constexpr const char* kNamespace = "friend_v2"; +constexpr const char* kSnapshotKey = "snapshot"; +constexpr uint32_t kMagic = 0x32444E46; +constexpr uint16_t kVersion = 1; +constexpr const char* kLegacyDeviceNamespace = "device"; +constexpr const char* kLegacyDeviceNameKey = "name"; +constexpr const char* kLegacyFriendsNamespace = "friends"; +constexpr const char* kLegacyFriendCountKey = "count"; + +struct PersistedFriendSnapshot { + uint32_t magic = kMagic; + uint16_t version = kVersion; + uint16_t friend_count = 0; + uint8_t has_pending_upload = 0; + uint8_t reserved[3]{}; + char device_name[kFriendNameCapacity]{}; + FriendPeer friends[kMaximumFriendCount]{}; + FriendPeer pending_upload{}; + uint32_t checksum = 0; +}; + +uint32_t Checksum(const void* data, size_t size) +{ + const auto* bytes = static_cast(data); + uint32_t value = 2166136261U; + for (size_t index = 0; index < size; ++index) { + value ^= bytes[index]; + value *= 16777619U; + } + return value; +} + +bool PeerValid(const FriendPeer& peer) +{ + return peer.mac[0] != '\0' && + std::memchr(peer.mac.data(), '\0', peer.mac.size()) != nullptr && + std::memchr(peer.name.data(), '\0', peer.name.size()) != nullptr; +} + +template +bool CopyString( + const char* value, + std::array* output) +{ + if (value == nullptr || output == nullptr) { + return false; + } + const size_t length = std::strlen(value); + if (length == 0 || length >= Capacity) { + return false; + } + output->fill('\0'); + std::memcpy(output->data(), value, length); + return true; +} + +bool LoadLegacy(FriendStoreSnapshot* snapshot) +{ + bool migrated = false; + nvs_handle_t device_handle = 0; + if (nvs_open( + kLegacyDeviceNamespace, + NVS_READONLY, + &device_handle) == ESP_OK) { + size_t size = snapshot->device_name.size(); + if (nvs_get_str( + device_handle, + kLegacyDeviceNameKey, + snapshot->device_name.data(), + &size) == ESP_OK && + snapshot->device_name[0] != '\0') { + migrated = true; + } else { + snapshot->device_name.fill('\0'); + } + nvs_close(device_handle); + } + + nvs_handle_t friends_handle = 0; + if (nvs_open( + kLegacyFriendsNamespace, + NVS_READONLY, + &friends_handle) != ESP_OK) { + return migrated; + } + int32_t count = 0; + if (nvs_get_i32( + friends_handle, + kLegacyFriendCountKey, + &count) != ESP_OK || + count <= 0) { + nvs_close(friends_handle); + return migrated; + } + count = std::min( + count, static_cast(kMaximumFriendCount)); + for (int32_t index = 0; index < count; ++index) { + char key[16]{}; + std::snprintf(key, sizeof(key), "f_%u", + static_cast(index)); + std::array json{}; + size_t size = json.size(); + if (nvs_get_str( + friends_handle, + key, + json.data(), + &size) != ESP_OK) { + continue; + } + cJSON* root = cJSON_Parse(json.data()); + const cJSON* mac = + cJSON_GetObjectItemCaseSensitive(root, "mac"); + const cJSON* name = + cJSON_GetObjectItemCaseSensitive(root, "name"); + FriendPeer peer; + const bool valid = + cJSON_IsString(mac) && + cJSON_IsString(name) && + CopyString(mac->valuestring, &peer.mac) && + CopyString(name->valuestring, &peer.name); + cJSON_Delete(root); + if (valid && AddOrUpdateFriend(snapshot, peer)) { + migrated = true; + } + } + nvs_close(friends_handle); + return migrated; +} + +} // namespace + +bool NvsFriendStore::Load(FriendStoreSnapshot* snapshot) const +{ + if (snapshot == nullptr) { + return false; + } + auto legacy = MakePsramObject(); + auto stored = MakePsramObject(); + if (!legacy || !stored) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + return false; + } + const bool has_legacy = LoadLegacy(legacy.get()); + *snapshot = {}; + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNamespace, NVS_READONLY, &handle); + if (result == ESP_ERR_NVS_NOT_FOUND) { + *snapshot = *legacy; + if (has_legacy) { + ESP_LOGI(kTag, "migrated legacy friends/device name"); + Save(*snapshot); + } + return true; + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "open failed: %s", esp_err_to_name(result)); + return false; + } + size_t size = sizeof(*stored); + result = nvs_get_blob( + handle, kSnapshotKey, stored.get(), &size); + nvs_close(handle); + if (result == ESP_ERR_NVS_NOT_FOUND) { + *snapshot = *legacy; + if (has_legacy) { + ESP_LOGI(kTag, "migrated legacy friends/device name"); + Save(*snapshot); + } + return true; + } + const uint32_t expected = Checksum( + stored.get(), offsetof(PersistedFriendSnapshot, checksum)); + if (result != ESP_OK || size != sizeof(*stored) || + stored->magic != kMagic || stored->version != kVersion || + stored->friend_count > kMaximumFriendCount || + stored->checksum != expected || + std::memchr( + stored->device_name, + '\0', + sizeof(stored->device_name)) == nullptr) { + ESP_LOGE(kTag, "invalid persisted friend snapshot"); + return false; + } + snapshot->friend_count = stored->friend_count; + std::memcpy( + snapshot->device_name.data(), + stored->device_name, + snapshot->device_name.size()); + for (size_t index = 0; + index < snapshot->friend_count; + ++index) { + if (!PeerValid(stored->friends[index])) { + return false; + } + snapshot->friends[index] = stored->friends[index]; + } + snapshot->has_pending_upload = + stored->has_pending_upload != 0; + if (snapshot->has_pending_upload) { + if (!PeerValid(stored->pending_upload)) { + return false; + } + snapshot->pending_upload = stored->pending_upload; + } + if (snapshot->device_name[0] == '\0' && + legacy->device_name[0] != '\0') { + snapshot->device_name = legacy->device_name; + Save(*snapshot); + } + return true; +} + +bool NvsFriendStore::Save(const FriendStoreSnapshot& snapshot) const +{ + if (snapshot.friend_count > kMaximumFriendCount || + std::memchr( + snapshot.device_name.data(), + '\0', + snapshot.device_name.size()) == nullptr || + (snapshot.has_pending_upload && + !PeerValid(snapshot.pending_upload))) { + return false; + } + auto stored = MakePsramObject(); + if (!stored) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + return false; + } + stored->friend_count = + static_cast(snapshot.friend_count); + stored->has_pending_upload = + snapshot.has_pending_upload ? 1 : 0; + std::memcpy( + stored->device_name, + snapshot.device_name.data(), + snapshot.device_name.size()); + for (size_t index = 0; + index < snapshot.friend_count; + ++index) { + if (!PeerValid(snapshot.friends[index])) { + return false; + } + stored->friends[index] = snapshot.friends[index]; + } + stored->pending_upload = snapshot.pending_upload; + stored->checksum = Checksum( + stored.get(), offsetof(PersistedFriendSnapshot, checksum)); + + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNamespace, NVS_READWRITE, &handle); + if (result == ESP_OK) { + result = nvs_set_blob( + handle, kSnapshotKey, stored.get(), sizeof(*stored)); + } + if (result == ESP_OK) { + result = nvs_commit(handle); + } + if (handle != 0) { + nvs_close(handle); + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "save failed: %s", esp_err_to_name(result)); + return false; + } + return true; +} + +bool AddOrUpdateFriend( + FriendStoreSnapshot* snapshot, + const FriendPeer& peer) +{ + if (snapshot == nullptr || !PeerValid(peer)) { + return false; + } + for (size_t index = 0; + index < snapshot->friend_count; + ++index) { + if (std::strcmp( + snapshot->friends[index].mac.data(), + peer.mac.data()) == 0) { + snapshot->friends[index] = peer; + return true; + } + } + if (snapshot->friend_count >= snapshot->friends.size()) { + return false; + } + snapshot->friends[snapshot->friend_count++] = peer; + return true; +} + +} // namespace borla diff --git a/main/friend/friend_store.h b/main/friend/friend_store.h new file mode 100644 index 0000000..8d16f7d --- /dev/null +++ b/main/friend/friend_store.h @@ -0,0 +1,35 @@ +#pragma once + +#include "friend/friend_types.h" + +#include +#include + +namespace borla { + +struct FriendStoreSnapshot { + std::array device_name{}; + std::array friends{}; + size_t friend_count = 0; + FriendPeer pending_upload{}; + bool has_pending_upload = false; +}; + +class IFriendStore { +public: + virtual ~IFriendStore() = default; + virtual bool Load(FriendStoreSnapshot* snapshot) const = 0; + virtual bool Save(const FriendStoreSnapshot& snapshot) const = 0; +}; + +class NvsFriendStore final : public IFriendStore { +public: + bool Load(FriendStoreSnapshot* snapshot) const override; + bool Save(const FriendStoreSnapshot& snapshot) const override; +}; + +bool AddOrUpdateFriend( + FriendStoreSnapshot* snapshot, + const FriendPeer& peer); + +} // namespace borla diff --git a/main/friend/friend_types.cc b/main/friend/friend_types.cc new file mode 100644 index 0000000..a5259fd --- /dev/null +++ b/main/friend/friend_types.cc @@ -0,0 +1,215 @@ +#include "friend/friend_types.h" + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kFriendPrefix = "BorlaF-"; + +template +bool CopyString(const char* value, std::array* output) +{ + if (value == nullptr || output == nullptr) { + return false; + } + const size_t size = std::strlen(value); + if (size == 0 || size >= Capacity) { + return false; + } + output->fill('\0'); + std::memcpy(output->data(), value, size); + return true; +} + +bool IsFriendName(const char* name) +{ + return name != nullptr && + std::strncmp(name, kFriendPrefix, std::strlen(kFriendPrefix)) == 0; +} + +} // namespace + +bool FriendCandidateSelector::Observe( + const char* ble_mac, + const char* advertising_name, + int8_t rssi_dbm, + uint64_t now_ms) +{ + if (!IsFriendName(advertising_name) || + ble_mac == nullptr || now_ms == 0) { + return false; + } + + FriendCandidate* slot = nullptr; + FriendCandidate* oldest = nullptr; + for (FriendCandidate& candidate : candidates_) { + if (candidate.occupied && + std::strcmp(candidate.peer.mac.data(), ble_mac) == 0) { + slot = &candidate; + break; + } + if (!candidate.occupied && slot == nullptr) { + slot = &candidate; + } + if (candidate.occupied && + (oldest == nullptr || + candidate.last_seen_ms < oldest->last_seen_ms)) { + oldest = &candidate; + } + } + if (slot == nullptr) { + slot = oldest; + } + if (slot == nullptr) { + return false; + } + + if (!slot->occupied || + std::strcmp(slot->peer.mac.data(), ble_mac) != 0) { + *slot = {}; + if (!CopyString(ble_mac, &slot->peer.mac) || + !CopyString(advertising_name, &slot->peer.name)) { + *slot = {}; + return false; + } + slot->best_rssi_dbm = rssi_dbm; + slot->occupied = true; + } else { + CopyString(advertising_name, &slot->peer.name); + slot->best_rssi_dbm = + std::max(slot->best_rssi_dbm, rssi_dbm); + } + if (slot->seen_count != UINT8_MAX) { + slot->seen_count++; + } + slot->last_seen_ms = now_ms; + return true; +} + +bool FriendCandidateSelector::Select( + uint64_t now_ms, + FriendPeer* peer) +{ + if (peer == nullptr) { + return false; + } + FriendCandidate* best = nullptr; + for (FriendCandidate& candidate : candidates_) { + if (!candidate.occupied) { + continue; + } + if (now_ms < candidate.last_seen_ms || + now_ms - candidate.last_seen_ms > kStaleAfterMs) { + candidate = {}; + continue; + } + const bool eligible = + candidate.best_rssi_dbm >= kStrongRssiDbm || + (candidate.best_rssi_dbm >= kWeakRssiDbm && + candidate.seen_count >= kWeakMinimumSeen); + if (eligible && + (best == nullptr || + candidate.best_rssi_dbm > best->best_rssi_dbm)) { + best = &candidate; + } + } + if (best == nullptr) { + return false; + } + *peer = best->peer; + return NormalizeBleMacToBaseMac( + best->peer.mac.data(), + peer->mac.data(), + peer->mac.size()); +} + +void FriendCandidateSelector::Reset() +{ + candidates_.fill(FriendCandidate{}); +} + +bool NormalizeBleMacToBaseMac( + const char* ble_mac, + char* base_mac, + size_t capacity) +{ + if (ble_mac == nullptr || base_mac == nullptr || + capacity < kFriendMacCapacity) { + return false; + } + unsigned values[6]{}; + char trailing = '\0'; + if (std::sscanf( + ble_mac, + "%2x:%2x:%2x:%2x:%2x:%2x%c", + &values[0], + &values[1], + &values[2], + &values[3], + &values[4], + &values[5], + &trailing) != 6) { + return false; + } + uint64_t value = 0; + for (unsigned octet : values) { + if (octet > 0xFFU) { + return false; + } + value = (value << 8U) | octet; + } + if (value < 2) { + return false; + } + value -= 2; + // Lower case, non-negotiable. The normalized base MAC is the peer + // device's device_id, sent verbatim in friend_add, and the server matches + // device ids case-sensitively — the same contract that made the uppercase + // MAC in borla_s3_platform.cc loop the activation prompt forever. The + // previous firmware's BleMacToBaseMac emitted lower case here too. + const int written = std::snprintf( + base_mac, + capacity, + "%02x:%02x:%02x:%02x:%02x:%02x", + static_cast((value >> 40U) & 0xFFU), + static_cast((value >> 32U) & 0xFFU), + static_cast((value >> 24U) & 0xFFU), + static_cast((value >> 16U) & 0xFFU), + static_cast((value >> 8U) & 0xFFU), + static_cast(value & 0xFFU)); + return written == 17; +} + +bool BuildFriendAdvertisingName( + const char* base_mac, + char* output, + size_t capacity) +{ + if (base_mac == nullptr || output == nullptr || + capacity < 12) { + return false; + } + char compact[13]{}; + size_t count = 0; + for (size_t index = 0; + base_mac[index] != '\0' && count < 12; + ++index) { + if (base_mac[index] != ':') { + compact[count++] = base_mac[index]; + } + } + if (count != 12) { + return false; + } + const int written = std::snprintf( + output, + capacity, + "BorlaF-%.4s", + compact + 8); + return written == 11; +} + +} // namespace borla diff --git a/main/friend/friend_types.h b/main/friend/friend_types.h new file mode 100644 index 0000000..d44b224 --- /dev/null +++ b/main/friend/friend_types.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +inline constexpr size_t kFriendMacCapacity = 18; +inline constexpr size_t kFriendNameCapacity = 64; +inline constexpr size_t kFriendAdvertisingNameCapacity = 32; +inline constexpr size_t kMaximumFriendCount = 20; +inline constexpr size_t kMaximumFriendCandidates = 8; + +struct FriendPeer { + std::array mac{}; + std::array name{}; +}; + +struct FriendCandidate { + FriendPeer peer{}; + int8_t best_rssi_dbm = -127; + uint8_t seen_count = 0; + uint64_t last_seen_ms = 0; + bool occupied = false; +}; + +class FriendCandidateSelector final { +public: + static constexpr int8_t kStrongRssiDbm = -60; + static constexpr int8_t kWeakRssiDbm = -85; + static constexpr uint8_t kWeakMinimumSeen = 2; + static constexpr uint64_t kStaleAfterMs = 6000; + + bool Observe( + const char* ble_mac, + const char* advertising_name, + int8_t rssi_dbm, + uint64_t now_ms); + bool Select(uint64_t now_ms, FriendPeer* peer); + void Reset(); + +private: + std::array candidates_{}; +}; + +bool NormalizeBleMacToBaseMac( + const char* ble_mac, + char* base_mac, + size_t capacity); +bool BuildFriendAdvertisingName( + const char* base_mac, + char* output, + size_t capacity); + +} // namespace borla diff --git a/main/idf_component.yml b/main/idf_component.yml new file mode 100644 index 0000000..f69df9f --- /dev/null +++ b/main/idf_component.yml @@ -0,0 +1,8 @@ +dependencies: + idf: ">=5.3,<6.0" + 78/esp-opus: "==1.0.5" + espressif/button: "==4.1.3" + espressif/esp_codec_dev: "==1.4.0" + espressif/esp-dsp: "==1.8.0" + espressif/esp-sr: "==2.5.0" + espressif/led_strip: "==3.0.3" diff --git a/main/main.cc b/main/main.cc new file mode 100644 index 0000000..085c991 --- /dev/null +++ b/main/main.cc @@ -0,0 +1,41 @@ +#include "app/composition_root.h" +#include "diagnostics/device_log_formatter.h" +#include +#include + +#include + +namespace { + +constexpr const char* kTag = "BorlaFirmware2"; +void* PsramCjsonMalloc(size_t size) +{ + return heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); +} + +void PsramCjsonFree(void* pointer) +{ + heap_caps_free(pointer); +} +} // namespace + +extern "C" void app_main() +{ + cJSON_Hooks cjson_hooks = { + PsramCjsonMalloc, + PsramCjsonFree, + }; + cJSON_InitHooks(&cjson_hooks);///修复:全局 cJSON 钩子指向 PSRAM,防止WiFi mem fail + + const bool log_identity_ready = borla::DeviceLogFormatter::Initialize(); + ESP_LOGI(kTag, "starting firmware2 control and playback foundation"); + if (!log_identity_ready) { + ESP_LOGW(kTag, "device MAC unavailable for log prefix"); + } + + static borla::CompositionRoot root; + if (!root.Initialize()) { + ESP_LOGE(kTag, "initialization incomplete; entering fault-capable loop"); + } + root.Run(); +} diff --git a/main/memory/memory_cache.cc b/main/memory/memory_cache.cc new file mode 100644 index 0000000..027c780 --- /dev/null +++ b/main/memory/memory_cache.cc @@ -0,0 +1,228 @@ +#include "memory/memory_cache.h" + +#include "core/psram_object.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "MemoryCache2"; +constexpr const char* kNamespace = "memory2"; +constexpr const char* kSnapshotKey = "snapshot"; +constexpr const char* kLegacyPartitionLabel = "claude_mem"; +constexpr uint32_t kRecordMagic = 0x324D454DU; // "MEM2" +constexpr uint16_t kRecordVersion = 1; +constexpr uint32_t kLegacyMagic = 0x424F524CU; // "BORL" +constexpr size_t kMaximumLegacyJsonBytes = 64 * 1024; + +struct StoredMemoryRecord { + uint32_t magic = kRecordMagic; + uint16_t version = kRecordVersion; + uint16_t reserved = 0; + MemorySnapshot snapshot{}; + uint32_t checksum = 0; +}; + +template +void CopyLegacyTruncated( + const char* value, + std::array* output) +{ + output->fill('\0'); + if (value == nullptr) { + return; + } + size_t length = std::min( + std::strlen(value), Capacity - 1); + while (length > 0 && + (static_cast(value[length]) & 0xC0U) == 0x80U) { + --length; + } + std::memcpy(output->data(), value, length); +} + +} // namespace + +bool NvsMemoryCache::Load() +{ + std::lock_guard lock(mutex_); + snapshot_ = {}; + if (LoadNvsLocked()) { + return true; + } + if (!LoadLegacyPartitionLocked()) { + ESP_LOGI(kTag, "no valid memory snapshot"); + return true; + } + if (!SaveLocked(snapshot_)) { + ESP_LOGW(kTag, "legacy snapshot loaded but NVS migration failed"); + } + return true; +} + +void NvsMemoryCache::CopySnapshot(MemorySnapshot* output) const +{ + if (output == nullptr) { + return; + } + std::lock_guard lock(mutex_); + *output = snapshot_; +} + +bool NvsMemoryCache::Update(const MemorySnapshot& snapshot) +{ + if (!IsValidMemorySnapshot(snapshot)) { + return false; + } + std::lock_guard lock(mutex_); + if (!SaveLocked(snapshot)) { + return false; + } + snapshot_ = snapshot; + ESP_LOGD(kTag, + "snapshot saved child_bytes=%u brain_bytes=%u interactions=%ld", + static_cast( + std::strlen(snapshot_.child_name.data())), + static_cast( + std::strlen(snapshot_.brain_text.data())), + static_cast(snapshot_.interaction_count)); + return true; +} + +bool NvsMemoryCache::LoadNvsLocked() +{ + nvs_handle_t handle = 0; + if (nvs_open(kNamespace, NVS_READONLY, &handle) != ESP_OK) { + return false; + } + auto record = MakePsramObject(); + if (!record) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + nvs_close(handle); + return false; + } + size_t size = sizeof(*record); + const esp_err_t result = + nvs_get_blob(handle, kSnapshotKey, record.get(), &size); + nvs_close(handle); + if (result != ESP_OK || size != sizeof(*record) || + record->magic != kRecordMagic || + record->version != kRecordVersion || + !IsValidMemorySnapshot(record->snapshot) || + record->checksum != + MemorySnapshotChecksum(record->snapshot)) { + return false; + } + snapshot_ = record->snapshot; + ESP_LOGI(kTag, "loaded memory snapshot from NVS"); + return true; +} + +bool NvsMemoryCache::LoadLegacyPartitionLocked() +{ + const esp_partition_t* partition = esp_partition_find_first( + ESP_PARTITION_TYPE_DATA, + ESP_PARTITION_SUBTYPE_DATA_SPIFFS, + kLegacyPartitionLabel); + if (partition == nullptr) { + return false; + } + uint32_t header[2]{}; + if (esp_partition_read( + partition, 0, header, sizeof(header)) != ESP_OK || + header[0] != kLegacyMagic || header[1] == 0 || + header[1] > kMaximumLegacyJsonBytes || + sizeof(header) + header[1] > partition->size) { + return false; + } + auto* json = static_cast(heap_caps_calloc( + header[1] + 1, + sizeof(char), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + if (json == nullptr) { + return false; + } + const esp_err_t read_result = esp_partition_read( + partition, sizeof(header), json, header[1]); + cJSON* root = read_result == ESP_OK + ? cJSON_ParseWithLength(json, header[1]) + : nullptr; + heap_caps_free(json); + if (!cJSON_IsObject(root)) { + cJSON_Delete(root); + return false; + } + + auto migrated = MakePsramObject(); + if (!migrated) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + cJSON_Delete(root); + return false; + } + const cJSON* brain = + cJSON_GetObjectItemCaseSensitive(root, "brain"); + const cJSON* name = + cJSON_GetObjectItemCaseSensitive(root, "name"); + const cJSON* count = + cJSON_GetObjectItemCaseSensitive(root, "count"); + if (cJSON_IsString(brain)) { + CopyLegacyTruncated( + brain->valuestring, &migrated->brain_text); + } + if (cJSON_IsString(name)) { + CopyLegacyTruncated( + name->valuestring, &migrated->child_name); + } + if (cJSON_IsNumber(count) && count->valuedouble >= 0 && + count->valuedouble <= INT32_MAX) { + migrated->interaction_count = count->valueint; + } + cJSON_Delete(root); + if (!IsValidMemorySnapshot(*migrated) || + !migrated->HasData()) { + return false; + } + snapshot_ = *migrated; + ESP_LOGI(kTag, "migrated legacy claude_mem snapshot"); + return true; +} + +bool NvsMemoryCache::SaveLocked(const MemorySnapshot& snapshot) +{ + auto record = MakePsramObject(); + if (!record) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + return false; + } + record->snapshot = snapshot; + record->checksum = MemorySnapshotChecksum(record->snapshot); + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNamespace, NVS_READWRITE, &handle); + if (result == ESP_OK) { + result = nvs_set_blob( + handle, kSnapshotKey, record.get(), sizeof(*record)); + } + if (result == ESP_OK) { + result = nvs_commit(handle); + } + if (handle != 0) { + nvs_close(handle); + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "NVS save failed: %s", + esp_err_to_name(result)); + return false; + } + return true; +} + +} // namespace borla diff --git a/main/memory/memory_cache.h b/main/memory/memory_cache.h new file mode 100644 index 0000000..7013c6c --- /dev/null +++ b/main/memory/memory_cache.h @@ -0,0 +1,24 @@ +#pragma once + +#include "ports/memory_cache.h" + +#include + +namespace borla { + +class NvsMemoryCache final : public IMemoryCache { +public: + bool Load() override; + void CopySnapshot(MemorySnapshot* output) const override; + bool Update(const MemorySnapshot& snapshot) override; + +private: + bool LoadNvsLocked(); + bool LoadLegacyPartitionLocked(); + bool SaveLocked(const MemorySnapshot& snapshot); + + mutable std::mutex mutex_; + MemorySnapshot snapshot_{}; +}; + +} // namespace borla diff --git a/main/memory/memory_types.cc b/main/memory/memory_types.cc new file mode 100644 index 0000000..3bdb90e --- /dev/null +++ b/main/memory/memory_types.cc @@ -0,0 +1,56 @@ +#include "memory/memory_types.h" + +#include + +namespace borla { +namespace { + +constexpr uint32_t kFnvOffset = 2166136261U; +constexpr uint32_t kFnvPrime = 16777619U; + +void HashBytes( + uint32_t* hash, + const void* data, + size_t size) +{ + const auto* bytes = static_cast(data); + for (size_t index = 0; index < size; ++index) { + *hash ^= bytes[index]; + *hash *= kFnvPrime; + } +} + +template +bool IsTerminated(const std::array& value) +{ + return std::memchr(value.data(), '\0', value.size()) != nullptr; +} + +} // namespace + +bool IsValidMemorySnapshot(const MemorySnapshot& snapshot) +{ + return IsTerminated(snapshot.child_name) && + IsTerminated(snapshot.brain_text) && + snapshot.interaction_count >= 0; +} + +uint32_t MemorySnapshotChecksum(const MemorySnapshot& snapshot) +{ + uint32_t hash = kFnvOffset; + HashBytes( + &hash, + snapshot.child_name.data(), + snapshot.child_name.size()); + HashBytes( + &hash, + snapshot.brain_text.data(), + snapshot.brain_text.size()); + HashBytes( + &hash, + &snapshot.interaction_count, + sizeof(snapshot.interaction_count)); + return hash; +} + +} // namespace borla diff --git a/main/memory/memory_types.h b/main/memory/memory_types.h new file mode 100644 index 0000000..fad54c3 --- /dev/null +++ b/main/memory/memory_types.h @@ -0,0 +1,26 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +inline constexpr size_t kMemoryChildNameCapacity = 64; +inline constexpr size_t kMemoryBrainTextCapacity = 2048; + +struct MemorySnapshot { + std::array child_name{}; + std::array brain_text{}; + int32_t interaction_count = 0; + + bool HasData() const + { + return child_name[0] != '\0' || brain_text[0] != '\0'; + } +}; + +bool IsValidMemorySnapshot(const MemorySnapshot& snapshot); +uint32_t MemorySnapshotChecksum(const MemorySnapshot& snapshot); + +} // namespace borla diff --git a/main/ota/ota_endpoint.cc b/main/ota/ota_endpoint.cc new file mode 100644 index 0000000..5768e5d --- /dev/null +++ b/main/ota/ota_endpoint.cc @@ -0,0 +1,135 @@ +#include "ota/ota_endpoint.h" + +#include + +namespace borla { +namespace { + +constexpr const char kWildcardHost[] = "0.0.0.0"; +constexpr size_t kWildcardHostLength = sizeof(kWildcardHost) - 1; + +bool Contains(const char* haystack, const char* needle) +{ + return haystack != nullptr && needle != nullptr && + std::strstr(haystack, needle) != nullptr; +} + +// Extract the host portion of "://[:port][/path]". +// Returns 0 when the URL has no scheme separator or an empty host. +size_t HostSpan(const char* url, const char** host_begin) +{ + if (url == nullptr || host_begin == nullptr) { + return 0; + } + const char* separator = std::strstr(url, "://"); + if (separator == nullptr) { + return 0; + } + const char* begin = separator + 3; + const char* cursor = begin; + while (*cursor != '\0' && *cursor != ':' && *cursor != '/') { + cursor++; + } + *host_begin = begin; + return static_cast(cursor - begin); +} + +} // namespace + +bool IsRolloverEndpoint(const char* url) +{ + if (url == nullptr || url[0] == '\0') { + return false; + } + if (Contains(url, ".lkall.com") && + (Contains(url, "-dev.") || Contains(url, "-moe.") || + Contains(url, "borlaws.lkall.com") || + Contains(url, "borla-ota.lkall.com"))) { + return true; + } + return Contains(url, "192.168.1.121") || + Contains(url, "117.50.44.247"); +} + +bool SubstituteWildcardHost( + const char* url, + const char* ota_url, + char* output, + size_t capacity) +{ + if (url == nullptr || output == nullptr || capacity == 0) { + return false; + } + const char* wildcard = std::strstr(url, kWildcardHost); + if (wildcard == nullptr) { + return false; + } + const char* ota_host = nullptr; + const size_t ota_host_size = HostSpan(ota_url, &ota_host); + if (ota_host_size == 0 || + (ota_host_size == kWildcardHostLength && + std::strncmp(ota_host, kWildcardHost, kWildcardHostLength) == 0)) { + return false; + } + + const size_t prefix_size = static_cast(wildcard - url); + const char* suffix = wildcard + kWildcardHostLength; + const size_t suffix_size = std::strlen(suffix); + const size_t total = prefix_size + ota_host_size + suffix_size; + if (total >= capacity) { + return false; + } + std::memcpy(output, url, prefix_size); + std::memcpy(output + prefix_size, ota_host, ota_host_size); + std::memcpy( + output + prefix_size + ota_host_size, suffix, suffix_size); + output[total] = '\0'; + return true; +} + +bool ResolveRealtimeUrl( + const char* url, + const char* ota_url, + const char* default_url, + char* output, + size_t capacity) +{ + if (output == nullptr || capacity == 0) { + return false; + } + const char* candidate = url; + if (candidate == nullptr || candidate[0] == '\0') { + candidate = nullptr; + } + + if (candidate != nullptr) { + if (SubstituteWildcardHost( + candidate, ota_url, output, capacity)) { + // A substituted URL is by construction the reachable OTA host, so + // it is never treated as a rollover default. + return true; + } + if (std::strstr(candidate, kWildcardHost) != nullptr) { + // Wildcard host that could not be resolved is unusable. + candidate = nullptr; + } + } + + if (candidate != nullptr && IsRolloverEndpoint(candidate)) { + candidate = nullptr; + } + if (candidate == nullptr) { + candidate = default_url; + } + if (candidate == nullptr || candidate[0] == '\0') { + return false; + } + const size_t size = std::strlen(candidate); + if (size >= capacity) { + return false; + } + std::memcpy(output, candidate, size + 1); + return true; +} + +} // namespace borla diff --git a/main/ota/ota_endpoint.h b/main/ota/ota_endpoint.h new file mode 100644 index 0000000..00a00be --- /dev/null +++ b/main/ota/ota_endpoint.h @@ -0,0 +1,50 @@ +#pragma once + +#include "protocol/websocket_transport.h" + +#include +#include + +namespace borla { + +// Endpoint block carried by the OTA check response. The OTA service is the +// only channel that can repoint a fielded device at a different realtime +// server, so the URL/token pair travels with the firmware manifest rather than +// with the realtime protocol itself. +struct OtaEndpointConfig { + std::array url{}; + std::array token{}; + bool has_url = false; + bool has_token = false; + + bool HasAny() const { return has_url || has_token; } +}; + +// True for endpoints that ship as build/staging defaults. A saved value that +// matches one of these is treated as "not deliberately provisioned" and is +// replaced by the current default, so a device that once talked to a retired +// staging host recovers on its own instead of retrying it forever. +bool IsRolloverEndpoint(const char* url); + +// Some deployments answer with a wildcard bind address in the websocket block. +// Substitute the host the OTA request itself was answered by, which is the +// only host the device is known to be able to reach. +// Returns false when `url` has no 0.0.0.0 host, when `ota_url` has no usable +// host, or when the result would not fit; `output` is only written on true. +bool SubstituteWildcardHost( + const char* url, + const char* ota_url, + char* output, + size_t capacity); + +// Full resolution used by OtaService: applies SubstituteWildcardHost, then +// falls back to `default_url` when the result is a rollover endpoint. +// Returns false when nothing usable could be produced. +bool ResolveRealtimeUrl( + const char* url, + const char* ota_url, + const char* default_url, + char* output, + size_t capacity); + +} // namespace borla diff --git a/main/ota/ota_response_parser.cc b/main/ota/ota_response_parser.cc new file mode 100644 index 0000000..64f2eeb --- /dev/null +++ b/main/ota/ota_response_parser.cc @@ -0,0 +1,232 @@ +#include "ota/ota_response_parser.h" + +#include +#include +#include +#include +#include + +#include + +namespace borla { +namespace { + +const char* StringField(const cJSON* root, const char* name) +{ + const cJSON* value = + cJSON_GetObjectItemCaseSensitive(root, name); + return cJSON_IsString(value) ? value->valuestring : nullptr; +} + +bool CopyBounded(const char* source, char* output, size_t capacity) +{ + if (source == nullptr || output == nullptr || capacity == 0) { + return false; + } + const size_t size = std::strlen(source); + if (size == 0 || size >= capacity) { + return false; + } + std::memcpy(output, source, size); + output[size] = '\0'; + return true; +} + +bool IsSafeUrl(const char* url, bool allow_insecure_http) +{ + return url != nullptr && + (std::strncmp(url, "https://", 8) == 0 || + (allow_insecure_http && + std::strncmp(url, "http://", 7) == 0)); +} + +int HexNibble(char value) +{ + if (value >= '0' && value <= '9') { + return value - '0'; + } + value = static_cast( + std::tolower(static_cast(value))); + return value >= 'a' && value <= 'f' + ? value - 'a' + 10 + : -1; +} + +int NextVersionPart(const char** cursor) +{ + const char* value = *cursor; + while (*value == 'v' || *value == 'V' || + *value == '.' || *value == '-' || + std::isspace(static_cast(*value))) { + value++; + } + int part = 0; + while (std::isdigit(static_cast(*value))) { + if (part <= (INT_MAX - 9) / 10) { + part = part * 10 + (*value - '0'); + } + value++; + } + while (*value != '\0' && *value != '.') { + value++; + } + *cursor = value; + return part; +} + +} // namespace + +OtaParseStatus OtaResponseParser::Parse( + const char* json, + size_t size, + const char* current_version, + bool allow_insecure_http, + OtaManifest* manifest, + OtaEndpointConfig* endpoint) const +{ + if (json == nullptr || size == 0 || + current_version == nullptr || manifest == nullptr) { + return OtaParseStatus::kMalformed; + } + *manifest = {}; + if (endpoint != nullptr) { + *endpoint = {}; + } + cJSON* root = cJSON_ParseWithLength(json, size); + if (!cJSON_IsObject(root)) { + cJSON_Delete(root); + return OtaParseStatus::kMalformed; + } + + // The websocket block is parsed first and kept across every firmware-block + // outcome below: the server may hand out a new realtime endpoint on a + // response that carries no image at all, and losing it would strand the + // device on the previous host. + const cJSON* websocket = + cJSON_GetObjectItemCaseSensitive(root, "websocket"); + if (endpoint != nullptr && cJSON_IsObject(websocket)) { + const char* endpoint_url = StringField(websocket, "url"); + const char* endpoint_token = StringField(websocket, "token"); + if (endpoint_url != nullptr) { + endpoint->has_url = CopyBounded( + endpoint_url, + endpoint->url.data(), + endpoint->url.size()); + } + if (endpoint_token != nullptr) { + endpoint->has_token = CopyBounded( + endpoint_token, + endpoint->token.data(), + endpoint->token.size()); + } + } + + const cJSON* firmware = + cJSON_GetObjectItemCaseSensitive(root, "firmware"); + if (cJSON_IsNull(firmware) || firmware == nullptr) { + cJSON_Delete(root); + return OtaParseStatus::kOk; + } + if (!cJSON_IsObject(firmware)) { + cJSON_Delete(root); + return OtaParseStatus::kInvalidManifest; + } + + const char* version = StringField(firmware, "version"); + const char* url = StringField(firmware, "url"); + const char* sha256 = StringField(firmware, "sha256"); + const cJSON* size_value = + cJSON_GetObjectItemCaseSensitive(firmware, "size"); + uint8_t digest[32]{}; + if (!CopyBounded( + version, manifest->version.data(), + manifest->version.size()) || + !CopyBounded( + url, manifest->url.data(), manifest->url.size()) || + !CopyBounded( + sha256, manifest->sha256.data(), + manifest->sha256.size()) || + !DecodeSha256(sha256, digest) || + !cJSON_IsNumber(size_value) || + !std::isfinite(size_value->valuedouble) || + std::floor(size_value->valuedouble) != + size_value->valuedouble || + size_value->valuedouble <= 0 || + size_value->valuedouble > UINT32_MAX) { + cJSON_Delete(root); + return OtaParseStatus::kInvalidManifest; + } + if (!IsSafeUrl(url, allow_insecure_http)) { + cJSON_Delete(root); + return OtaParseStatus::kUnsafeUrl; + } + if (CompareVersions(version, current_version) <= 0) { + *manifest = {}; + cJSON_Delete(root); + return OtaParseStatus::kOk; + } + + manifest->size = + static_cast(size_value->valuedouble); + const cJSON* automatic = + cJSON_GetObjectItemCaseSensitive(root, "auto_update"); + const cJSON* forced = + cJSON_GetObjectItemCaseSensitive(root, "force_upgrade"); + if ((automatic != nullptr && !cJSON_IsBool(automatic)) || + (forced != nullptr && !cJSON_IsBool(forced))) { + cJSON_Delete(root); + return OtaParseStatus::kInvalidManifest; + } + if (cJSON_IsTrue(automatic)) { + manifest->policy = OtaUpgradePolicy::kAutomatic; + } else if (cJSON_IsTrue(forced)) { + manifest->policy = OtaUpgradePolicy::kForced; + } else { + manifest->policy = OtaUpgradePolicy::kOptional; + } + cJSON_Delete(root); + return OtaParseStatus::kOk; +} + +int OtaResponseParser::CompareVersions( + const char* left, + const char* right) +{ + if (left == nullptr || right == nullptr) { + return 0; + } + const char* left_cursor = left; + const char* right_cursor = right; + for (size_t i = 0; i < 8; ++i) { + const int left_part = NextVersionPart(&left_cursor); + const int right_part = NextVersionPart(&right_cursor); + if (left_part != right_part) { + return left_part < right_part ? -1 : 1; + } + if (*left_cursor == '\0' && *right_cursor == '\0') { + return 0; + } + } + return 0; +} + +bool OtaResponseParser::DecodeSha256( + const char* hex, + uint8_t output[32]) +{ + if (hex == nullptr || output == nullptr || + std::strlen(hex) != 64) { + return false; + } + for (size_t i = 0; i < 32; ++i) { + const int upper = HexNibble(hex[i * 2]); + const int lower = HexNibble(hex[i * 2 + 1]); + if (upper < 0 || lower < 0) { + return false; + } + output[i] = static_cast((upper << 4) | lower); + } + return true; +} + +} // namespace borla diff --git a/main/ota/ota_response_parser.h b/main/ota/ota_response_parser.h new file mode 100644 index 0000000..f61a4af --- /dev/null +++ b/main/ota/ota_response_parser.h @@ -0,0 +1,30 @@ +#pragma once + +#include "ota/ota_endpoint.h" +#include "ota/ota_types.h" + +#include + +namespace borla { + +class OtaResponseParser final { +public: + // `endpoint` is optional and independent of the firmware block: a + // response may repoint the device without shipping an image. It is kept + // out of OtaManifest on purpose — the manifest is copied under a + // critical section, and the endpoint is consumed immediately. + OtaParseStatus Parse( + const char* json, + size_t size, + const char* current_version, + bool allow_insecure_http, + OtaManifest* manifest, + OtaEndpointConfig* endpoint = nullptr) const; + + static int CompareVersions(const char* left, const char* right); + static bool DecodeSha256( + const char* hex, + uint8_t output[32]); +}; + +} // namespace borla diff --git a/main/ota/ota_service.cc b/main/ota/ota_service.cc new file mode 100644 index 0000000..60c91df --- /dev/null +++ b/main/ota/ota_service.cc @@ -0,0 +1,685 @@ +#include "ota/ota_service.h" + +#include "diagnostics/trace_context.h" +#include "ota/ota_endpoint.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP +#define CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP 0 +#endif + +namespace borla { +namespace { + +// Wall-clock milliseconds, or 0 while the clock still reads 1970 because NTP +// has not landed yet — which is the normal case for the boot-time OTA check. +int64_t EpochMs() +{ + struct timeval now {}; + if (gettimeofday(&now, nullptr) != 0 || + now.tv_sec < 1700000000) { + return 0; + } + return static_cast(now.tv_sec) * 1000 + + now.tv_usec / 1000; +} + +constexpr const char* kTag = "OtaService2"; +constexpr uint32_t kCheckFailedError = 3401; +constexpr uint32_t kManifestInvalidError = 3402; +constexpr uint32_t kPartitionError = 3403; +constexpr uint32_t kDownloadError = 3404; +constexpr uint32_t kSizeMismatchError = 3405; +constexpr uint32_t kShaMismatchError = 3406; +constexpr uint32_t kImageValidationError = 3407; +constexpr size_t kMaximumCheckResponseBytes = 4096; +constexpr uint32_t kUpgradeAnnouncementDelayMs = 8000; +constexpr uint32_t kAnnouncementChannelWaitMs = 10000; +constexpr uint32_t kAnnouncementPollMs = 500; + +// Kept verbatim from the legacy firmware so the server-side TTS cache and the +// parent-facing copy do not change during the migration. +constexpr const char* kAutoUpgradeText = + "当前有最新版本,即将开始升级!请耐心等候"; +constexpr const char* kForcedUpgradeText = + "目前有大版本需要升级,否则设备将不可用,即将升级请耐心等候!"; +constexpr const char* kOptionalUpgradeText = + "当前设备有最新版本,是否进行升级?"; +constexpr const char* kAutoUpgradeUnavailableText = + "检测到新版本,升级文件准备中,请稍后重试"; +constexpr const char* kForcedUpgradeUnavailableText = + "检测到需要升级的版本,升级文件准备中,请稍后重试"; +// NOTE: the legacy firmware also announced "升级成功,正在重启" after flashing. +// firmware2 cannot: kUpgradeRequested deterministically closes the realtime +// channel before the download starts, so there is no socket left to speak on. +// The server learns the outcome from the post-reboot hello version instead. + +struct ResponseBuffer { + std::array data{}; + size_t size = 0; + bool overflow = false; +}; + +esp_err_t CaptureResponse(esp_http_client_event_t* event) +{ + if (event == nullptr || event->user_data == nullptr) { + return ESP_OK; + } + if (event->event_id != HTTP_EVENT_ON_DATA || + event->data == nullptr || event->data_len <= 0) { + return ESP_OK; + } + auto* response = + static_cast(event->user_data); + const size_t incoming = + static_cast(event->data_len); + if (response->size + incoming >= response->data.size()) { + response->overflow = true; + return ESP_FAIL; + } + std::memcpy( + response->data.data() + response->size, + event->data, + incoming); + response->size += incoming; + response->data[response->size] = '\0'; + return ESP_OK; +} + +bool SecureUrlAllowed(const char* url) +{ + if (url == nullptr) { + return false; + } + if (std::strncmp(url, "https://", 8) == 0) { + return true; + } +#if CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP + return std::strncmp(url, "http://", 7) == 0; +#else + return false; +#endif +} + +esp_http_client_handle_t CreateHttpClient( + const char* url, + http_event_handle_cb event_handler = nullptr, + void* user_data = nullptr) +{ + if (!SecureUrlAllowed(url)) { + return nullptr; + } + esp_http_client_config_t config{}; + config.url = url; + config.event_handler = event_handler; + config.user_data = user_data; + config.timeout_ms = 30000; + config.buffer_size = 4096; + config.buffer_size_tx = 1024; + if (std::strncmp(url, "https://", 8) == 0) { + config.crt_bundle_attach = esp_crt_bundle_attach; + } + return esp_http_client_init(&config); +} + +} // namespace + +bool OtaService::Initialize( + const DeviceIdentity& identity, + IEventPublisher& publisher) +{ + identity_ = identity; + publisher_ = &publisher; + if (task_ != nullptr) { + return true; + } + request_ = xSemaphoreCreateBinaryStatic(&request_storage_); + if (request_ == nullptr) { + ESP_LOGE(kTag, "OTA request semaphore creation failed"); + return false; + } + task_ = xTaskCreateStatic( + &OtaService::TaskEntry, + "ota_service2", + task_stack_.size(), + this, + 5, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + ESP_LOGE(kTag, "OTA worker creation failed"); + return false; + } + return true; +} + +void OtaService::OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) +{ + // 记录实时通道是否已握手完成:RunOnce 用它把版本检查的 TLS 错开 + // (原因见 kCheckStaggerMaxMs 的注释)。 + realtime_open_.store(state.realtime == RealtimeState::kOpen); + + if (event.type != AppEventType::kNetworkConnected || + task_ == nullptr || + check_started_.exchange(true)) { + return; + } + if (busy_.exchange(true)) { + check_started_.store(false); + return; + } + task_mode_.store(TaskMode::kCheck); + xSemaphoreGive(request_); +} + +void OtaService::StartUpgrade(uint32_t request_id) +{ + request_id_.store(request_id); + upgrade_requested_.store(true); + if (task_ == nullptr) { + PublishFailure(kDownloadError); + return; + } + if (busy_.exchange(true)) { + // A check-mode run is already waiting for this flag and will perform + // the upgrade itself. + return; + } + task_mode_.store(TaskMode::kUpgrade); + xSemaphoreGive(request_); +} + +bool OtaService::ConfirmCurrentImage() +{ + const esp_partition_t* running = + esp_ota_get_running_partition(); + esp_ota_img_states_t state = ESP_OTA_IMG_UNDEFINED; + const esp_err_t result = + esp_ota_get_state_partition(running, &state); + if (result == ESP_ERR_NOT_SUPPORTED || + state != ESP_OTA_IMG_PENDING_VERIFY) { + return result == ESP_OK || result == ESP_ERR_NOT_SUPPORTED; + } + const esp_err_t mark_result = + esp_ota_mark_app_valid_cancel_rollback(); + ESP_LOGI(kTag, "current image confirmation: %s", + esp_err_to_name(mark_result)); + return mark_result == ESP_OK; +} + +void OtaService::RejectCurrentImageAndRollback() +{ + const esp_partition_t* running = + esp_ota_get_running_partition(); + esp_ota_img_states_t state = ESP_OTA_IMG_UNDEFINED; + if (esp_ota_get_state_partition(running, &state) == ESP_OK && + state == ESP_OTA_IMG_PENDING_VERIFY) { + ESP_LOGE(kTag, "boot self-test failed; rolling back image"); + esp_ota_mark_app_invalid_rollback_and_reboot(); + } +} + +OtaDiagnostics OtaService::GetDiagnostics() const +{ + portENTER_CRITICAL(&lock_); + const OtaDiagnostics result = diagnostics_; + portEXIT_CRITICAL(&lock_); + return result; +} + +void OtaService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void OtaService::Run() +{ + for (;;) { + if (xSemaphoreTake(request_, portMAX_DELAY) != pdTRUE) { + continue; + } + RunOnce(); + busy_.store(false); + } +} + +void OtaService::RunOnce() +{ + const TaskMode mode = task_mode_.load(); + if (mode == TaskMode::kCheck) { + TraceContext::RefreshTrace("ota"); + // 先让实时通道把 TLS 握完(两条 TLS 并发会让 WiFi 拿不到内部 DMA + // 缓冲,见 kCheckStaggerMaxMs)。通道已经打开时一次都不等。 + uint32_t staggered_ms = 0; + while (!realtime_open_.load() && + staggered_ms < kCheckStaggerMaxMs) { + vTaskDelay(pdMS_TO_TICKS(kCheckStaggerStepMs)); + staggered_ms += kCheckStaggerStepMs; + } + if (staggered_ms > 0) { + ESP_LOGI(kTag, + "staggered version check waited=%ums realtime_open=%d", + static_cast(staggered_ms), + realtime_open_.load() ? 1 : 0); + } + bool checked = false; + for (uint32_t attempt = 0; attempt < 3 && !checked; ++attempt) { + portENTER_CRITICAL(&lock_); + diagnostics_.checking = true; + diagnostics_.check_attempts++; + portEXIT_CRITICAL(&lock_); + checked = CheckVersion(); + if (!checked && attempt < 2) { + vTaskDelay(pdMS_TO_TICKS(10000)); + } + } + portENTER_CRITICAL(&lock_); + diagnostics_.checking = false; + portEXIT_CRITICAL(&lock_); + + OtaManifest manifest; + portENTER_CRITICAL(&lock_); + manifest = manifest_; + portEXIT_CRITICAL(&lock_); + if (checked && manifest.policy == OtaUpgradePolicy::kOptional) { + // Advisory only: tell the parent a version exists, install nothing. + AnnounceUpgrade(manifest); + } + if (checked && manifest.ShouldStartAutomatically()) { + // Announce first. kUpgradeRequested deterministically closes the + // realtime channel, so anything said after it would never reach + // the server. + AnnounceUpgrade(manifest); + publisher_->Publish(AppEvent::Make( + AppEventType::kUpgradeRequested, + request_id_.load())); + for (uint32_t waited = 0; + !upgrade_requested_.load() && waited < 5000; + waited += 50) { + vTaskDelay(pdMS_TO_TICKS(50)); + } + if (upgrade_requested_.load()) { + PerformUpgrade(); + } else { + PublishFailure(kDownloadError); + } + } + } else { + PerformUpgrade(); + } +} + +bool OtaService::CheckVersion() +{ + // 碎片防护:内部RAM最大连续块不足,直接跳过版本检查,避免触发socket分配失败 + const size_t largest_int_ram = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); + ESP_LOGI(kTag, "CheckVersion largest_int_ram=%zu", largest_int_ram); + if (largest_int_ram < 12 * 1024U) + { + ESP_LOGW(kTag, "internal ram fragmented, skip ota version check"); + PublishFailure(kCheckFailedError); + return false; + } + + + ResponseBuffer response; + esp_http_client_handle_t client = CreateHttpClient( + CONFIG_BORLA_OTA_URL, &CaptureResponse, &response); + if (client == nullptr) { + PublishFailure(kCheckFailedError); + return false; + } + std::array body{}; + const int body_size = std::snprintf( + body.data(), + body.size(), + "{\"mac_address\":\"%s\",\"board_type\":\"%s\"," + "\"app_version\":\"%s\",\"idf_version\":\"%s\"," + "\"chip_model\":\"%s\",\"free_heap\":%lu}", + identity_.mac, + identity_.board, + identity_.app_version, + esp_get_idf_version(), + identity_.chip_model, + static_cast( + heap_caps_get_free_size(MALLOC_CAP_8BIT))); + if (body_size <= 0 || + static_cast(body_size) >= body.size()) { + esp_http_client_cleanup(client); + PublishFailure(kCheckFailedError); + return false; + } + + esp_http_client_set_method(client, HTTP_METHOD_POST); + esp_http_client_set_header( + client, "Content-Type", "application/json"); + esp_http_client_set_header(client, "Device-Id", identity_.mac); + // Correlation headers: server and backend grep the same ids to stitch the + // device-side OTA call into their own request logs. + const char* request_id = TraceContext::NewRequestId(); + esp_http_client_set_header( + client, "X-Borla-Trace-Id", TraceContext::TraceId()); + esp_http_client_set_header( + client, "X-Borla-Session-Id", TraceContext::SessionId()); + esp_http_client_set_header(client, "X-Request-Id", request_id); + // http_server.py reads these two to time the call and derive the device's + // clock offset. The epoch header is skipped while the wall clock still + // reads 1970, since OTA check runs before NTP on a cold boot and a 1970 + // stamp would be read as a 56-year skew rather than as "unknown". + char send_ms[24]{}; + std::snprintf( + send_ms, + sizeof(send_ms), + "%llu", + static_cast(esp_timer_get_time() / 1000)); + esp_http_client_set_header( + client, "X-Borla-Client-Send-Ms", send_ms); + const int64_t client_epoch_ms = EpochMs(); + if (client_epoch_ms > 0) { + char epoch_ms[24]{}; + std::snprintf( + epoch_ms, + sizeof(epoch_ms), + "%lld", + static_cast(client_epoch_ms)); + esp_http_client_set_header( + client, "X-Borla-Client-Epoch-Ms", epoch_ms); + } + ESP_LOGI(kTag, "version check trace=%s request=%s", + TraceContext::TraceId(), request_id); + esp_http_client_set_post_field( + client, body.data(), body_size); + const esp_err_t result = esp_http_client_perform(client); + const int status = esp_http_client_get_status_code(client); + esp_http_client_close(client);//释放内存 + esp_http_client_cleanup(client); + if (result != ESP_OK || status != 200 || + response.overflow || response.size == 0) { + ESP_LOGW(kTag, "version check failed result=%s status=%d", + esp_err_to_name(result), status); + PublishFailure(kCheckFailedError); + return false; + } + + OtaManifest parsed; + OtaEndpointConfig endpoint; + const OtaParseStatus parse_status = parser_.Parse( + response.data.data(), + response.size, + identity_.app_version, + CONFIG_BORLA_OTA_ALLOW_INSECURE_HTTP, + &parsed, + &endpoint); + const esp_partition_t* target = + esp_ota_get_next_update_partition(nullptr); + if (parse_status != OtaParseStatus::kOk || + (parsed.HasUpdate() && + (target == nullptr || parsed.size > target->size))) { + portENTER_CRITICAL(&lock_); + diagnostics_.last_parse_status = parse_status; + portEXIT_CRITICAL(&lock_); + PublishFailure(kManifestInvalidError); + return false; + } + + portENTER_CRITICAL(&lock_); + manifest_ = parsed; + diagnostics_.manifest = parsed; + diagnostics_.last_parse_status = parse_status; + portEXIT_CRITICAL(&lock_); + ESP_LOGI(kTag, "version check policy=%s version=%s size=%lu", + ToString(parsed.policy), + parsed.version.data(), + static_cast(parsed.size)); + // Endpoint handling is deliberately independent of HasUpdate(): the OTA + // response is the only channel that can repoint a fielded device, and it + // routinely carries a websocket block with no firmware block at all. + ApplyEndpoint(endpoint); + return true; +} + +void OtaService::ApplyEndpoint(const OtaEndpointConfig& endpoint) +{ + if (config_store_ == nullptr || !endpoint.HasAny()) { + return; + } + std::array resolved{}; + const bool has_url = + endpoint.has_url && + ResolveRealtimeUrl( + endpoint.url.data(), + CONFIG_BORLA_OTA_URL, + kDefaultRealtimeUrl, + resolved.data(), + resolved.size()); + if (!has_url && !endpoint.has_token) { + ESP_LOGW(kTag, "OTA endpoint block unusable; keeping stored value"); + return; + } + if (!config_store_->SaveEndpoint( + has_url ? resolved.data() : nullptr, + endpoint.has_token ? endpoint.token.data() : nullptr)) { + ESP_LOGW(kTag, "OTA endpoint persistence failed"); + return; + } + // Applied on the next Open(): RealtimeProtocol loads its transport config + // once at Initialize(), so a changed endpoint takes effect after reboot. + ESP_LOGI(kTag, "OTA endpoint stored url=%s", + has_url ? resolved.data() : "(unchanged)"); +} + +void OtaService::AnnounceUpgrade(const OtaManifest& manifest) +{ + if (realtime_ == nullptr || !manifest.HasUpdate()) { + return; + } + const bool forced = manifest.policy == OtaUpgradePolicy::kForced; + const bool optional = + manifest.policy == OtaUpgradePolicy::kOptional; + const char* text = nullptr; + if (optional) { + text = kOptionalUpgradeText; + } else if (manifest.url[0] == '\0') { + text = forced ? kForcedUpgradeUnavailableText + : kAutoUpgradeUnavailableText; + } else { + text = forced ? kForcedUpgradeText : kAutoUpgradeText; + } + + // The check can finish before the realtime channel has finished opening + // (both are triggered by the same kNetworkConnected edge), so give the + // channel a bounded grace period rather than dropping the announcement. + bool sent = false; + for (uint32_t waited = 0; + !sent && waited < kAnnouncementChannelWaitMs; + waited += kAnnouncementPollMs) { + sent = realtime_->SendOtaNotify(text, optional); + if (!sent) { + vTaskDelay(pdMS_TO_TICKS(kAnnouncementPollMs)); + } + } + if (!sent) { + ESP_LOGW(kTag, "upgrade announcement skipped: channel not open"); + return; + } + ESP_LOGI(kTag, "upgrade announcement sent policy=%s", + ToString(manifest.policy)); + if (optional) { + return; + } + // Give the server time to synthesise and the device time to play the + // announcement before the download saturates the link. + vTaskDelay(pdMS_TO_TICKS(kUpgradeAnnouncementDelayMs)); +} + +bool OtaService::PerformUpgrade() +{ + portENTER_CRITICAL(&lock_); + diagnostics_.upgrading = true; + portEXIT_CRITICAL(&lock_); + const bool success = DownloadToPartition(); + portENTER_CRITICAL(&lock_); + diagnostics_.upgrading = false; + portEXIT_CRITICAL(&lock_); + if (success) { + publisher_->Publish(AppEvent::Make( + AppEventType::kUpgradeCompleted, + request_id_.load())); + } + return success; +} + +bool OtaService::DownloadToPartition() +{ + OtaManifest manifest; + portENTER_CRITICAL(&lock_); + manifest = manifest_; + diagnostics_.downloaded_bytes = 0; + portEXIT_CRITICAL(&lock_); + if (!manifest.HasUpdate()) { + PublishFailure(kManifestInvalidError); + return false; + } + const esp_partition_t* partition = + esp_ota_get_next_update_partition(nullptr); + if (partition == nullptr || manifest.size > partition->size) { + PublishFailure(kPartitionError); + return false; + } + + // 碎片防护 + const size_t largest_int_ram = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); + ESP_LOGI(kTag, "DownloadToPartition largest_int_ram=%zu", largest_int_ram); + if (largest_int_ram < 12 * 1024U) + { + ESP_LOGW(kTag, "internal ram fragmented, abort download"); + PublishFailure(kDownloadError); + return false; + }///// + + + esp_http_client_handle_t client = + CreateHttpClient(manifest.url.data()); + if (client == nullptr) { + PublishFailure(kDownloadError); + return false; + } + esp_http_client_set_method(client, HTTP_METHOD_GET); + esp_err_t result = esp_http_client_open(client, 0); + if (result != ESP_OK) { + esp_http_client_cleanup(client); + PublishFailure(kDownloadError); + return false; + } + const int64_t content_length = + esp_http_client_fetch_headers(client); + const int status = esp_http_client_get_status_code(client); + if (status != 200 || + (content_length > 0 && + static_cast(content_length) != manifest.size)) { + esp_http_client_close(client); + esp_http_client_cleanup(client); + PublishFailure( + status == 200 ? kSizeMismatchError : kDownloadError); + return false; + } + + esp_ota_handle_t ota_handle = 0; + result = esp_ota_begin( + partition, manifest.size, &ota_handle); + if (result != ESP_OK) { + esp_http_client_close(client); + esp_http_client_cleanup(client); + PublishFailure(kPartitionError); + return false; + } + + mbedtls_sha256_context sha; + mbedtls_sha256_init(&sha); + mbedtls_sha256_starts(&sha, 0); + std::array buffer{}; + uint32_t total = 0; + bool valid = true; + while (total < manifest.size) { + const int read = esp_http_client_read( + client, + reinterpret_cast(buffer.data()), + std::min( + buffer.size(), manifest.size - total)); + if (read <= 0) { + valid = false; + break; + } + if (esp_ota_write( + ota_handle, buffer.data(), read) != ESP_OK) { + valid = false; + break; + } + mbedtls_sha256_update( + &sha, buffer.data(), static_cast(read)); + total += static_cast(read); + portENTER_CRITICAL(&lock_); + diagnostics_.downloaded_bytes = total; + portEXIT_CRITICAL(&lock_); + } + esp_http_client_close(client); + esp_http_client_cleanup(client); + + uint8_t actual_digest[32]{}; + uint8_t expected_digest[32]{}; + mbedtls_sha256_finish(&sha, actual_digest); + mbedtls_sha256_free(&sha); + if (!valid || total != manifest.size) { + esp_ota_abort(ota_handle); + PublishFailure(kSizeMismatchError); + return false; + } + if (!OtaResponseParser::DecodeSha256( + manifest.sha256.data(), expected_digest) || + std::memcmp(actual_digest, expected_digest, 32) != 0) { + esp_ota_abort(ota_handle); + PublishFailure(kShaMismatchError); + return false; + } + if (esp_ota_end(ota_handle) != ESP_OK || + esp_ota_set_boot_partition(partition) != ESP_OK) { + PublishFailure(kImageValidationError); + return false; + } + ESP_LOGI(kTag, "OTA image verified version=%s bytes=%lu", + manifest.version.data(), + static_cast(total)); + return true; +} + +void OtaService::PublishFailure(uint32_t error) +{ + portENTER_CRITICAL(&lock_); + diagnostics_.last_error = error; + portEXIT_CRITICAL(&lock_); + if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kUpgradeFailed, error)); + } +} + +} // namespace borla diff --git a/main/ota/ota_service.h b/main/ota/ota_service.h new file mode 100644 index 0000000..83e204d --- /dev/null +++ b/main/ota/ota_service.h @@ -0,0 +1,108 @@ +#pragma once + +#include "ota/ota_response_parser.h" +#include "ports/application_observer.h" +#include "ports/device_platform.h" +#include "ports/event_publisher.h" +#include "ports/ota_service.h" +#include "ports/realtime_protocol.h" +#include "protocol/realtime_config.h" + +#include +#include + +#include +#include +#include + +namespace borla { + +struct OtaDiagnostics { + OtaManifest manifest{}; + OtaParseStatus last_parse_status = OtaParseStatus::kOk; + uint32_t check_attempts = 0; + uint32_t downloaded_bytes = 0; + uint32_t last_error = 0; + bool checking = false; + bool upgrading = false; +}; + +class OtaService final + : public IOtaService, + public IApplicationObserver { +public: + bool Initialize( + const DeviceIdentity& identity, + IEventPublisher& publisher); + // Optional collaborators. Both are wired by CompositionRoot; the service + // degrades to "check + install only" when either is absent. + void SetRealtimeConfigStore(IRealtimeConfigStore* store) + { + config_store_ = store; + } + void SetRealtimeProtocol(IRealtimeProtocol* realtime) + { + realtime_ = realtime; + } + void StartUpgrade(uint32_t request_id) override; + void OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) override; + + bool ConfirmCurrentImage(); + void RejectCurrentImageAndRollback(); + OtaDiagnostics GetDiagnostics() const; + +private: + enum class TaskMode : uint8_t { + kCheck, + kUpgrade, + }; + + static constexpr uint32_t kTaskStackDepth = 12288; + + // 版本检查是设备上的第二条 TLS:它与实时通道(websocket)的 TLS 都由 + // kNetworkConnected 触发,两条同时握手会把内部 DMA 可用的 RAM 抢空 —— + // WiFi 驱动随即分配不到 RX 缓冲("wifi:mem fail" → ADDBA RX DELBA → + // 收包瘫痪 → "WebSocket read failed"),实测 internal free 掉到 863 B。 + // 因此检查前先等实时通道把 TLS 握完;超过 kCheckStaggerMaxMs 就照常进行, + // 避免实时通道一直连不上时版本检查被永久推迟。 + static constexpr uint32_t kCheckStaggerMaxMs = 8000; + static constexpr uint32_t kCheckStaggerStepMs = 100; + + static void TaskEntry(void* context); + // Long-lived worker: the static task control block and stack cannot be + // recycled for a second task while the first is still terminating, so the + // worker parks on request_ instead of deleting itself. + [[noreturn]] void Run(); + void RunOnce(); + bool CheckVersion(); + bool PerformUpgrade(); + bool DownloadToPartition(); + void PublishFailure(uint32_t error); + void ApplyEndpoint(const OtaEndpointConfig& endpoint); + void AnnounceUpgrade(const OtaManifest& manifest); + + DeviceIdentity identity_{}; + IEventPublisher* publisher_ = nullptr; + IRealtimeConfigStore* config_store_ = nullptr; + IRealtimeProtocol* realtime_ = nullptr; + OtaResponseParser parser_; + OtaManifest manifest_{}; + OtaDiagnostics diagnostics_{}; + mutable portMUX_TYPE lock_ = portMUX_INITIALIZER_UNLOCKED; + std::atomic task_mode_{TaskMode::kCheck}; + // 由 OnApplicationEvent 刷新,RunOnce 用它错开实时通道的 TLS 握手。 + std::atomic realtime_open_{false}; + std::atomic check_started_{false}; + std::atomic busy_{false}; + std::atomic upgrade_requested_{false}; + std::atomic request_id_{0}; + SemaphoreHandle_t request_ = nullptr; + StaticSemaphore_t request_storage_{}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array task_stack_{}; +}; + +} // namespace borla diff --git a/main/ota/ota_types.cc b/main/ota/ota_types.cc new file mode 100644 index 0000000..3c25ac0 --- /dev/null +++ b/main/ota/ota_types.cc @@ -0,0 +1,35 @@ +#include "ota/ota_types.h" + +namespace borla { + +const char* ToString(OtaUpgradePolicy policy) +{ + switch (policy) { + case OtaUpgradePolicy::kNone: + return "none"; + case OtaUpgradePolicy::kOptional: + return "optional"; + case OtaUpgradePolicy::kAutomatic: + return "automatic"; + case OtaUpgradePolicy::kForced: + return "forced"; + } + return "unknown"; +} + +const char* ToString(OtaParseStatus status) +{ + switch (status) { + case OtaParseStatus::kOk: + return "ok"; + case OtaParseStatus::kMalformed: + return "malformed"; + case OtaParseStatus::kInvalidManifest: + return "invalid_manifest"; + case OtaParseStatus::kUnsafeUrl: + return "unsafe_url"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/ota/ota_types.h b/main/ota/ota_types.h new file mode 100644 index 0000000..77cdd66 --- /dev/null +++ b/main/ota/ota_types.h @@ -0,0 +1,48 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +enum class OtaUpgradePolicy : uint8_t { + kNone, + kOptional, + kAutomatic, + kForced, +}; + +inline constexpr size_t kOtaVersionCapacity = 32; +inline constexpr size_t kOtaUrlCapacity = 384; +inline constexpr size_t kOtaSha256HexCapacity = 65; + +struct OtaManifest { + OtaUpgradePolicy policy = OtaUpgradePolicy::kNone; + std::array version{}; + std::array url{}; + std::array sha256{}; + uint32_t size = 0; + + bool HasUpdate() const + { + return policy != OtaUpgradePolicy::kNone; + } + bool ShouldStartAutomatically() const + { + return policy == OtaUpgradePolicy::kAutomatic || + policy == OtaUpgradePolicy::kForced; + } +}; + +enum class OtaParseStatus : uint8_t { + kOk, + kMalformed, + kInvalidManifest, + kUnsafeUrl, +}; + +const char* ToString(OtaUpgradePolicy policy); +const char* ToString(OtaParseStatus status); + +} // namespace borla diff --git a/main/platform/borla_s3/battery_monitor.cc b/main/platform/borla_s3/battery_monitor.cc new file mode 100644 index 0000000..56bdf68 --- /dev/null +++ b/main/platform/borla_s3/battery_monitor.cc @@ -0,0 +1,148 @@ +#include "platform/borla_s3/battery_monitor.h" + +#include +#include + +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "BatteryMonitor2"; +constexpr adc_channel_t kBatteryAdcChannel = ADC_CHANNEL_9; +constexpr size_t kSampleCount = 32; +constexpr size_t kTrimCount = 8; + +} // namespace + +BatteryMonitor::~BatteryMonitor() +{ + if (calibration_ != nullptr) { + adc_cali_delete_scheme_curve_fitting(calibration_); + } + if (adc_ != nullptr) { + adc_oneshot_del_unit(adc_); + } +} + +bool BatteryMonitor::Initialize() +{ + if (adc_ != nullptr) { + return true; + } + const adc_oneshot_unit_init_cfg_t unit_config = { + .unit_id = ADC_UNIT_1, + .clk_src = ADC_RTC_CLK_SRC_DEFAULT, + .ulp_mode = ADC_ULP_MODE_DISABLE, + }; + esp_err_t result = + adc_oneshot_new_unit(&unit_config, &adc_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "ADC unit initialization failed: %s", + esp_err_to_name(result)); + adc_ = nullptr; + return false; + } + const adc_oneshot_chan_cfg_t channel_config = { + .atten = ADC_ATTEN_DB_12, + .bitwidth = ADC_BITWIDTH_DEFAULT, + }; + result = adc_oneshot_config_channel( + adc_, kBatteryAdcChannel, &channel_config); + if (result != ESP_OK) { + ESP_LOGE(kTag, "ADC channel configuration failed: %s", + esp_err_to_name(result)); + adc_oneshot_del_unit(adc_); + adc_ = nullptr; + return false; + } + + const adc_cali_curve_fitting_config_t calibration_config = { + .unit_id = ADC_UNIT_1, + .chan = kBatteryAdcChannel, + .atten = ADC_ATTEN_DB_12, + .bitwidth = ADC_BITWIDTH_DEFAULT, + }; + result = adc_cali_create_scheme_curve_fitting( + &calibration_config, &calibration_); + if (result != ESP_OK) { + calibration_ = nullptr; + ESP_LOGW(kTag, "eFuse calibration unavailable: %s", + esp_err_to_name(result)); + } + ESP_LOGI(kTag, "battery ADC initialized on GPIO10"); + return true; +} + +bool BatteryMonitor::Read(uint64_t now_ms, BatteryStatus* status) +{ + if (adc_ == nullptr || status == nullptr) { + return false; + } + std::array samples{}; + for (int& sample : samples) { + if (adc_oneshot_read( + adc_, kBatteryAdcChannel, &sample) != ESP_OK) { + return false; + } + vTaskDelay(pdMS_TO_TICKS(1)); + } + std::sort(samples.begin(), samples.end()); + uint32_t sum = 0; + for (size_t i = kTrimCount; + i < samples.size() - kTrimCount; + ++i) { + sum += static_cast(samples[i]); + } + const int raw = static_cast( + sum / (samples.size() - 2 * kTrimCount)); + int pin_millivolts = raw * 3100 / 4095; + if (calibration_ != nullptr) { + int calibrated = 0; + if (adc_cali_raw_to_voltage( + calibration_, raw, &calibrated) == ESP_OK) { + pin_millivolts = calibrated; + } + } + const uint16_t battery_millivolts = static_cast( + std::clamp(pin_millivolts * 3 / 2, 0, 5000)); + if (!BatteryEstimator::IsPlausibleVoltage( + battery_millivolts)) { + if (!invalid_sample_reported_) { + ESP_LOGW(kTag, + "invalid battery sample raw=%d pin=%dmV battery=%umV; " + "status remains unavailable", + raw, + pin_millivolts, + static_cast(battery_millivolts)); + invalid_sample_reported_ = true; + } else { + ESP_LOGD(kTag, + "battery sample still invalid raw=%d battery=%umV", + raw, + static_cast(battery_millivolts)); + } + *status = {}; + return false; + } + if (invalid_sample_reported_) { + ESP_LOGI(kTag, "battery sample recovered battery=%umV", + static_cast(battery_millivolts)); + invalid_sample_reported_ = false; + } + estimator_.Update(battery_millivolts); + *status = { + .timestamp_ms = now_ms, + .millivolts = estimator_.smoothed_millivolts(), + .percent = estimator_.percent(), + .charging = estimator_.charging(), + .valid = true, + }; + return true; +} + +} // namespace borla diff --git a/main/platform/borla_s3/battery_monitor.h b/main/platform/borla_s3/battery_monitor.h new file mode 100644 index 0000000..4d0622c --- /dev/null +++ b/main/platform/borla_s3/battery_monitor.h @@ -0,0 +1,26 @@ +#pragma once + +#include "sensor/battery_estimator.h" +#include "sensor/sensor_types.h" + +#include +#include + +namespace borla { + +class BatteryMonitor final { +public: + BatteryMonitor() = default; + ~BatteryMonitor(); + + bool Initialize(); + bool Read(uint64_t now_ms, BatteryStatus* status); + +private: + adc_oneshot_unit_handle_t adc_ = nullptr; + adc_cali_handle_t calibration_ = nullptr; + BatteryEstimator estimator_; + bool invalid_sample_reported_ = false; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/ble_friend_exchange.cc b/main/platform/borla_s3/ble_friend_exchange.cc new file mode 100644 index 0000000..fd86596 --- /dev/null +++ b/main/platform/borla_s3/ble_friend_exchange.cc @@ -0,0 +1,480 @@ +#include "platform/borla_s3/ble_friend_exchange.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "BleFriend2"; +constexpr uint32_t kModeTimeoutMs = 30000; +constexpr uint32_t kPhaseDurationMs = 2000; +constexpr uint32_t kGraceDurationMs = 4000; +constexpr uint32_t kNimbleInitializationError = 12101; +constexpr uint32_t kNimbleSyncError = 12102; +constexpr uint32_t kGapStartError = 12103; +constexpr uint32_t kNimbleSyncTimeoutMs = 5000; +constexpr uint32_t kControllerReleaseDelayMs = 200; + +BleFriendExchange* g_exchange = nullptr; + +} // namespace + +bool BleFriendExchange::Initialize() +{ + if (initialized_.load()) { + return true; + } + if (g_exchange != nullptr && g_exchange != this) { + return false; + } + queue_ = xQueueCreateStatic( + kQueueDepth, + sizeof(Command), + queue_storage_.data(), + &queue_control_); + if (queue_ == nullptr) { + return false; + } + candidate_mutex_ = + xSemaphoreCreateMutexStatic(&candidate_mutex_storage_); + if (candidate_mutex_ == nullptr) { + return false; + } + const esp_timer_create_args_t timer_args = { + .callback = &BleFriendExchange::TimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "friend_tick2", + .skip_unhandled_events = true, + }; + if (esp_timer_create(&timer_args, &timer_) != ESP_OK) { + return false; + } + worker_task_ = xTaskCreateStatic( + &BleFriendExchange::WorkerTaskEntry, + "friend_ble2", + worker_task_stack_.size(), + this, + kWorkerPriority, + worker_task_stack_.data(), + &worker_task_control_); + if (worker_task_ == nullptr) { + return false; + } + g_exchange = this; + initialized_.store(true); + return true; +} + +bool BleFriendExchange::Start( + const char* local_base_mac, + IBleFriendExchangeObserver& observer) +{ + Command command; + command.type = CommandType::kStart; + command.observer = &observer; + if (!BuildFriendAdvertisingName( + local_base_mac, + command.advertising_name.data(), + command.advertising_name.size())) { + return false; + } + return Post(command); +} + +void BleFriendExchange::Stop() +{ + Post({CommandType::kStop}); +} + +void BleFriendExchange::WorkerTaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void BleFriendExchange::HostTaskEntry(void* context) +{ + auto* exchange = static_cast(context); + ESP_LOGI(kTag, "NimBLE host task started"); + nimble_port_run(); + exchange->host_task_ = nullptr; + vTaskDelete(nullptr); +} + +void BleFriendExchange::TimerCallback(void* context) +{ + auto* exchange = static_cast(context); + exchange->Post({CommandType::kTick}); +} + +void BleFriendExchange::HostSyncCallback() +{ + if (g_exchange == nullptr || !g_exchange->active_.load()) { + return; + } + int result = ble_hs_util_ensure_addr(0); + if (result == 0) { + result = ble_hs_id_infer_auto( + 0, &g_exchange->own_address_type_); + } + if (result != 0) { + ESP_LOGE(kTag, "BLE address setup failed rc=%d", result); + g_exchange->Post({CommandType::kStop}); + return; + } + g_exchange->host_synced_.store(true); + g_exchange->Post({CommandType::kSynced}); +} + +void BleFriendExchange::HostResetCallback(int reason) +{ + ESP_LOGW(kTag, "NimBLE host reset reason=%d", reason); +} + +int BleFriendExchange::GapEventCallback( + ble_gap_event* event, + void* context) +{ + auto* exchange = static_cast(context); + return exchange == nullptr + ? 0 + : exchange->HandleGapEvent(event); +} + +[[noreturn]] void BleFriendExchange::Run() +{ + while (true) { + Command command; + if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) { + Handle(command); + } + } +} + +bool BleFriendExchange::Post(const Command& command) +{ + return initialized_.load() && queue_ != nullptr && + xQueueSend(queue_, &command, 0) == pdTRUE; +} + +void BleFriendExchange::Handle(const Command& command) +{ + switch (command.type) { + case CommandType::kStart: + HandleStart(command); + return; + case CommandType::kStop: + HandleStop(0); + return; + case CommandType::kSynced: + if (active_.load() && !StartScan()) { + HandleStop(kGapStartError); + } + return; + case CommandType::kScanComplete: + if (!active_.load()) { + return; + } + if (grace_requested_) { + grace_requested_ = false; + if (!StartAdvertising(true)) { + HandleStop(kGapStartError); + } + } else if (!StartAdvertising(false)) { + HandleStop(kGapStartError); + } + return; + case CommandType::kAdvertiseComplete: + if (!active_.load()) { + return; + } + if (phase_ == GapPhase::kGraceAdvertising) { + HandleStop(0); + } else if (grace_requested_) { + grace_requested_ = false; + if (!StartAdvertising(true)) { + HandleStop(kGapStartError); + } + } else if (!StartScan()) { + HandleStop(kGapStartError); + } + return; + case CommandType::kTick: + HandleTick(); + return; + } +} + +void BleFriendExchange::HandleStart(const Command& command) +{ + if (active_.load()) { + return; + } + observer_ = command.observer; + advertising_name_ = command.advertising_name; + ResetCandidates(); + paired_ = false; + match_reported_ = false; + grace_requested_ = false; + phase_ = GapPhase::kIdle; + host_synced_.store(false); + active_.store(true); + const uint64_t now = NowMs(); + sync_deadline_ms_ = now + kNimbleSyncTimeoutMs; + deadline_ms_ = now + kModeTimeoutMs; + + const esp_err_t init_result = nimble_port_init(); + if (init_result != ESP_OK) { + ESP_LOGE(kTag, "nimble_port_init failed: %s", + esp_err_to_name(init_result)); + HandleStop(kNimbleInitializationError); + return; + } + nimble_initialized_ = true; + ble_hs_cfg.reset_cb = &BleFriendExchange::HostResetCallback; + ble_hs_cfg.sync_cb = &BleFriendExchange::HostSyncCallback; + ble_svc_gap_init(); + if (ble_svc_gap_device_name_set( + advertising_name_.data()) != 0) { + HandleStop(kNimbleInitializationError); + return; + } + host_task_ = xTaskCreateStaticPinnedToCore( + &BleFriendExchange::HostTaskEntry, + "friend_host2", + host_task_stack_.size(), + this, + configMAX_PRIORITIES - 4, + host_task_stack_.data(), + &host_task_control_, + CONFIG_BT_NIMBLE_PINNED_TO_CORE); + if (host_task_ == nullptr) { + HandleStop(kNimbleInitializationError); + return; + } + esp_timer_stop(timer_); + esp_timer_start_periodic(timer_, 1000ULL * 1000ULL); + ESP_LOGI(kTag, "friend exchange started name=%s", + advertising_name_.data()); +} + +void BleFriendExchange::HandleStop(uint32_t error_id) +{ + if (!active_.exchange(false) && !nimble_initialized_) { + return; + } + if (timer_ != nullptr) { + esp_timer_stop(timer_); + } + if (host_synced_.load()) { + ble_gap_disc_cancel(); + ble_gap_adv_stop(); + // Both calls only queue the stop to the controller. Tearing the host + // down in the same breath can deinit the port while the controller is + // still winding an advertising or scan context down, and the BT memory + // then comes back late or not at all — which matters here because the + // caller re-attaches WiFi immediately afterwards and the two stacks + // together do not fit in internal RAM. The previous firmware waited the + // same 200 ms in the same position for the same reason. + vTaskDelay(pdMS_TO_TICKS(kControllerReleaseDelayMs)); + } + if (nimble_initialized_) { + const int stop_result = nimble_port_stop(); + if (stop_result == 0) { + nimble_port_deinit(); + } else { + ESP_LOGW(kTag, "nimble stop failed rc=%d", stop_result); + if (error_id == 0) { + error_id = kNimbleInitializationError; + } + } + } + nimble_initialized_ = false; + host_synced_.store(false); + phase_ = GapPhase::kIdle; + sync_deadline_ms_ = 0; + deadline_ms_ = 0; + ResetCandidates(); + IBleFriendExchangeObserver* observer = observer_; + observer_ = nullptr; + if (observer != nullptr) { + observer->OnBleFriendExchangeStopped(paired_, error_id); + } + ESP_LOGI(kTag, "friend exchange stopped paired=%d error=%lu", + paired_ ? 1 : 0, + static_cast(error_id)); +} + +bool BleFriendExchange::StartScan() +{ + ble_gap_disc_params parameters{}; + parameters.passive = 1; + parameters.itvl = 80; + parameters.window = 60; + parameters.filter_duplicates = 0; + parameters.limited = 0; + const int result = ble_gap_disc( + own_address_type_, + kPhaseDurationMs, + ¶meters, + &BleFriendExchange::GapEventCallback, + this); + if (result != 0) { + ESP_LOGE(kTag, "scan start failed rc=%d", result); + return false; + } + phase_ = GapPhase::kScanning; + return true; +} + +bool BleFriendExchange::StartAdvertising(bool grace) +{ + ble_hs_adv_fields fields{}; + fields.flags = + BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; + fields.name = reinterpret_cast( + advertising_name_.data()); + fields.name_len = static_cast( + std::strlen(advertising_name_.data())); + fields.name_is_complete = 1; + int result = ble_gap_adv_set_fields(&fields); + if (result != 0) { + return false; + } + ble_gap_adv_params parameters{}; + parameters.conn_mode = BLE_GAP_CONN_MODE_NON; + parameters.disc_mode = BLE_GAP_DISC_MODE_GEN; + parameters.itvl_min = 48; + parameters.itvl_max = 96; + result = ble_gap_adv_start( + own_address_type_, + nullptr, + grace ? kGraceDurationMs : kPhaseDurationMs, + ¶meters, + &BleFriendExchange::GapEventCallback, + this); + if (result != 0) { + ESP_LOGE(kTag, "advertising start failed rc=%d", result); + return false; + } + phase_ = grace + ? GapPhase::kGraceAdvertising + : GapPhase::kAdvertising; + return true; +} + +void BleFriendExchange::HandleTick() +{ + if (!active_.load()) { + return; + } + const uint64_t now = NowMs(); + if (now >= deadline_ms_) { + HandleStop(0); + return; + } + if (!host_synced_.load() && now >= sync_deadline_ms_) { + HandleStop(kNimbleSyncError); + return; + } + if (match_reported_) { + return; + } + FriendPeer peer; + xSemaphoreTake(candidate_mutex_, portMAX_DELAY); + const bool matched = candidates_.Select(now, &peer); + xSemaphoreGive(candidate_mutex_); + if (!matched) { + return; + } + match_reported_ = true; + paired_ = true; + grace_requested_ = true; + if (observer_ != nullptr) { + observer_->OnBleFriendMatched(peer); + } + if (phase_ == GapPhase::kScanning) { + ble_gap_disc_cancel(); + } +} + +int BleFriendExchange::HandleGapEvent(ble_gap_event* event) +{ + if (event == nullptr || !active_.load()) { + return 0; + } + switch (event->type) { + case BLE_GAP_EVENT_DISC: { + ble_hs_adv_fields fields{}; + if (ble_hs_adv_parse_fields( + &fields, + event->disc.data, + event->disc.length_data) != 0 || + fields.name == nullptr || fields.name_len == 0 || + fields.name_len >= kFriendAdvertisingNameCapacity) { + return 0; + } + std::array name{}; + std::memcpy(name.data(), fields.name, fields.name_len); + char mac[kFriendMacCapacity]{}; + const ble_addr_t& address = event->disc.addr; + // Lower case to match every other MAC in the system; this raw BLE MAC + // is only a local dedup key, but NormalizeBleMacToBaseMac's output IS + // the peer's device_id and the server matches those case-sensitively. + std::snprintf( + mac, + sizeof(mac), + "%02x:%02x:%02x:%02x:%02x:%02x", + address.val[5], + address.val[4], + address.val[3], + address.val[2], + address.val[1], + address.val[0]); + xSemaphoreTake(candidate_mutex_, portMAX_DELAY); + candidates_.Observe( + mac, + name.data(), + static_cast(event->disc.rssi), + NowMs()); + xSemaphoreGive(candidate_mutex_); + return 0; + } + case BLE_GAP_EVENT_DISC_COMPLETE: + Post({CommandType::kScanComplete}); + return 0; + case BLE_GAP_EVENT_ADV_COMPLETE: + Post({CommandType::kAdvertiseComplete}); + return 0; + default: + return 0; + } +} + +void BleFriendExchange::ResetCandidates() +{ + if (candidate_mutex_ == nullptr) { + candidates_.Reset(); + return; + } + xSemaphoreTake(candidate_mutex_, portMAX_DELAY); + candidates_.Reset(); + xSemaphoreGive(candidate_mutex_); +} + +uint64_t BleFriendExchange::NowMs() const +{ + return static_cast( + esp_timer_get_time() / 1000ULL); +} + +} // namespace borla diff --git a/main/platform/borla_s3/ble_friend_exchange.h b/main/platform/borla_s3/ble_friend_exchange.h new file mode 100644 index 0000000..7c6fad8 --- /dev/null +++ b/main/platform/borla_s3/ble_friend_exchange.h @@ -0,0 +1,130 @@ +#pragma once + +#include "friend/friend_types.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace borla { + +class IBleFriendExchangeObserver { +public: + virtual ~IBleFriendExchangeObserver() = default; + virtual void OnBleFriendMatched(const FriendPeer& peer) = 0; + virtual void OnBleFriendExchangeStopped( + bool paired, + uint32_t error_id) = 0; +}; + +class BleFriendExchange final { +public: + bool Initialize(); + bool Start( + const char* local_base_mac, + IBleFriendExchangeObserver& observer); + void Stop(); + bool IsActive() const { return active_.load(); } + +private: + enum class CommandType : uint8_t { + kStart, + kStop, + kSynced, + kScanComplete, + kAdvertiseComplete, + kTick, + }; + + struct Command { + CommandType type = CommandType::kTick; + IBleFriendExchangeObserver* observer = nullptr; + std::array + advertising_name{}; + }; + + enum class GapPhase : uint8_t { + kIdle, + kScanning, + kAdvertising, + kGraceAdvertising, + }; + + static constexpr size_t kQueueDepth = 12; + // ESP-IDF expresses task stack depths in bytes. Its Xtensa + // StackType_t is uint8_t, so the static arrays have the same size. + //static constexpr uint32_t kWorkerStackDepth = 2048; + // 2026-9-6 ckkj fix: worker 在本任务栈上执行 nimble_port_init/deinit + // (调用链深),叠加 Xtensa ISR 压栈后 2048 字节溢出触发 canary panic, + // 提升到与 host 任务一致的 4096。 + static constexpr uint32_t kWorkerStackDepth = 4096; + static constexpr uint32_t kHostStackDepth = 4096; + static constexpr UBaseType_t kWorkerPriority = 5; + + static void WorkerTaskEntry(void* context); + static void HostTaskEntry(void* context); + static void TimerCallback(void* context); + static void HostSyncCallback(); + static void HostResetCallback(int reason); + static int GapEventCallback( + ble_gap_event* event, + void* context); + + [[noreturn]] void Run(); + bool Post(const Command& command); + void Handle(const Command& command); + void HandleStart(const Command& command); + void HandleStop(uint32_t error_id); + bool StartScan(); + bool StartAdvertising(bool grace); + void HandleTick(); + void ResetCandidates(); + int HandleGapEvent(ble_gap_event* event); + uint64_t NowMs() const; + + QueueHandle_t queue_ = nullptr; + StaticQueue_t queue_control_{}; + alignas(Command) + std::array + queue_storage_{}; + TaskHandle_t worker_task_ = nullptr; + StaticTask_t worker_task_control_{}; + std::array + worker_task_stack_{}; + TaskHandle_t host_task_ = nullptr; + StaticTask_t host_task_control_{}; + std::array + host_task_stack_{}; + esp_timer_handle_t timer_ = nullptr; + + // Candidate bookkeeping runs string compares and, on selection, sscanf and + // snprintf. That is far too much work for a spinlock with interrupts + // disabled; both callers (NimBLE host task, friend worker task) can block. + SemaphoreHandle_t candidate_mutex_ = nullptr; + StaticSemaphore_t candidate_mutex_storage_{}; + FriendCandidateSelector candidates_; + IBleFriendExchangeObserver* observer_ = nullptr; + std::array + advertising_name_{}; + std::atomic initialized_{false}; + std::atomic active_{false}; + std::atomic host_synced_{false}; + bool nimble_initialized_ = false; + bool paired_ = false; + bool match_reported_ = false; + bool grace_requested_ = false; + uint8_t own_address_type_ = 0; + GapPhase phase_ = GapPhase::kIdle; + uint64_t sync_deadline_ms_ = 0; + uint64_t deadline_ms_ = 0; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/ble_provisioning_gatt.cc b/main/platform/borla_s3/ble_provisioning_gatt.cc new file mode 100644 index 0000000..20e247d --- /dev/null +++ b/main/platform/borla_s3/ble_provisioning_gatt.cc @@ -0,0 +1,717 @@ +#include "platform/borla_s3/ble_provisioning_gatt.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" void ble_store_config_init(void); + +namespace borla { +namespace { + +constexpr const char* kTag = "BleProvisioning2"; +constexpr uint16_t kPreferredMtu = 517; +constexpr uint16_t kInvalidConnectionHandle = 0xffff; +constexpr uint32_t kHostSyncTimeoutMs = 3000; + +BleProvisioningGattServer* g_server = nullptr; +uint16_t g_scan_value_handle = 0; +uint16_t g_result_value_handle = 0; +uint16_t g_saved_wifi_value_handle = 0; + +const ble_uuid128_t kServiceUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00); +const ble_uuid128_t kDeviceInfoUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x02, 0xff, 0x00, 0x00); +const ble_uuid128_t kWifiScanUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x03, 0xff, 0x00, 0x00); +const ble_uuid128_t kWifiConfigUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x04, 0xff, 0x00, 0x00); +const ble_uuid128_t kWifiResultUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x05, 0xff, 0x00, 0x00); +const ble_uuid128_t kCommandUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x06, 0xff, 0x00, 0x00); +const ble_uuid128_t kSavedWifiUuid = + BLE_UUID128_INIT( + 0xfb, 0x34, 0x9b, 0x5f, 0x80, 0x00, 0x00, 0x80, + 0x00, 0x10, 0x00, 0x00, 0x07, 0xff, 0x00, 0x00); + +ble_gatt_chr_def g_characteristics[] = { + { + .uuid = &kDeviceInfoUuid.u, + .access_cb = BorlaBleGattAccess, + .arg = nullptr, + .descriptors = nullptr, + .flags = BLE_GATT_CHR_F_READ, + .min_key_size = 0, + .val_handle = nullptr, + .cpfd = nullptr, + }, + { + .uuid = &kWifiScanUuid.u, + .access_cb = BorlaBleGattAccess, + .arg = nullptr, + .descriptors = nullptr, + .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY, + .min_key_size = 0, + .val_handle = &g_scan_value_handle, + .cpfd = nullptr, + }, + { + .uuid = &kWifiConfigUuid.u, + .access_cb = BorlaBleGattAccess, + .arg = nullptr, + .descriptors = nullptr, + .flags = BLE_GATT_CHR_F_WRITE, + .min_key_size = 0, + .val_handle = nullptr, + .cpfd = nullptr, + }, + { + .uuid = &kWifiResultUuid.u, + .access_cb = BorlaBleGattAccess, + .arg = nullptr, + .descriptors = nullptr, + .flags = BLE_GATT_CHR_F_NOTIFY, + .min_key_size = 0, + .val_handle = &g_result_value_handle, + .cpfd = nullptr, + }, + { + .uuid = &kCommandUuid.u, + .access_cb = BorlaBleGattAccess, + .arg = nullptr, + .descriptors = nullptr, + .flags = BLE_GATT_CHR_F_WRITE, + .min_key_size = 0, + .val_handle = nullptr, + .cpfd = nullptr, + }, + { + .uuid = &kSavedWifiUuid.u, + .access_cb = BorlaBleGattAccess, + .arg = nullptr, + .descriptors = nullptr, + .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY, + .min_key_size = 0, + .val_handle = &g_saved_wifi_value_handle, + .cpfd = nullptr, + }, + {}, +}; + +const ble_gatt_svc_def g_services[] = { + { + .type = BLE_GATT_SVC_TYPE_PRIMARY, + .uuid = &kServiceUuid.u, + .includes = nullptr, + .characteristics = g_characteristics, + }, + {}, +}; + +bool ReadMbuf( + os_mbuf* buffer, + uint8_t* output, + size_t capacity, + size_t* size) +{ + if (buffer == nullptr || output == nullptr || size == nullptr) { + return false; + } + const size_t packet_size = OS_MBUF_PKTLEN(buffer); + if (packet_size == 0 || packet_size > capacity) { + return false; + } + uint16_t copied = 0; + if (ble_hs_mbuf_to_flat( + buffer, + output, + static_cast(capacity), + &copied) != 0 || + copied != packet_size) { + return false; + } + *size = packet_size; + return true; +} + +} // namespace + +bool BleProvisioningGattServer::Start( + const DeviceIdentity& identity, + IBleProvisioningGattObserver& observer) +{ + if (running_.load()) { + return true; + } + if (g_server != nullptr && g_server != this) { + ESP_LOGE(kTag, "only one BLE provisioning server is supported"); + return false; + } + + identity_ = identity; + observer_ = &observer; + if (!BuildProvisioningDeviceInfoJson( + identity_, + device_info_json_.data(), + device_info_json_.size(), + &device_info_size_)) { + ESP_LOGE(kTag, "device info JSON creation failed"); + return false; + } + + char name[16] = "Borla-0000"; + size_t suffix_index = 6; + for (size_t index = 0; + identity_.mac[index] != '\0'; + ++index) { + const char value = identity_.mac[index]; + if (value == ':') { + continue; + } + if (suffix_index == 10) { + std::memmove(name + 6, name + 7, 3); + suffix_index = 9; + } + name[suffix_index++] = value; + } + name[10] = '\0'; + + g_server = this; + host_started_.store(false); + host_synced_.store(false); + ClearConnection(); + + const esp_err_t init_result = nimble_port_init(); + if (init_result != ESP_OK) { + ESP_LOGE(kTag, "nimble_port_init failed: %s", + esp_err_to_name(init_result)); + g_server = nullptr; + return false; + } + + ble_hs_cfg.reset_cb = &BleProvisioningGattServer::OnHostReset; + ble_hs_cfg.sync_cb = &BleProvisioningGattServer::OnHostSync; + ble_hs_cfg.store_status_cb = ble_store_util_status_rr; + ble_store_config_init(); + ble_att_set_preferred_mtu(kPreferredMtu); + ble_svc_gap_init(); + ble_svc_gatt_init(); + + int result = ble_gatts_count_cfg(g_services); + if (result == 0) { + result = ble_gatts_add_svcs(g_services); + } + if (result == 0) { + result = ble_svc_gap_device_name_set(name); + } + if (result != 0) { + ESP_LOGE(kTag, "GATT service setup failed rc=%d", result); + nimble_port_deinit(); + g_server = nullptr; + return false; + } + + running_.store(true); + host_task_ = xTaskCreateStaticPinnedToCore( + &BleProvisioningGattServer::HostTask, + "nimble_host2", + host_task_stack_.size(), + this, + configMAX_PRIORITIES - 4, + host_task_stack_.data(), + &host_task_control_, + CONFIG_BT_NIMBLE_PINNED_TO_CORE); + if (host_task_ == nullptr) { + ESP_LOGE(kTag, "static NimBLE host task creation failed"); + running_.store(false); + nimble_port_deinit(); + g_server = nullptr; + return false; + } + const TickType_t delay = pdMS_TO_TICKS(50); + const uint32_t attempts = + std::max(1, kHostSyncTimeoutMs / 50); + for (uint32_t attempt = 0; + attempt < attempts && !host_synced_.load(); + ++attempt) { + vTaskDelay(delay); + } + if (!host_started_.load() || !host_synced_.load()) { + ESP_LOGE( + kTag, + "NimBLE host unavailable started=%d synced=%d " + "internal_free=%u largest=%u", + host_started_.load() ? 1 : 0, + host_synced_.load() ? 1 : 0, + static_cast( + heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL))); + Stop(); + return false; + } + + ESP_LOGI(kTag, "BLE provisioning ready name=%s mtu=%u", + name, static_cast(kPreferredMtu)); + return true; +} + +void BleProvisioningGattServer::Stop() +{ + if (!running_.exchange(false)) { + return; + } + ble_gap_adv_stop(); + if (connected_.load()) { + uint16_t connection = kInvalidConnectionHandle; + portENTER_CRITICAL(&connection_lock_); + connection = connection_handle_; + portEXIT_CRITICAL(&connection_lock_); + if (connection != kInvalidConnectionHandle) { + ble_gap_terminate( + connection, BLE_ERR_REM_USER_CONN_TERM); + } + } + if (nimble_port_stop() == 0) { + nimble_port_deinit(); + } + ClearConnection(); + observer_ = nullptr; + g_server = nullptr; + ESP_LOGI(kTag, "BLE provisioning stopped"); +} + +bool BleProvisioningGattServer::NotifyScanResults( + const WifiNetwork* networks, + size_t count) +{ + notification_json_.fill('\0'); + size_t size = 0; + return BuildProvisioningScanJson( + networks, + count, + notification_json_.data(), + notification_json_.size(), + &size) && + NotifyChunked( + g_scan_value_handle, + notification_json_.data(), + size); +} + +bool BleProvisioningGattServer::NotifyWifiResult( + bool success, + const char* error) +{ + std::array json{}; + size_t size = 0; + return BuildProvisioningResultJson( + success, error, json.data(), json.size(), &size) && + NotifySingle(g_result_value_handle, json.data(), size); +} + +bool BleProvisioningGattServer::NotifySavedWifi( + const WifiCredential* credentials, + size_t count) +{ + notification_json_.fill('\0'); + size_t size = 0; + return BuildProvisioningSavedWifiJson( + credentials, + count, + notification_json_.data(), + notification_json_.size(), + &size) && + NotifyChunked( + g_saved_wifi_value_handle, + notification_json_.data(), + size); +} + +bool BleProvisioningGattServer::NotifySavedWifiResult( + bool success, + const char* error) +{ + std::array json{}; + size_t size = 0; + return BuildProvisioningResultJson( + success, error, json.data(), json.size(), &size) && + NotifyChunked( + g_saved_wifi_value_handle, json.data(), size); +} + +void BleProvisioningGattServer::HostTask(void* context) +{ + auto* server = + static_cast(context); + server->host_started_.store(true); + ESP_LOGI(kTag, "NimBLE host task started"); + nimble_port_run(); + server->host_task_ = nullptr; + vTaskDelete(nullptr); +} + +void BleProvisioningGattServer::OnHostSync() +{ + if (g_server == nullptr) { + return; + } + int result = ble_hs_util_ensure_addr(0); + if (result == 0) { + result = ble_hs_id_infer_auto( + 0, &g_server->own_address_type_); + } + if (result != 0) { + ESP_LOGE(kTag, "BLE address setup failed rc=%d", result); + return; + } + g_server->host_synced_.store(true); + g_server->StartAdvertising(); +} + +void BleProvisioningGattServer::OnHostReset(int reason) +{ + ESP_LOGW(kTag, "NimBLE host reset reason=%d", reason); +} + +bool BleProvisioningGattServer::StartAdvertising() +{ + if (!running_.load()) { + return false; + } + ble_hs_adv_fields fields{}; + fields.flags = + BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; + ble_uuid16_t service = BLE_UUID16_INIT(0xff01); + fields.uuids16 = &service; + fields.num_uuids16 = 1; + fields.uuids16_is_complete = 1; + const char* name = ble_svc_gap_device_name(); + fields.name = + reinterpret_cast(const_cast(name)); + fields.name_len = + static_cast(std::strlen(name)); + fields.name_is_complete = 1; + int result = ble_gap_adv_set_fields(&fields); + if (result != 0) { + ESP_LOGE(kTag, "advertising data setup failed rc=%d", result); + return false; + } + + ble_gap_adv_params parameters{}; + parameters.conn_mode = BLE_GAP_CONN_MODE_UND; + parameters.disc_mode = BLE_GAP_DISC_MODE_GEN; + result = ble_gap_adv_start( + own_address_type_, + nullptr, + BLE_HS_FOREVER, + ¶meters, + BorlaBleGapEvent, + this); + if (result != 0) { + ESP_LOGE(kTag, "advertising start failed rc=%d", result); + return false; + } + ESP_LOGI(kTag, "BLE provisioning advertising"); + return true; +} + +int BleProvisioningGattServer::HandleGattAccess( + ble_gatt_access_ctxt* context) +{ + if (context == nullptr || context->chr == nullptr) { + return BLE_ATT_ERR_UNLIKELY; + } + const ble_uuid_t* uuid = context->chr->uuid; + if (ble_uuid_cmp(uuid, &kDeviceInfoUuid.u) == 0) { + return HandleDeviceInfoRead(context); + } + if (ble_uuid_cmp(uuid, &kWifiScanUuid.u) == 0) { + return HandleScanWrite(context); + } + if (ble_uuid_cmp(uuid, &kWifiConfigUuid.u) == 0) { + return HandleCredentialWrite(context); + } + if (ble_uuid_cmp(uuid, &kCommandUuid.u) == 0) { + return HandleCommandWrite(context); + } + if (ble_uuid_cmp(uuid, &kSavedWifiUuid.u) == 0) { + return HandleSavedWifiWrite(context); + } + if (ble_uuid_cmp(uuid, &kWifiResultUuid.u) == 0) { + return 0; + } + return BLE_ATT_ERR_UNLIKELY; +} + +int BleProvisioningGattServer::HandleDeviceInfoRead( + ble_gatt_access_ctxt* context) +{ + return os_mbuf_append( + context->om, + device_info_json_.data(), + device_info_size_) == 0 + ? 0 + : BLE_ATT_ERR_INSUFFICIENT_RES; +} + +int BleProvisioningGattServer::HandleScanWrite( + ble_gatt_access_ctxt* context) +{ + std::array packet{}; + size_t size = 0; + if (!ReadMbuf( + context->om, packet.data(), packet.size(), &size) || + size != 1 || packet[0] != 0x01) { + return BLE_ATT_ERR_VALUE_NOT_ALLOWED; + } + if (observer_ != nullptr) { + observer_->OnBleWifiScanRequested(); + } + return 0; +} + +int BleProvisioningGattServer::HandleCredentialWrite( + ble_gatt_access_ctxt* context) +{ + std::array packet{}; + size_t size = 0; + if (!ReadMbuf( + context->om, packet.data(), packet.size(), &size)) { + credential_assembler_.Reset(); + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + const BleChunkAssemblyResult result = + credential_assembler_.Push(packet.data(), size); + if (result == BleChunkAssemblyResult::kInvalid) { + return BLE_ATT_ERR_VALUE_NOT_ALLOWED; + } + if (result == BleChunkAssemblyResult::kComplete) { + WifiCredential credential; + if (!ParseProvisioningCredential( + credential_assembler_.data(), + credential_assembler_.size(), + &credential)) { + credential_assembler_.Reset(); + NotifyWifiResult(false, "unknown"); + return 0; + } + credential_assembler_.Reset(); + if (observer_ != nullptr) { + observer_->OnBleWifiCredential(credential); + } + } + return 0; +} + +int BleProvisioningGattServer::HandleCommandWrite( + ble_gatt_access_ctxt* context) +{ + std::array packet{}; + size_t size = 0; + if (!ReadMbuf( + context->om, packet.data(), packet.size(), &size) || + size != 1 || packet[0] != 0x01) { + return BLE_ATT_ERR_VALUE_NOT_ALLOWED; + } + if (observer_ != nullptr) { + observer_->OnBleRebootRequested(); + } + return 0; +} + +int BleProvisioningGattServer::HandleSavedWifiWrite( + ble_gatt_access_ctxt* context) +{ + std::array packet{}; + size_t size = 0; + if (!ReadMbuf( + context->om, packet.data(), packet.size(), &size)) { + return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; + } + if (size == 1 && packet[0] == 0x01) { + if (observer_ != nullptr) { + observer_->OnBleSavedWifiListRequested(); + } + return 0; + } + if (size == 2 && packet[0] == 0x02) { + if (observer_ != nullptr) { + observer_->OnBleSavedWifiDeleteRequested(packet[1]); + } + return 0; + } + return BLE_ATT_ERR_VALUE_NOT_ALLOWED; +} + +bool BleProvisioningGattServer::NotifyChunked( + uint16_t value_handle, + const char* json, + size_t size) +{ + if (!connected_.load() || value_handle == 0) { + return false; + } + uint16_t mtu = 23; + portENTER_CRITICAL(&connection_lock_); + active_notification_handle_ = value_handle; + mtu = negotiated_mtu_; + portEXIT_CRITICAL(&connection_lock_); + const bool result = + VisitBleNotificationChunks(json, size, mtu, *this); + portENTER_CRITICAL(&connection_lock_); + active_notification_handle_ = 0; + portEXIT_CRITICAL(&connection_lock_); + return result; +} + +bool BleProvisioningGattServer::NotifySingle( + uint16_t value_handle, + const char* json, + size_t size) +{ + if (!connected_.load() || value_handle == 0 || + json == nullptr || size == 0) { + return false; + } + uint16_t connection = kInvalidConnectionHandle; + portENTER_CRITICAL(&connection_lock_); + connection = connection_handle_; + portEXIT_CRITICAL(&connection_lock_); + os_mbuf* buffer = ble_hs_mbuf_from_flat(json, size); + return buffer != nullptr && + ble_gatts_notify_custom( + connection, value_handle, buffer) == 0; +} + +bool BleProvisioningGattServer::OnBleChunk( + const uint8_t* data, + size_t size) +{ + uint16_t connection = kInvalidConnectionHandle; + uint16_t value_handle = 0; + portENTER_CRITICAL(&connection_lock_); + connection = connection_handle_; + value_handle = active_notification_handle_; + portEXIT_CRITICAL(&connection_lock_); + if (!connected_.load() || + connection == kInvalidConnectionHandle || + value_handle == 0) { + return false; + } + os_mbuf* buffer = ble_hs_mbuf_from_flat(data, size); + if (buffer == nullptr || + ble_gatts_notify_custom( + connection, value_handle, buffer) != 0) { + return false; + } + vTaskDelay(pdMS_TO_TICKS(60)); + return true; +} + +void BleProvisioningGattServer::ClearConnection() +{ + portENTER_CRITICAL(&connection_lock_); + connection_handle_ = kInvalidConnectionHandle; + negotiated_mtu_ = 23; + active_notification_handle_ = 0; + portEXIT_CRITICAL(&connection_lock_); + connected_.store(false); + credential_assembler_.Reset(); +} + +int BorlaBleGapEvent( + ble_gap_event* event, + void* context) +{ + auto* server = + static_cast(context); + if (server == nullptr || event == nullptr) { + return 0; + } + switch (event->type) { + case BLE_GAP_EVENT_CONNECT: + if (event->connect.status == 0) { + portENTER_CRITICAL(&server->connection_lock_); + server->connection_handle_ = + event->connect.conn_handle; + server->negotiated_mtu_ = + ble_att_mtu(event->connect.conn_handle); + portEXIT_CRITICAL(&server->connection_lock_); + server->connected_.store(true); + ESP_LOGI(kTag, "BLE client connected handle=%u mtu=%u", + static_cast( + event->connect.conn_handle), + static_cast( + server->negotiated_mtu_)); + } else { + ESP_LOGW(kTag, "BLE connection failed status=%d", + event->connect.status); + server->StartAdvertising(); + } + break; + case BLE_GAP_EVENT_DISCONNECT: + ESP_LOGI(kTag, "BLE client disconnected reason=%d", + event->disconnect.reason); + server->ClearConnection(); + server->StartAdvertising(); + break; + case BLE_GAP_EVENT_MTU: + portENTER_CRITICAL(&server->connection_lock_); + server->negotiated_mtu_ = + std::min( + event->mtu.value, kPreferredMtu); + portEXIT_CRITICAL(&server->connection_lock_); + ESP_LOGI(kTag, "BLE MTU=%u", + static_cast(event->mtu.value)); + break; + case BLE_GAP_EVENT_ADV_COMPLETE: + if (!server->connected_.load()) { + server->StartAdvertising(); + } + break; + default: + break; + } + return 0; +} + +int BorlaBleGattAccess( + uint16_t, + uint16_t, + ble_gatt_access_ctxt* context, + void*) +{ + return g_server == nullptr + ? BLE_ATT_ERR_UNLIKELY + : g_server->HandleGattAccess(context); +} + +} // namespace borla diff --git a/main/platform/borla_s3/ble_provisioning_gatt.h b/main/platform/borla_s3/ble_provisioning_gatt.h new file mode 100644 index 0000000..2e9d8a4 --- /dev/null +++ b/main/platform/borla_s3/ble_provisioning_gatt.h @@ -0,0 +1,112 @@ +#pragma once + +#include "connectivity/wifi_types.h" +#include "ports/device_platform.h" +#include "provisioning/ble_provisioning_codec.h" + +#include +#include +#include +#include + +#include +#include +#include + +struct ble_gap_event; +struct ble_gatt_access_ctxt; + +namespace borla { + +class IBleProvisioningGattObserver { +public: + virtual ~IBleProvisioningGattObserver() = default; + virtual void OnBleWifiScanRequested() = 0; + virtual void OnBleWifiCredential( + const WifiCredential& credential) = 0; + virtual void OnBleSavedWifiListRequested() = 0; + virtual void OnBleSavedWifiDeleteRequested(uint8_t index) = 0; + virtual void OnBleRebootRequested() = 0; +}; + +class BleProvisioningGattServer final : private IBleChunkVisitor { +public: + bool Start( + const DeviceIdentity& identity, + IBleProvisioningGattObserver& observer); + void Stop(); + + bool NotifyScanResults( + const WifiNetwork* networks, + size_t count); + bool NotifyWifiResult(bool success, const char* error); + bool NotifySavedWifi( + const WifiCredential* credentials, + size_t count); + bool NotifySavedWifiResult(bool success, const char* error); + + bool running() const { return running_.load(); } + bool connected() const { return connected_.load(); } + +private: + friend int BorlaBleGapEvent( + struct ble_gap_event* event, + void* context); + friend int BorlaBleGattAccess( + uint16_t connection_handle, + uint16_t attribute_handle, + struct ble_gatt_access_ctxt* context, + void* argument); + + static void HostTask(void* context); + static void OnHostSync(); + static void OnHostReset(int reason); + + bool StartAdvertising(); + int HandleGattAccess(struct ble_gatt_access_ctxt* context); + int HandleDeviceInfoRead(struct ble_gatt_access_ctxt* context); + int HandleScanWrite(struct ble_gatt_access_ctxt* context); + int HandleCredentialWrite(struct ble_gatt_access_ctxt* context); + int HandleCommandWrite(struct ble_gatt_access_ctxt* context); + int HandleSavedWifiWrite(struct ble_gatt_access_ctxt* context); + bool NotifyChunked(uint16_t value_handle, const char* json, size_t size); + bool NotifySingle(uint16_t value_handle, const char* json, size_t size); + bool OnBleChunk(const uint8_t* data, size_t size) override; + void ClearConnection(); + + IBleProvisioningGattObserver* observer_ = nullptr; + DeviceIdentity identity_{}; + std::array device_info_json_{}; + size_t device_info_size_ = 0; + std::array + notification_json_{}; + BleChunkAssembler credential_assembler_; + + mutable portMUX_TYPE connection_lock_ = + portMUX_INITIALIZER_UNLOCKED; + uint16_t connection_handle_ = 0; + uint16_t negotiated_mtu_ = 23; + uint16_t active_notification_handle_ = 0; + uint8_t own_address_type_ = 0; + + std::atomic running_{false}; + std::atomic connected_{false}; + std::atomic host_started_{false}; + std::atomic host_synced_{false}; + static constexpr uint32_t kHostTaskStackDepth = 4096; + TaskHandle_t host_task_ = nullptr; + StaticTask_t host_task_control_{}; + std::array + host_task_stack_{}; +}; + +int BorlaBleGapEvent( + struct ble_gap_event* event, + void* context); +int BorlaBleGattAccess( + uint16_t connection_handle, + uint16_t attribute_handle, + struct ble_gatt_access_ctxt* context, + void* argument); + +} // namespace borla diff --git a/main/platform/borla_s3/bmi270_sensor.cc b/main/platform/borla_s3/bmi270_sensor.cc new file mode 100644 index 0000000..1c7fcdc --- /dev/null +++ b/main/platform/borla_s3/bmi270_sensor.cc @@ -0,0 +1,235 @@ +#include "platform/borla_s3/bmi270_sensor.h" + +#include +#include + +#include +#include +#include +#include + +extern "C" { +extern const uint8_t bmi270_context_config_file[]; +extern const int bmi270_context_config_file_size; +} + +namespace borla { +namespace { + +constexpr const char* kTag = "Bmi270Sensor2"; +constexpr uint8_t kDeviceAddress = 0x68; +constexpr uint8_t kChipIdRegister = 0x00; +constexpr uint8_t kExpectedChipId = 0x24; +constexpr uint8_t kInternalStatusRegister = 0x21; +constexpr uint8_t kAccelDataRegister = 0x0C; +constexpr uint8_t kAccelConfigRegister = 0x40; +constexpr uint8_t kAccelRangeRegister = 0x41; +constexpr uint8_t kGyroConfigRegister = 0x42; +constexpr uint8_t kGyroRangeRegister = 0x43; +constexpr uint8_t kInitControlRegister = 0x59; +constexpr uint8_t kInitAddressLowRegister = 0x5B; +constexpr uint8_t kInitAddressHighRegister = 0x5C; +constexpr uint8_t kInitDataRegister = 0x5E; +constexpr uint8_t kPowerConfigRegister = 0x7C; +constexpr uint8_t kPowerControlRegister = 0x7D; +constexpr uint8_t kCommandRegister = 0x7E; +constexpr uint8_t kSoftResetCommand = 0xB6; +constexpr size_t kConfigurationChunkBytes = 32; +constexpr float kAccelScale = 16.0F / 32768.0F; +constexpr float kGyroScale = 2000.0F / 32768.0F; + +int16_t ReadLe16(const uint8_t* data) +{ + return static_cast( + static_cast(data[0]) | + static_cast(data[1]) << 8); +} + +} // namespace + +Bmi270Sensor::~Bmi270Sensor() +{ + if (device_ != nullptr) { + i2c_master_bus_rm_device(device_); + } +} + +bool Bmi270Sensor::Initialize() +{ + if (device_ != nullptr) { + return true; + } + if (!bus_.Initialize()) { + return false; + } + const i2c_device_config_t config = { + .dev_addr_length = I2C_ADDR_BIT_LEN_7, + .device_address = kDeviceAddress, + .scl_speed_hz = 400000, + .scl_wait_us = 0, + .flags = { + .disable_ack_check = false, + }, + }; + esp_err_t result = + i2c_master_bus_add_device(bus_.Handle(), &config, &device_); + if (result != ESP_OK) { + ESP_LOGW(kTag, "device not available: %s", + esp_err_to_name(result)); + device_ = nullptr; + return false; + } + + uint8_t chip_id = 0; + if (!ReadData(kChipIdRegister, &chip_id, 1) || + chip_id != kExpectedChipId) { + ESP_LOGW(kTag, "chip id mismatch got=0x%02x expected=0x%02x", + chip_id, kExpectedChipId); + i2c_master_bus_rm_device(device_); + device_ = nullptr; + return false; + } + if (!WriteRegister(kCommandRegister, kSoftResetCommand)) { + i2c_master_bus_rm_device(device_); + device_ = nullptr; + return false; + } + vTaskDelay(pdMS_TO_TICKS(3)); + if (!UploadConfiguration()) { + i2c_master_bus_rm_device(device_); + device_ = nullptr; + return false; + } + + // 50 Hz normal-performance sampling, ±16 g, ±2000 dps. + const bool configured = + WriteRegister(kAccelConfigRegister, 0xA7) && + WriteRegister(kAccelRangeRegister, 0x03) && + WriteRegister(kGyroConfigRegister, 0xA7) && + WriteRegister(kGyroRangeRegister, 0x00) && + WriteRegister(kPowerControlRegister, 0x06) && + WriteRegister(kPowerConfigRegister, 0x02); + if (!configured) { + ESP_LOGE(kTag, "runtime configuration failed"); + i2c_master_bus_rm_device(device_); + device_ = nullptr; + return false; + } + vTaskDelay(pdMS_TO_TICKS(5)); + ESP_LOGI(kTag, "initialized at 50Hz, accel=16g gyro=2000dps"); + return true; +} + +bool Bmi270Sensor::Read(ImuSample* sample) +{ + if (device_ == nullptr || sample == nullptr) { + return false; + } + std::array data{}; + if (!ReadData(kAccelDataRegister, data.data(), data.size())) { + read_failure_count_++; + if (read_failure_count_ == 1 || + read_failure_count_ % 50 == 0) { + ESP_LOGW(kTag, "read failures=%lu", + static_cast(read_failure_count_)); + } + return false; + } + read_failure_count_ = 0; + sample->ax = ReadLe16(&data[0]) * kAccelScale; + sample->ay = -ReadLe16(&data[2]) * kAccelScale; + sample->az = -ReadLe16(&data[4]) * kAccelScale; + sample->gx = ReadLe16(&data[6]) * kGyroScale; + sample->gy = -ReadLe16(&data[8]) * kGyroScale; + sample->gz = -ReadLe16(&data[10]) * kGyroScale; + return true; +} + +bool Bmi270Sensor::WriteRegister(uint8_t address, uint8_t value) +{ + return WriteData(address, &value, 1); +} + +bool Bmi270Sensor::WriteData( + uint8_t address, + const uint8_t* data, + size_t size) +{ + if (device_ == nullptr || data == nullptr || size > 64) { + return false; + } + std::array message{}; + message[0] = address; + std::copy_n(data, size, message.begin() + 1); + const esp_err_t result = i2c_master_transmit( + device_, message.data(), size + 1, 1000); + if (result != ESP_OK) { + ESP_LOGE(kTag, "write reg=0x%02x failed: %s", + address, esp_err_to_name(result)); + return false; + } + return true; +} + +bool Bmi270Sensor::ReadData( + uint8_t address, + uint8_t* data, + size_t size) +{ + if (device_ == nullptr || data == nullptr || size == 0) { + return false; + } + const esp_err_t result = i2c_master_transmit_receive( + device_, &address, 1, data, size, 1000); + return result == ESP_OK; +} + +bool Bmi270Sensor::UploadConfiguration() +{ + if (bmi270_context_config_file_size <= 0 || + !WriteRegister(kPowerConfigRegister, 0x00)) { + return false; + } + vTaskDelay(pdMS_TO_TICKS(10)); + if (!WriteRegister(kInitControlRegister, 0x00)) { + return false; + } + + const size_t total = + static_cast(bmi270_context_config_file_size); + for (size_t offset = 0; offset < total; + offset += kConfigurationChunkBytes) { + const uint16_t word_address = + static_cast(offset / 2); + const size_t chunk = std::min( + kConfigurationChunkBytes, total - offset); + if (!WriteRegister( + kInitAddressLowRegister, + static_cast(word_address & 0x0F)) || + !WriteRegister( + kInitAddressHighRegister, + static_cast(word_address >> 4)) || + !WriteData( + kInitDataRegister, + bmi270_context_config_file + offset, + chunk)) { + ESP_LOGE(kTag, "configuration upload failed at %u/%u", + static_cast(offset), + static_cast(total)); + return false; + } + } + if (!WriteRegister(kInitControlRegister, 0x01)) { + return false; + } + vTaskDelay(pdMS_TO_TICKS(20)); + uint8_t status = 0; + if (!ReadData(kInternalStatusRegister, &status, 1) || + (status & 0x0F) != 0x01) { + ESP_LOGE(kTag, "configuration rejected status=0x%02x", status); + return false; + } + return true; +} + +} // namespace borla diff --git a/main/platform/borla_s3/bmi270_sensor.h b/main/platform/borla_s3/bmi270_sensor.h new file mode 100644 index 0000000..f423007 --- /dev/null +++ b/main/platform/borla_s3/bmi270_sensor.h @@ -0,0 +1,35 @@ +#pragma once + +#include "platform/borla_s3/i2c_bus.h" +#include "sensor/sensor_types.h" + +#include +#include + +#include + +namespace borla { + +class Bmi270Sensor final { +public: + explicit Bmi270Sensor(BorlaS3I2cBus& bus) : bus_(bus) {} + ~Bmi270Sensor(); + + bool Initialize(); + bool Read(ImuSample* sample); + +private: + bool WriteRegister(uint8_t address, uint8_t value); + bool WriteData( + uint8_t address, + const uint8_t* data, + size_t size); + bool ReadData(uint8_t address, uint8_t* data, size_t size); + bool UploadConfiguration(); + + BorlaS3I2cBus& bus_; + i2c_master_dev_handle_t device_ = nullptr; + uint32_t read_failure_count_ = 0; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/board_config.h b/main/platform/borla_s3/board_config.h new file mode 100644 index 0000000..11a28ba --- /dev/null +++ b/main/platform/borla_s3/board_config.h @@ -0,0 +1,90 @@ +#pragma once + +#include + +#include +#include +#include "tca9555.h" + +namespace borla::board_config +{ + + inline constexpr const char *kBoardName = "borla-s3"; + + // inline constexpr gpio_num_t kMcuPowerGpio = GPIO_NUM_4; + // inline constexpr gpio_num_t kPeripheralPowerGpio = GPIO_NUM_6; + // inline constexpr gpio_num_t kLedGpio = GPIO_NUM_11; + //inline constexpr gpio_num_t kPowerButtonGpio = GPIO_NUM_12; + // 2026-9-17 ckkj add: TCA9555 INT 中断脚接主控 GPIO45, + // 按键按下/释放时 INT 拉低,下降沿触发唤醒 iot_button 状态机。 + inline constexpr gpio_num_t kTcaIntGpio = GPIO_NUM_45; + + inline constexpr gpio_num_t kAudioI2cSdaGpio = GPIO_NUM_2; + inline constexpr gpio_num_t kAudioI2cSclGpio = GPIO_NUM_1; + inline constexpr gpio_num_t kAudioI2sMclkGpio = GPIO_NUM_NC; + + inline constexpr gpio_num_t comSda = GPIO_NUM_9; // LCD_MOSI_GPIO, SD_MOSI_PIN + inline constexpr gpio_num_t comScl = GPIO_NUM_10; // LCD_SCK_GPIO + + // inline constexpr gpio_num_t kAudioI2sBclkGpio = GPIO_NUM_16; + // inline constexpr gpio_num_t kAudioI2sWordSelectGpio = GPIO_NUM_17; + // inline constexpr gpio_num_t kAudioI2sDataInGpio = GPIO_NUM_15; + // inline constexpr gpio_num_t kAudioI2sDataOutGpio = GPIO_NUM_18; + inline constexpr gpio_num_t kAudioI2sBclkGpio = GPIO_NUM_18; + inline constexpr gpio_num_t kAudioI2sWordSelectGpio = GPIO_NUM_16; + inline constexpr gpio_num_t kAudioI2sDataInGpio = GPIO_NUM_17; + inline constexpr gpio_num_t kAudioI2sDataOutGpio = GPIO_NUM_15; + + // inline constexpr gpio_num_t kAudioPowerAmplifierGpio = GPIO_NUM_40; + inline constexpr uint16_t kAudioPowerAmplifierGpio = PA_CTL; + + inline constexpr uint32_t kAudioOutputSampleRate = 48000; + inline constexpr uint32_t kAudioInputHardwareSampleRate = 48000; + inline constexpr uint32_t kAudioProtocolInputSampleRate = 16000; + + inline constexpr uint32_t kWifiRetryInitialDelayMs = 1000; + inline constexpr uint32_t kWifiRetryMaximumDelayMs = 60000; + inline constexpr uint8_t kWifiRetryMultiplier = 2; + inline constexpr uint8_t kWifiRetryJitterPercent = 20; + + inline constexpr gpio_num_t kMl307TxGpio = GPIO_NUM_43; + inline constexpr gpio_num_t kMl307RxGpio = GPIO_NUM_44; + inline constexpr uint32_t kMl307BaudRate = 115200; + inline constexpr uint32_t kWifiDisconnectFailoverMs = 30000; + inline constexpr int8_t kWifiWeakRssiDbm = -80; + inline constexpr uint8_t kWifiWeakSampleCount = 6; + // 4G physical switch sensing (see DualNetworkPolicyConfig). + inline constexpr uint8_t kModemAbsentSampleCount = 2; + inline constexpr uint32_t kModemUnavailableRepeatMs = 120000; + + inline constexpr uint16_t kButtonLongPressMs = 2000; + // iot_button's short_press_time is NOT a minimum press duration — it is the + // window after a release in which the next press still joins the same + // multi-click group. 50 ms made every human double-click resolve as two + // single clicks; 180 ms is the component default the legacy firmware ran on. + // 注意:组件同时把它当作"单次按下时长"阈值,按下超过它的释放会让组件 + // 直接结束分组并且不产生任何点击事件(四击因此被拆散/丢失)。多击分组 + // 现已由 ButtonInput 自己实现,这里只保留给组件内部状态机使用。 + inline constexpr uint16_t kButtonShortPressMs = 180; + // 多击分组窗口:一次松开后,只要在这个窗口内再次按下,就并入同一组多击。 + // 只与"松开→按下"的间隔有关,与按了多久无关,所以慢速连击也能正确识别。 + // 实测人手连击的松开→按下间隔多在 60~230ms,组间停顿多 >600ms。 + inline constexpr uint32_t kButtonMultiClickWindowMs = 320; + inline constexpr int kButtonReleaseWaitMs = 5000; + // TCA9555 KEY(P1.0) 软件去抖:iot_button 以 5ms 周期调用 get_key_level, + // 只有连续 N 次采样读到同一电平才认可一次电平变化。 + // 12 次 ≈ 60ms,用于滤掉弱上拉网络(RF/电源/I2C 串扰)上的短促低电平毛刺, + // 这类毛刺此前会被当成真实的按下-松开,产生单击/双击/三击/四击假事件。 + inline constexpr uint16_t kButtonDebounceSamples = 12; + +} // namespace borla::board_config + +namespace borla // ckkj add +{ + + constexpr uint16_t kMcuPowerExtIo = MCU_VCC_CTL; + constexpr uint16_t kPeripheralPowerExtIo = PREP_VCC_CTL; + constexpr uint16_t kPowerButtonExtIo = KEY; + // constexpr uint16_t kAudioAmpExtIo = PA_CTL; + +} \ No newline at end of file diff --git a/main/platform/borla_s3/borla_s3_platform.cc b/main/platform/borla_s3/borla_s3_platform.cc new file mode 100644 index 0000000..b62a400 --- /dev/null +++ b/main/platform/borla_s3/borla_s3_platform.cc @@ -0,0 +1,493 @@ +#include "platform/borla_s3/borla_s3_platform.h" +#include "platform/borla_s3/capacitive_touch_input.h" +#include "platform/borla_s3/board_config.h" +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace borla +{ + namespace + { + + constexpr const char *kTag = "BorlaS3Platform2"; + + bool CheckGpioResult(esp_err_t result, const char *operation) + { + if (result == ESP_OK) + { + return true; + } + ESP_LOGE(kTag, "%s failed: %s", operation, esp_err_to_name(result)); + return false; + } + ////2026-9-4 ckkj add + // ESP32-S3 深睡仅支持一个触摸通道,浅睡支持全部已配置通道。 + // 此处使用浅睡(esp_light_sleep_start)实现 IO3/IO5/IO6 三路触摸唤醒。 + // 选用运行时触摸区中的全部通道作为浅睡唤醒通道。 + // 与运行时 TouchChannelConfig::minimum_threshold_delta 一致的灵敏度下限。 + constexpr uint32_t kTouchWakeMinDelta = 80; + // 启动 FSM 后等待首轮扫描测量完成、基准收敛的时间。 + constexpr uint32_t kTouchWakeWarmupMs = 500; + + // 软关机前配置浅睡触摸唤醒通道(PAD3/PAD5/PAD6 全部使能)。 + // S3 触摸硬件按增量比较:raw - benchmark > threshold 时触发中断唤醒。 + // 运行时触摸 raw 值随触摸升高(filtered > baseline + delta), + // 因此 threshold 取 max(baseline/10, kTouchWakeMinDelta)。 + void ConfigureTouchWakeup() + { + if (touch_pad_init() != ESP_OK) + { + ESP_LOGE(kTag, "touch wakeup init failed, touch wake disabled"); + return; + } + touch_pad_config(TOUCH_PAD_NUM3); + touch_pad_config(TOUCH_PAD_NUM5); + touch_pad_config(TOUCH_PAD_NUM6); + // 与运行时 CapacitiveTouchInput 保持一致的电压配置, + // 避免默认衰减电压导致计数饱和。 + touch_pad_set_voltage( + TOUCH_HVOLT_2V7, + TOUCH_LVOLT_0V5, + TOUCH_HVOLT_ATTEN_1V); + + // 去噪配置(内部使用 PAD0 作参考通道) + touch_pad_denoise_t denoise = { + .grade = TOUCH_PAD_DENOISE_BIT4, + .cap_level = TOUCH_PAD_DENOISE_CAP_L4, + }; + touch_pad_denoise_set_config(&denoise); + touch_pad_denoise_enable(); + + // 滤波器配置,稳定基准值 + touch_filter_config_t filter_info = { + .mode = TOUCH_PAD_FILTER_IIR_16, + .debounce_cnt = 1, + .noise_thr = 0, + .jitter_step = 4, + .smh_lvl = TOUCH_PAD_SMOOTH_IIR_2, + }; + touch_pad_filter_set_config(&filter_info); + touch_pad_filter_enable(); + + touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); + touch_pad_fsm_start(); + vTaskDelay(pdMS_TO_TICKS(kTouchWakeWarmupMs)); + + // 为每个通道设置触发阈值(增量:max(baseline/10, 下限)) + for (touch_pad_t pad : kTouchPads) + { + uint32_t raw = 0; + if (touch_pad_read_raw_data(pad, &raw) != ESP_OK || + raw == 0 || raw >= 0x3FFFF0) + { + ESP_LOGW(kTag, "touch PAD%u raw invalid=%lu, skip thresh", + static_cast(pad), + static_cast(raw)); + continue; + } + const uint32_t threshold = + std::max(raw / 16, kTouchWakeMinDelta); + touch_pad_set_thresh(pad, threshold); + touch_pad_sleep_set_threshold(pad, threshold); + touch_pad_sleep_channel_enable(pad, true); + uint32_t sleep_bench = 0; + touch_pad_sleep_channel_read_benchmark(pad, &sleep_bench); + ESP_LOGI(kTag, "touch wakeup PAD%u baseline=%lu delta_th=%lu sleep_bench=%lu", + static_cast(pad), + static_cast(raw), + static_cast(threshold), + static_cast(sleep_bench)); + } + touch_pad_sleep_channel_reset_benchmark(); + } ///////ckkj add end + } // namespace + BorlaS3Platform::BorlaS3Platform(TCA9555 &tca9555) + : tca9555_(tca9555) + { + } + BorlaS3Platform::~BorlaS3Platform() + { + if (alert_timer_ != nullptr) + { + esp_timer_stop(alert_timer_); + esp_timer_delete(alert_timer_); + } + } + + bool BorlaS3Platform::Initialize() + { + // if (!InitializePowerRails() || !LoadIdentity() || + // !led_.Initialize(board_config::kLedGpio)) { + if (!InitializePowerRails() || !LoadIdentity()) + { + ESP_LOGE(kTag, "platform initialization failed"); + return false; + } + + const esp_timer_create_args_t timer_args = { + .callback = &BorlaS3Platform::AlertTimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "led_alert2", + .skip_unhandled_events = true, + }; + if (esp_timer_create(&timer_args, &alert_timer_) != ESP_OK) + { + ESP_LOGE(kTag, "temporary LED alert timer creation failed"); + return false; + } + //2026-9-8 ckkj add 省电模式配置 + esp_pm_config_t pm_config = {}; + pm_config.max_freq_mhz = 240; + pm_config.min_freq_mhz = 10; + pm_config.light_sleep_enable = false; + const esp_err_t pm_result = esp_pm_configure(&pm_config); + if (pm_result != ESP_OK) { + ESP_LOGW(kTag, "esp_pm_configure failed: %s (enable CONFIG_PM_ENABLE)", + esp_err_to_name(pm_result)); + } else { + ESP_LOGI(kTag, "power management enabled dfs=240/10MHz auto_light_sleep=false"); + } + ////// + initialized_ = true; + ESP_LOGI(kTag, "platform initialized board=%s mac=%s version=%s chip=%s", + identity_.board, identity_.mac, identity_.app_version, + identity_.chip_model); + return true; + } + + void BorlaS3Platform::SetLed(LedPattern pattern) + { + if (!initialized_) + { + ESP_LOGW(kTag, "LED request ignored before platform initialization"); + return; + } + std::lock_guard lock(led_state_mutex_); + desired_led_pattern_ = pattern; + if (!temporary_alert_active_) + { + led_.SetPattern(pattern); + } + } + + void BorlaS3Platform::ShowTemporaryLedAlert(uint32_t duration_ms) + { + if (!initialized_ || alert_timer_ == nullptr) + { + ESP_LOGW(kTag, "temporary LED alert ignored before initialization"); + return; + } + duration_ms = std::max( + 100, std::min(duration_ms, 60000)); + std::lock_guard lock(led_state_mutex_); + const esp_err_t stop = esp_timer_stop(alert_timer_); + if (stop != ESP_OK && stop != ESP_ERR_INVALID_STATE) + { + ESP_LOGW(kTag, "temporary LED timer stop failed: %s", + esp_err_to_name(stop)); + } + temporary_alert_active_ = true; + led_.SetPattern(LedPattern::kError); + const esp_err_t start = esp_timer_start_once( + alert_timer_, static_cast(duration_ms) * 1000ULL); + if (start != ESP_OK) + { + temporary_alert_active_ = false; + led_.SetPattern(desired_led_pattern_); + ESP_LOGE(kTag, "temporary LED timer start failed: %s", + esp_err_to_name(start)); + } + } + + void BorlaS3Platform::ReportError(uint32_t error_id) + { + ESP_LOGE(kTag, "platform error id=%lu", + static_cast(error_id)); + if (initialized_) + { + SetLed(LedPattern::kError); + } + } + + void BorlaS3Platform::Reboot() + { + ESP_LOGW(kTag, "reboot requested"); + vTaskDelay(pdMS_TO_TICKS(100)); + esp_restart(); + } + + void BorlaS3Platform::EnterSoftOff(uint64_t timer_wakeup_us) + { + if (initialized_) + { + std::lock_guard lock(led_state_mutex_); + temporary_alert_active_ = false; + desired_led_pattern_ = LedPattern::kOff; + if (alert_timer_ != nullptr) + { + esp_timer_stop(alert_timer_); + } + led_.SetPattern(LedPattern::kOff); + } + int waited_ms = 0; + // while (gpio_get_level(board_config::kPowerButtonGpio) == 1 && + // waited_ms < board_config::kButtonReleaseWaitMs) { + while (waited_ms < board_config::kButtonReleaseWaitMs) + { + uint8_t p1 = 0xFF; + const esp_err_t r = tca9555_.read_p1_input(&p1); + const bool still_pressed = (r == ESP_OK) && ((p1 & (1U << TCA_P1_KEY)) == 0); + if (!still_pressed) + { + break; + } // 2028-9-4 ckkj mod + vTaskDelay(pdMS_TO_TICKS(20)); + waited_ms += 20; + } + if (waited_ms >= board_config::kButtonReleaseWaitMs) + { + ESP_LOGW(kTag, "TCA9555 P1.0 KEY remained pressed after %d ms, proceeding", + waited_ms); + } + // 2026-8-26 ckkj add + // tca9555_.clr_pin(MCU_VCC_CTL); + tca9555_.clr_pin(EN_4G); + tca9555_.clr_pin(PA_CTL); + tca9555_.clr_pin(PREP_VCC_CTL); + tca9555_.clr_pin(V5_EN); + + tca9555_.clr_pin(SC_LEDA); + tca9555_.clr_pin(OV_FLASH); + tca9555_.set_pin(OV_PWDN); + tca9555_.clr_pin(SC_LEDA); + // end + esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL); + // esp_err_t result = gpio_wakeup_enable( + // board_config::kPowerButtonGpio, GPIO_INTR_HIGH_LEVEL); + // if (result == ESP_OK) { + // result = esp_sleep_enable_gpio_wakeup(); + // } + // 配置触摸唤醒引脚 (IO3=PAD3, IO5=PAD5, IO6=PAD6) + ConfigureTouchWakeup(); + // touch_pad_fsm_stop(); + // touch_pad_deinit(); + // touch_pad_init(); + // touch_pad_config(TOUCH_PAD_NUM3); + // touch_pad_config(TOUCH_PAD_NUM5); + // touch_pad_config(TOUCH_PAD_NUM6); + + esp_err_t result = esp_sleep_enable_touchpad_wakeup(); // 配置触摸唤醒引脚 (IO3=PAD3, IO5=PAD5, IO6=PAD6) + if (result != ESP_OK) + { + ESP_LOGE(kTag, "touch wake configuration failed: %s", + esp_err_to_name(result)); + // esp_restart(); + } + //2026-9-8 ckkj add 配置按键唤醒引脚 + // GPIO45 (TCA9555 INT) 作为按键唤醒源:TCA9555 开漏输出, + // 按键按下时 INT 拉低,配置为低电平触发唤醒。 + // 与触摸唤醒在浅睡眠中可共存(EXT0/EXT1 才与触摸互斥)。 + // esp_err_t gpio_wake = gpio_wakeup_enable( + // board_config::kTcaIntGpio, GPIO_INTR_LOW_LEVEL); + // if (gpio_wake != ESP_OK) + // { + // ESP_LOGW(kTag, "GPIO45 wakeup enable failed: %s", + // esp_err_to_name(gpio_wake)); + // } + // gpio_wake = esp_sleep_enable_gpio_wakeup(); + // if (gpio_wake != ESP_OK) + // { + // ESP_LOGW(kTag, "esp_sleep_enable_gpio_wakeup failed: %s", + // esp_err_to_name(gpio_wake)); + // } + ///////// + if (timer_wakeup_us > 0) + { + result = esp_sleep_enable_timer_wakeup(timer_wakeup_us); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "timer wake configuration failed: %s", + esp_err_to_name(result)); + } + } + //esp_sleep_enable_timer_wakeup(3*60*1000000ULL); + + // ESP_LOGI(kTag, "entering final light sleep timer_us=%llu", + esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); + esp_sleep_pd_config(ESP_PD_DOMAIN_RC_FAST, ESP_PD_OPTION_ON); + esp_sleep_pd_config(ESP_PD_DOMAIN_XTAL, ESP_PD_OPTION_OFF); + ESP_LOGI(kTag, "entering light sleep timer_us=%llu",static_cast(timer_wakeup_us)); + + const esp_err_t sleep_result = esp_light_sleep_start(); + const esp_sleep_wakeup_cause_t cause =esp_sleep_get_wakeup_cause(); + + RTC_DATA_ATTR static esp_sleep_wakeup_cause_t g_rtc_wake_cause; + // 在esp_light_sleep_start()返回后,restart之前: + g_rtc_wake_cause = esp_sleep_get_wakeup_cause(); + // 重启后ConsumeSoftOffWakeReason读取g_rtc_wake_cause + + ESP_LOGI(kTag, "light sleep returned result=%s cause=%d",esp_err_to_name(sleep_result), static_cast(cause)); + // 浅睡唤醒后重启,复用深睡的唤醒原因处理流程 + esp_restart(); + } + + void BorlaS3Platform::AlertTimerCallback(void *context) + { + static_cast(context)->OnAlertTimer(); + } + + void BorlaS3Platform::OnAlertTimer() + { + std::lock_guard lock(led_state_mutex_); + temporary_alert_active_ = false; + if (initialized_) + { + led_.SetPattern(desired_led_pattern_); + } + } + + SoftOffWakeReason BorlaS3Platform::ConsumeSoftOffWakeReason() + { // 2026-8-26 ckkj + // const auto reason = + // static_cast(g_soft_off_wake_reason); + // g_soft_off_wake_reason = + // static_cast(SoftOffWakeReason::kNone); + // return reason; + const esp_sleep_wakeup_cause_t cause = + esp_sleep_get_wakeup_cause(); + ESP_LOGI(kTag, "wakeup cause=%d", static_cast(cause)); + switch (cause) + { + case ESP_SLEEP_WAKEUP_TOUCHPAD: + case ESP_SLEEP_WAKEUP_EXT0: + case ESP_SLEEP_WAKEUP_EXT1: + return SoftOffWakeReason::kButton; + case ESP_SLEEP_WAKEUP_TIMER: + return SoftOffWakeReason::kTimer; + default: + return SoftOffWakeReason::kNone; + } + } + // 2026-8-26 ckkj + bool BorlaS3Platform::ReadWakeButton() + { + uint8_t val = 0; + esp_err_t ret = tca9555_.read_p1_input(&val); + if (ret != ESP_OK) + { + ESP_LOGW(kTag, "read P1 input failed: %s", + esp_err_to_name(ret)); + return false; + } + return (val & 0x01) == 0; + } + bool BorlaS3Platform::InitializePowerRails() + { + // gpio_config_t config = {}; + // config.pin_bit_mask = + // (1ULL << board_config::kMcuPowerGpio) | + // (1ULL << board_config::kPeripheralPowerGpio); + // config.mode = GPIO_MODE_OUTPUT; + // config.pull_up_en = GPIO_PULLUP_DISABLE; + // config.pull_down_en = GPIO_PULLDOWN_DISABLE; + // config.intr_type = GPIO_INTR_DISABLE; + + // if (!CheckGpioResult(gpio_config(&config), "configure power GPIOs")) { + // return false; + // } + + bool valid = true; + valid &= CheckGpioResult( + // gpio_set_level(board_config::kMcuPowerGpio, 1), + tca9555_.set_pin(kMcuPowerExtIo), + "preload MCU power (TCA9555)"); + valid &= CheckGpioResult( + // gpio_set_level(board_config::kPeripheralPowerGpio, 1), + tca9555_.set_pin(kPeripheralPowerExtIo), "preload peripheral power (TCA9555)"); + //valid &= CheckGpioResult(tca9555_.set_pin(V5_EN), "enable 5V boost (TCA9555)"); + vTaskDelay(pdMS_TO_TICKS(300)); + // valid &= CheckGpioResult( + // //gpio_hold_dis(board_config::kMcuPowerGpio), + // "release MCU power GPIO hold"); + // valid &= CheckGpioResult( + // //gpio_hold_dis(board_config::kPeripheralPowerGpio), + // "release peripheral power GPIO hold"); + // valid &= CheckGpioResult( + // //gpio_set_level(board_config::kMcuPowerGpio, 1), + // "enable MCU power rail"); + // valid &= CheckGpioResult( + // //gpio_set_level(board_config::kPeripheralPowerGpio, 1), + // "enable peripheral power rail"); + // valid &= CheckGpioResult( + // //gpio_hold_en(board_config::kMcuPowerGpio), + // "hold MCU power GPIO"); + // valid &= CheckGpioResult( + // //gpio_hold_en(board_config::kPeripheralPowerGpio), + // "hold peripheral power GPIO"); + + if (valid) + { + ESP_LOGI(kTag, "power rails enabled via TCA9555"); + } + return valid; + } + + bool BorlaS3Platform::LoadIdentity() + { + std::snprintf(identity_.board, sizeof(identity_.board), "%s", + board_config::kBoardName); + + uint8_t mac[6] = {}; + const esp_err_t mac_result = esp_read_mac(mac, ESP_MAC_WIFI_STA); + if (mac_result != ESP_OK) + { + ESP_LOGE(kTag, "failed to read station MAC: %s", + esp_err_to_name(mac_result)); + return false; + } + // Lower case, and it has to stay that way. This string is the device_id the + // server keys its live connection map with, verbatim and unnormalised + // (websocket_server.py `self._connections[device_id]`). The backend, on the + // other hand, lower-cases the MAC before POSTing to + // /internal/devices/{mac}/control — which is how an admin activation, a + // deactivation or a volume change reaches an online device. + // + // The previous firmware formatted with %02x (system_info.cc), so those two + // always met. Emitting %02X here registered the connection under + // "58:E6:C5:..." while every control call looked up "58:e6:c5:...", so the + // server answered 404 "device not connected" and silently dropped the + // command. Visible symptom: a device that has just been activated keeps + // reading out its activation code forever, because the welcome prompt that + // ends that loop is delivered through exactly this path. + std::snprintf(identity_.mac, sizeof(identity_.mac), + "%02x:%02x:%02x:%02x:%02x:%02x", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + + const esp_app_desc_t *app = esp_app_get_description(); + std::snprintf(identity_.app_version, sizeof(identity_.app_version), "%s", + app == nullptr ? "unknown" : app->version); + + esp_chip_info_t chip = {}; + esp_chip_info(&chip); + std::snprintf(identity_.chip_model, sizeof(identity_.chip_model), + "%s-rev%d", CONFIG_IDF_TARGET, chip.revision); + return true; + } + +} // namespace borla \ No newline at end of file diff --git a/main/platform/borla_s3/borla_s3_platform.h b/main/platform/borla_s3/borla_s3_platform.h new file mode 100644 index 0000000..cf44576 --- /dev/null +++ b/main/platform/borla_s3/borla_s3_platform.h @@ -0,0 +1,45 @@ +#pragma once + +#include "platform/borla_s3/ws2812_led.h" +#include "ports/device_platform.h" +#include "platform/borla_s3/tca9555.h" +#include + +#include + +namespace borla { + +class BorlaS3Platform final : public IDevicePlatform { +public: + explicit BorlaS3Platform(TCA9555& tca9555); + ~BorlaS3Platform(); + + bool Initialize() override; + const DeviceIdentity& Identity() const override { return identity_; } + void SetLed(LedPattern pattern) override; + void ShowTemporaryLedAlert(uint32_t duration_ms) override; + void ReportError(uint32_t error_id) override; + void Reboot() override; + void EnterSoftOff(uint64_t timer_wakeup_us) override; + SoftOffWakeReason ConsumeSoftOffWakeReason() override; + //2026-8-26 ckkj add + bool ReadWakeButton() override; + +private: + static void AlertTimerCallback(void* context); + void OnAlertTimer(); + bool InitializePowerRails(); + bool LoadIdentity(); + + TCA9555& tca9555_; + + DeviceIdentity identity_{}; + Ws2812Led led_; + std::mutex led_state_mutex_; + esp_timer_handle_t alert_timer_ = nullptr; + LedPattern desired_led_pattern_ = LedPattern::kOff; + bool temporary_alert_active_ = false; + bool initialized_ = false; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/button_input.cc b/main/platform/borla_s3/button_input.cc new file mode 100644 index 0000000..c4e7098 --- /dev/null +++ b/main/platform/borla_s3/button_input.cc @@ -0,0 +1,385 @@ +#include "platform/borla_s3/button_input.h" + +#include "platform/borla_s3/board_config.h" + +// #include +// #include +// #include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "ButtonInput2"; + +// KEY(P1.0) 电平语义:扩展芯片内部上拉,松开=高,按下被拉到低(低有效)。 +// iot_button 的 get_key_level 要求返回 1 表示"按下"。 +constexpr uint8_t kKeyPressed = 1; +constexpr uint8_t kKeyReleased = 0; + +// I2C 连续读失败达到该次数才认为按键已松开,避免一次总线抖动被当成"松开沿"。 +constexpr uint32_t kKeyReadFailLimit = 20; + +// 初始化阶段等待按键松开:采样间隔与确认松开所需连续采样次数。 +constexpr uint32_t kReleaseSampleIntervalMs = 20; +constexpr uint8_t kReleaseConfirmSamples = 2; + +bool RegisterButtonCallback( + button_handle_t button, + button_event_t event, + button_event_args_t* args, + button_cb_t callback, + void* context) +{ + const esp_err_t result = + iot_button_register_cb(button, event, args, callback, context); + if (result == ESP_OK) { + return true; + } + ESP_LOGE(kTag, "failed to register button event=%d: %s", + static_cast(event), esp_err_to_name(result)); + return false; +} + +} // namespace + +ButtonInput::ButtonInput( + IEventPublisher& publisher, + //const IRemoteBehaviorConfig& behavior_config) + const IRemoteBehaviorConfig& behavior_config,TCA9555& tca9555) + : publisher_(publisher),behavior_config_(behavior_config),tca9555_(tca9555) + +{ +} + +ButtonInput::~ButtonInput() +{ + if (button_ != nullptr) { + iot_button_delete(button_); + } +} + +/*bool ButtonInput::Initialize() +{ + gpio_hold_dis(board_config::kPowerButtonGpio); + rtc_gpio_hold_dis(board_config::kPowerButtonGpio); + rtc_gpio_deinit(board_config::kPowerButtonGpio); + + gpio_config_t input_config = {}; + input_config.pin_bit_mask = 1ULL << board_config::kPowerButtonGpio; + input_config.mode = GPIO_MODE_INPUT; + // input_config.pull_up_en = GPIO_PULLUP_DISABLE; + // input_config.pull_down_en = GPIO_PULLDOWN_ENABLE;//2026-7-29 ckkj debug + input_config.pull_up_en = GPIO_PULLUP_ENABLE; + input_config.pull_down_en = GPIO_PULLDOWN_DISABLE; + input_config.intr_type = GPIO_INTR_DISABLE; + esp_err_t result = gpio_config(&input_config); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to configure GPIO%d: %s", + static_cast(board_config::kPowerButtonGpio), + esp_err_to_name(result)); + return false; + } + + int waited_ms = 0; + while (gpio_get_level(board_config::kPowerButtonGpio) == 1 && + waited_ms < board_config::kButtonReleaseWaitMs) { + vTaskDelay(pdMS_TO_TICKS(20)); + waited_ms += 20; + } + if (gpio_get_level(board_config::kPowerButtonGpio) == 1) { + ESP_LOGW(kTag, "power button remained pressed after %d ms", + waited_ms); + } + + const button_config_t button_config = { + .long_press_time = board_config::kButtonLongPressMs, + .short_press_time = board_config::kButtonShortPressMs, + }; + const button_gpio_config_t gpio_config = { + .gpio_num = board_config::kPowerButtonGpio, + //.active_level = 1,//2026-7-29 ckkj debug + .active_level = 0, + .enable_power_save = false, + .disable_pull = false, + }; + result = + iot_button_new_gpio_device(&button_config, &gpio_config, &button_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to create GPIO button: %s", + esp_err_to_name(result)); + return false; + } + + if (!RegisterCallbacks()) { + iot_button_delete(button_); + button_ = nullptr; + return false; + } + + ESP_LOGI(kTag, "power button initialized on GPIO%d", + static_cast(board_config::kPowerButtonGpio)); + return true; +}*/ + +uint8_t ButtonInput::TcaGetKeyLevel(button_driver_t* driver) +{ + if (driver == nullptr) { + return kKeyReleased; + } + auto* ctx = reinterpret_cast(driver); + if (ctx->tca == nullptr) { + return kKeyReleased; + } + + uint8_t port1 = 0xFF; + if (ctx->tca->read_p1_input(&port1) != ESP_OK) { + // 读失败不能当成"松开":一次 I2C 抖动就会制造一个假的释放沿, + // 让 iot_button 把一次真实长按拆成多个点击。保持上一次去抖结果, + // 只有连续失败足够多才退回"未按下"。 + if (++ctx->read_fail_count >= kKeyReadFailLimit) { + ctx->read_fail_count = 0; + ctx->same_count = 0; + ctx->stable_level = kKeyReleased; + ESP_LOGW(kTag, "P1.0 read failed %u times, treat as released", + static_cast(kKeyReadFailLimit)); + } + } else { + ctx->read_fail_count = 0; + + // 按下 = P1.0 为低(KEY 内部上拉,按下被拉到低),松开 = 高。 + const uint8_t raw_pressed = + ((port1 & (1U << TCA_P1_KEY)) == 0U) ? kKeyPressed : kKeyReleased; + const uint32_t now_ms = pdTICKS_TO_MS(xTaskGetTickCount()); + + if (raw_pressed == ctx->stable_level) { + // 与当前稳定电平一致,清空突变计数 + ctx->same_count = 0; + } else if (++ctx->same_count >= board_config::kButtonDebounceSamples) { + // 关键:必须是"连续"多次读到新电平才确认变化。 + // 这样交替抖动的噪声(高-低-高-低)永远累积不到阈值。 + ctx->same_count = 0; + ctx->stable_level = raw_pressed; + if (raw_pressed == kKeyPressed) { + ctx->press_start_ms = now_ms; + ESP_LOGI(kTag, "P1.0 pressed (port1=0x%02x)", port1); + } else { + ctx->last_press_ms = now_ms - ctx->press_start_ms; + ESP_LOGI(kTag, "P1.0 released (held=%lums)", + static_cast(ctx->last_press_ms)); + } + } + } + + // 多击分组收尾:只有在"松开"状态且超过分组窗口后才发布。 + // 按下期间窗口不生效,因此按得慢的一击不会把整组多击拆散。 + if (ctx->owner != nullptr) { + ctx->owner->CloseClickGroupIfIdle( + ctx->stable_level, pdTICKS_TO_MS(xTaskGetTickCount())); + } + return ctx->stable_level; +} + +esp_err_t ButtonInput::TcaDelDriver(button_driver_t* driver) +{ + // driver 嵌在 ButtonInput 对象里,不需要单独释放 + (void)driver; + return ESP_OK; +} +bool ButtonInput::ReadTcaButtonRaw(bool* pressed) +{ + uint8_t port1 = 0xFF; + if (tca9555_.read_p1_input(&port1) != ESP_OK) { + return false; + } + // 与 TcaGetKeyLevel 保持同一极性:KEY 内部上拉,低电平=按下。 + // (之前这里是 != 0,即把"空闲高电平"当成按下,导致启动时白等 5 秒 + // 并打印 "power button remained pressed" 的误报警告。) + *pressed = (port1 & (1U << TCA_P1_KEY)) == 0U; + return true; +} + +bool ButtonInput::WaitTcaButtonReleased(uint32_t timeout_ms) +{ + uint32_t waited_ms = 0; + uint8_t released_samples = 0; + while (waited_ms < timeout_ms) { + bool pressed = false; + if (!ReadTcaButtonRaw(&pressed)) { + // I2C 读失败:不能当成"松开",保持等待并继续采样 + released_samples = 0; + } else if (!pressed) { + // 连续多次读到松开才退出,避免毛刺让这里提前返回 + if (++released_samples >= kReleaseConfirmSamples) { + return true; + } + } else { + released_samples = 0; + } + vTaskDelay(pdMS_TO_TICKS(kReleaseSampleIntervalMs)); + waited_ms += kReleaseSampleIntervalMs; + } + return false; +} + +bool ButtonInput::Initialize() +{ + bool pressed = false; + if (!ReadTcaButtonRaw(&pressed)) { + ESP_LOGE(kTag, "failed to read TCA9555 P1.0 during button init"); + return false; + } + + if (!WaitTcaButtonReleased(board_config::kButtonReleaseWaitMs)) { + ESP_LOGW(kTag, "power button remained pressed after %d ms",board_config::kButtonReleaseWaitMs); + } + + // 初始化自定义 driver 上下文(嵌入在本对象内,生命周期一致) + driver_ctx_.tca = &tca9555_; + driver_ctx_.owner = this; + driver_ctx_.base.enable_power_save = false; + driver_ctx_.base.get_key_level = &ButtonInput::TcaGetKeyLevel; + driver_ctx_.base.enter_power_save = nullptr; + driver_ctx_.base.del = &ButtonInput::TcaDelDriver; + // 用当前真实电平作为去抖初值,避免开机瞬间凭空多出一个按下沿 + if (ReadTcaButtonRaw(&pressed)) { + driver_ctx_.stable_level = pressed ? kKeyPressed : kKeyReleased; + } + driver_ctx_.same_count = 0; + driver_ctx_.read_fail_count = 0; + + const button_config_t button_config = { + .long_press_time = board_config::kButtonLongPressMs, + .short_press_time = board_config::kButtonShortPressMs, + }; + const esp_err_t result = iot_button_create(&button_config, &driver_ctx_.base, &button_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to create TCA9555 custom button: %s",esp_err_to_name(result)); + return false; + } + + if (!RegisterCallbacks()) { + iot_button_delete(button_); + button_ = nullptr; + return false; + } + + ESP_LOGI(kTag, "power button initialized on TCA9555 P1.0 (bit=%u, active low, debounce=%u samples)", + static_cast(TCA_P1_KEY), + static_cast(board_config::kButtonDebounceSamples)); + return true; +}//////2026-9-4 ckkj add + +// 边沿事件(iot_button 的按下/松开事件每次物理边沿都会回调一次, +// 与组件内部的多击分组无关)——这里只记录时间戳,点击次数自己归组。 +void ButtonInput::OnPressDown(void*, void* context) +{ + auto* self = static_cast(context); + self->press_down_ms_ = pdTICKS_TO_MS(xTaskGetTickCount()); +} + +void ButtonInput::OnPressUp(void*, void* context) +{ + auto* self = static_cast(context); + const uint32_t now_ms = pdTICKS_TO_MS(xTaskGetTickCount()); + const uint32_t held_ms = now_ms - self->press_down_ms_; + + // 长按由 BUTTON_LONG_PRESS_START 处理,不计入多击分组。 + // 注意判据是"本次按了多久",与分组窗口无关。 + if (held_ms >= board_config::kButtonLongPressMs) { + ESP_LOGD(kTag, "press released after %lums, treated as long press", + static_cast(held_ms)); + return; + } + + if (self->click_count_ < 0xFFU) { + ++self->click_count_; + } + self->last_release_ms_ = now_ms; + self->click_group_open_ = true; + ESP_LOGD(kTag, "click %u in group (held=%lums)", + static_cast(self->click_count_), + static_cast(held_ms)); +} + +// 松开并保持 kButtonMultiClickWindowMs 之后才发布整组点击次数。 +// 由 TcaGetKeyLevel 每 5ms 驱动一次,避免额外定时器。 +void ButtonInput::CloseClickGroupIfIdle(uint8_t stable_level, uint32_t now_ms) +{ + if (!click_group_open_ || stable_level != kKeyReleased) { + // 还在按下(或已经发布过)时不收尾:连击间隔再长也会并入同一组 + return; + } + if ((now_ms - last_release_ms_) < board_config::kButtonMultiClickWindowMs) { + return; + } + + click_group_open_ = false; + const uint8_t count = click_count_; + click_count_ = 0; + PublishClick(static_cast(count)); +} + +void ButtonInput::OnLongPress(void*, void* context) +{ + static_cast(context)->PublishLongPress(); +} + +void ButtonInput::PublishClick(int32_t count) +{ + static uint64_t last_click_ts = 0; + uint32_t now = pdTICKS_TO_MS(xTaskGetTickCount()); + // 两次click间隔小于120ms,判定为噪声虚假事件,直接丢弃 + if((now - last_click_ts) < 120U) + { + ESP_LOGW(kTag,"filter spurious click count=%ld",count); + return; + } + last_click_ts = now; + + ESP_LOGI(kTag, "button clicked count=%ld", static_cast(count)); + const ButtonAction action = + behavior_config_.ResolveButtonAction( + static_cast(count)); + if (!publisher_.Publish( + AppEvent::Make( + AppEventType::kButtonClicked, + 0, + count, + static_cast(action)))) { + ESP_LOGE(kTag, "failed to publish button click count=%ld", + static_cast(count)); + } +} + +void ButtonInput::PublishLongPress() +{ + ESP_LOGI(kTag, "button long-pressed"); + if (!publisher_.Publish( + AppEvent::Make(AppEventType::kButtonLongPressed))) { + ESP_LOGE(kTag, "failed to publish long press"); + } +} + +bool ButtonInput::RegisterCallbacks() +{ + // 只注册边沿事件和长按:点击次数由 OnPressUp + CloseClickGroupIfIdle 归组, + // 不再使用 iot_button 的 SINGLE/DOUBLE/MULTIPLE_CLICK(其内置分组会把 + // 按下超过 short_press_time 的那一击当成分组结束并丢弃整组点击)。 + bool valid = true; + valid &= RegisterButtonCallback( + button_, BUTTON_PRESS_DOWN, nullptr, &ButtonInput::OnPressDown, + this); + valid &= RegisterButtonCallback( + button_, BUTTON_PRESS_UP, nullptr, &ButtonInput::OnPressUp, + this); + valid &= RegisterButtonCallback( + button_, BUTTON_LONG_PRESS_START, nullptr, &ButtonInput::OnLongPress, + this); + return valid; +} + +} // namespace borla diff --git a/main/platform/borla_s3/button_input.h b/main/platform/borla_s3/button_input.h new file mode 100644 index 0000000..d9c8061 --- /dev/null +++ b/main/platform/borla_s3/button_input.h @@ -0,0 +1,66 @@ +#pragma once + +#include "ports/event_publisher.h" +#include "ports/remote_behavior_config.h" +#include "platform/borla_s3/tca9555.h" + +#include +#include +#include + +namespace borla { + +class ButtonInput final { +public: + ButtonInput( + IEventPublisher& publisher, + //const IRemoteBehaviorConfig& behavior_config);//2026-9-4 ckkj mod + const IRemoteBehaviorConfig& behavior_config,TCA9555& tca9555); + ~ButtonInput(); + + bool Initialize(); + +private: + struct TcaButtonCtx { + button_driver_t base{}; + TCA9555* tca = nullptr; + ButtonInput* owner = nullptr; // 用于在轮询回调里收尾多击分组 + // KEY(P1.0) 去抖状态:get_key_level 由 iot_button 定时器每 5ms 调一次, + // 只有连续 kButtonDebounceSamples 次读到同一电平才认可电平变化。 + uint8_t stable_level = 0; // 去抖后的电平:1=按下,0=松开 + uint16_t same_count = 0; // 与 stable_level 不同的连续采样次数 + uint32_t read_fail_count = 0; // 连续 I2C 读失败次数 + uint32_t press_start_ms = 0; // 本次按下(去抖确认后)的时间戳 + uint32_t last_press_ms = 0; // 最近一次按下的持续时间,用于诊断 + }; + static uint8_t TcaGetKeyLevel(button_driver_t* driver); + static esp_err_t TcaDelDriver(button_driver_t* driver); + bool ReadTcaButtonRaw(bool* pressed); + bool WaitTcaButtonReleased(uint32_t timeout_ms); + + TcaButtonCtx driver_ctx_{};//2026-9-4 ckkj add + + // 多击分组:iot_button 的内置分组会把"按下超过 short_press_time 的那一击" + // 当成分组结束并丢弃整组点击(四击因此被拆成多次单击),所以这里只使用 + // 组件的边沿事件(按下/松开/长按),点击数由自己按"松开→按下"间隔归组。 + static void OnPressDown(void* handle, void* context); + static void OnPressUp(void* handle, void* context); + static void OnLongPress(void* handle, void* context); + // 松开且超过分组窗口后,发布当前分组的点击次数(由 get_key_level 每 5ms 驱动) + void CloseClickGroupIfIdle(uint8_t stable_level, uint32_t now_ms); + + void PublishClick(int32_t count); + void PublishLongPress(); + bool RegisterCallbacks(); + + IEventPublisher& publisher_; + const IRemoteBehaviorConfig& behavior_config_; + TCA9555& tca9555_; + button_handle_t button_ = nullptr; + uint32_t press_down_ms_ = 0; // 最近一次按下的时间戳 + uint32_t last_release_ms_ = 0; // 最近一次松开的时间戳(分组窗口起点) + uint8_t click_count_ = 0; // 当前分组内累计的点击数 + bool click_group_open_ = false; // 是否还有未发布的多击分组 +}; + +} // namespace borla diff --git a/main/platform/borla_s3/capacitive_touch_input.cc b/main/platform/borla_s3/capacitive_touch_input.cc new file mode 100644 index 0000000..df93bcf --- /dev/null +++ b/main/platform/borla_s3/capacitive_touch_input.cc @@ -0,0 +1,81 @@ +#include "platform/borla_s3/capacitive_touch_input.h" + +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "BorlaTouch2"; +// constexpr std::array kTouchPads{{ +// TOUCH_PAD_NUM3, +// TOUCH_PAD_NUM9, +// TOUCH_PAD_NUM13, +// TOUCH_PAD_NUM7, +// TOUCH_PAD_NUM8, +// }};//2026-9-4 ckkj mod + +} // namespace + +CapacitiveTouchInput::~CapacitiveTouchInput() +{ + if (initialized_) { + touch_pad_fsm_stop(); + touch_pad_deinit(); + } +} + +bool CapacitiveTouchInput::Initialize() +{ + if (initialized_) { + return true; + } + esp_err_t result = touch_pad_init(); + if (result == ESP_OK) { + result = touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); + } + if (result == ESP_OK) { + result = touch_pad_set_voltage( + TOUCH_HVOLT_2V7, + TOUCH_LVOLT_0V5, + TOUCH_HVOLT_ATTEN_1V); + } + for (touch_pad_t pad : kTouchPads) { + if (result == ESP_OK) { + result = touch_pad_config(pad); + } + } + if (result == ESP_OK) { + result = touch_pad_fsm_start(); + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "initialization failed: %s", + esp_err_to_name(result)); + //touch_pad_deinit(); + return false; + } + initialized_ = true; + ESP_LOGI(kTag, "three touch channels initialized"); + return true; +} + +bool CapacitiveTouchInput::Read(size_t channel, uint32_t* raw) +{ + if (!initialized_ || raw == nullptr || + channel >= kTouchPads.size()) { + return false; + } + const esp_err_t result =touch_pad_read_raw_data(kTouchPads[channel], raw); + if (result != ESP_OK) { + ESP_LOGW(kTag, "read failed channel=%u: %s", + static_cast(channel), + esp_err_to_name(result)); + return false; + } + return true; +} + +} // namespace borla diff --git a/main/platform/borla_s3/capacitive_touch_input.h b/main/platform/borla_s3/capacitive_touch_input.h new file mode 100644 index 0000000..3c04d31 --- /dev/null +++ b/main/platform/borla_s3/capacitive_touch_input.h @@ -0,0 +1,28 @@ +#pragma once + +#include "sensor/sensor_types.h" +#include +#include +#include +#include +namespace borla { +// 运行时三路触摸区通道;软关机的深睡触摸唤醒也复用同一组通道。 +inline constexpr std::array + kTouchPads{{ + TOUCH_PAD_NUM3, + TOUCH_PAD_NUM5, + TOUCH_PAD_NUM6, + }}; +class CapacitiveTouchInput final { +public: + CapacitiveTouchInput() = default; + ~CapacitiveTouchInput(); + + bool Initialize(); + bool Read(size_t channel, uint32_t* raw); + +private: + bool initialized_ = false; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/es8311_audio_output.cc b/main/platform/borla_s3/es8311_audio_output.cc new file mode 100644 index 0000000..a60996e --- /dev/null +++ b/main/platform/borla_s3/es8311_audio_output.cc @@ -0,0 +1,573 @@ +#include "platform/borla_s3/es8311_audio_output.h" + +#include "audio/playback_pipeline.h" +#include "diagnostics/audio_tap.h" +#include "platform/borla_s3/board_config.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace borla +{ + namespace + { + + // constexpr const char* kTag = "Es8311Output2"; + constexpr const char *kTag = "Es8389Output2"; + constexpr const char *kVolumeNamespace = "audio"; + constexpr const char *kVolumeKey = "output_volume"; + // constexpr uint8_t kEs8311Address = ES8311_CODEC_DEFAULT_ADDR; + constexpr uint8_t kEs8389Address = ES8389_CODEC_DEFAULT_ADDR; + + } // namespace + + // Es8311AudioOutput::Es8311AudioOutput(BorlaS3I2cBus& i2c_bus) + // : i2c_bus_(i2c_bus) + // { + // } + Es8311AudioOutput::Es8311AudioOutput(BorlaS3I2cBus &i2c_bus, TCA9555 &tca9555) + : i2c_bus_(i2c_bus), + tca9555_(tca9555) {} + Es8311AudioOutput::~Es8311AudioOutput() + { + Shutdown(); + if (scaled_buffer_ != nullptr) + { + heap_caps_free(scaled_buffer_); + } + } + + bool Es8311AudioOutput::Initialize() + { + std::lock_guard lock(mutex_); + if (initialized_) + { + return true; + } + if (!i2c_bus_.Initialize() || !InitializeI2s() || + !InitializeCodec()) + { + DestroyCodec(); + return false; + } + + scaled_buffer_samples_ = PlaybackPipeline::kSamplesPerFrame; + if (scaled_buffer_ == nullptr) + { + scaled_buffer_ = static_cast(heap_caps_calloc( + scaled_buffer_samples_ * 2, // + sizeof(int16_t), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + } + if (scaled_buffer_ == nullptr) + { + ESP_LOGE(kTag, "failed to allocate PSRAM volume buffer"); + DestroyCodec(); + return false; + } + + // gpio_set_direction(board_config::kAudioPowerAmplifierGpio, GPIO_MODE_OUTPUT); + // gpio_set_level(board_config::kAudioPowerAmplifierGpio, 1); + tca9555_.set_pin(board_config::kAudioPowerAmplifierGpio); + vTaskDelay(pdMS_TO_TICKS(200)); + uint8_t tca_out1_final = 0; + if (tca9555_.read_reg(0x03, &tca_out1_final) == ESP_OK) + { + ESP_LOGI(kTag, "TCA9555 OUT1 final=0x%02x PA_CTL bit=%d (exp 1)", + tca_out1_final, (tca_out1_final >> 7) & 0x01); + } + else + { + ESP_LOGE(kTag, "TCA9555 OUT1 final readback FAILED"); + } // temp debug + // Before anything can play, so the boot prompt already comes out at the + // level the user last chose rather than at the 70% default. + LoadPersistedVolume(); + initialized_ = true; + ESP_LOGI(kTag, "ES8389 output initialized rate=%lu BCLK=%d WS=%d DOUT=%d", + //"ES8311 output initialized rate=%lu BCLK=%d WS=%d DOUT=%d", + static_cast(SampleRate()), + static_cast(board_config::kAudioI2sBclkGpio), + static_cast(board_config::kAudioI2sWordSelectGpio), + static_cast(board_config::kAudioI2sDataOutGpio)); + return true; + } + + void Es8311AudioOutput::Shutdown() + { + std::lock_guard lock(mutex_); + if (!initialized_ && device_ == nullptr && tx_handle_ == nullptr) + { + return; + } + // gpio_set_level(board_config::kAudioPowerAmplifierGpio, 0); + tca9555_.clr_pin(board_config::kAudioPowerAmplifierGpio); + DestroyCodec(); + initialized_ = false; + } + + bool Es8311AudioOutput::Write( + const int16_t *samples, + size_t sample_count) + { + if (samples == nullptr || sample_count == 0) + { + return false; + } + + std::lock_guard lock(mutex_); + if (!initialized_ || device_ == nullptr || sample_count > scaled_buffer_samples_) + { + return false; + } + + const int32_t gain =static_cast(volume_percent_.load(std::memory_order_relaxed)) *256 / 100; + for (size_t index = 0; index < sample_count; ++index) + { + const int32_t scaled = + (static_cast(samples[index]) * gain) >> 8; + // scaled_buffer_[index] = static_cast( + const int16_t s = static_cast( // 2026-8-28 ckkj debug + std::clamp(scaled, -32768, 32767)); + scaled_buffer_[index * 2] = s; // 2026-8-28 ckkj debug + scaled_buffer_[index * 2 + 1] = s; // 2026-8-28 ckkj debug + } + + const int result = esp_codec_dev_write( + device_, + scaled_buffer_, + // static_cast(sample_count * sizeof(int16_t))); + static_cast(sample_count * 2 * sizeof(int16_t))); // 2026-8-28 ckkj debug + if (result != ESP_CODEC_DEV_OK) + { + ESP_LOGE(kTag, "I2S write failed code=%d", result); + return false; + } + if (AudioTap *tap = + audio_tap_.load(std::memory_order_acquire)) + { + // Keep spk.wav on the acoustic timeline: a late write means the DMA + // starved and the room heard silence, so record that silence too + // (capped so idle stretches between sessions stay cheap). + const uint64_t now_us = + static_cast(esp_timer_get_time()); + const uint64_t frame_us = + static_cast(sample_count) * 1000000ULL / + SampleRate(); + if (last_tap_write_us_ != 0 && + now_us > last_tap_write_us_ + frame_us) + { + const uint64_t gap_us = std::min( + now_us - last_tap_write_us_ - frame_us, + 500000ULL); + const size_t gap_samples = static_cast( + gap_us * SampleRate() / 1000000ULL); + if (gap_samples > 0) + { + // tap->PushOutput(nullptr, gap_samples); + // stereo 交错样本数 = 每声道样本数 * 2 + tap->PushOutput(nullptr, gap_samples * 2); // 2026-8-28 ckkj debug + } + } + last_tap_write_us_ = now_us; + tap->PushOutput(scaled_buffer_, sample_count); + } + return true; + } + + bool Es8311AudioOutput::Read( + int16_t *samples, + size_t sample_count, + uint32_t timeout_ms) + { + if (!initialized_.load() || rx_handle_ == nullptr || + samples == nullptr || sample_count == 0) + { + return false; + } + size_t bytes_read = 0; + const esp_err_t result = i2s_channel_read( + rx_handle_, + samples, + sample_count * sizeof(int16_t), + &bytes_read, + pdMS_TO_TICKS(timeout_ms)); + if (result == ESP_ERR_TIMEOUT) + { + return false; + } + if (result != ESP_OK || bytes_read != sample_count * sizeof(int16_t)) + { + ESP_LOGW(kTag, "I2S read failed result=%s bytes=%u/%u", + esp_err_to_name(result), + static_cast(bytes_read), + static_cast( + sample_count * sizeof(int16_t))); + return false; + } + // 2026-9-6 ckkj temp debug + static uint32_t diag_frame = 0; + //if (diag_frame < 20 || diag_frame % 100 == 0) + { + const size_t stereo_frames = sample_count / 2; + int64_t l_sq = 0; + int64_t r_sq = 0; + size_t nonzero_l = 0; + size_t nonzero_r = 0; + for (size_t i = 0; i < stereo_frames; ++i) + { + const int32_t l = samples[i * 2]; + const int32_t r = samples[i * 2 + 1]; + l_sq += static_cast(l) * l; + r_sq += static_cast(r) * r; + nonzero_l += l != 0 ? 1 : 0; + nonzero_r += r != 0 ? 1 : 0; + } + const uint32_t l_rms = stereo_frames > 0 ? static_cast(std::sqrt(static_cast(l_sq) / stereo_frames)) : 0; + const uint32_t r_rms = stereo_frames > 0 ? static_cast(std::sqrt(static_cast(r_sq) / stereo_frames)) : 0; + if (diag_frame < 20 || diag_frame % 100 == 0 + || l_rms > 300 || r_rms > 300) + { + ESP_LOGW(kTag, "RX diag f=%u nz=%zu/%zu L_rms=%u R_rms=%u", + static_cast(diag_frame), + static_cast(nonzero_l), + static_cast(nonzero_r), + static_cast(l_rms), + static_cast(r_rms)); + } + } + ++diag_frame; ////temp debug end + if (AudioTap *tap = audio_tap_.load(std::memory_order_acquire)) + { + tap->PushInput(samples, sample_count); + } + return true; + } + + void Es8311AudioOutput::SetVolume(uint8_t volume_percent) + { + const uint8_t clamped = std::min(volume_percent, 100); + const uint8_t previous = + volume_percent_.exchange(clamped, std::memory_order_relaxed); + ESP_LOGI(kTag, "software volume=%u%%", + static_cast(clamped)); + if (previous != clamped) + { + PersistVolume(clamped); + } + } + + void Es8311AudioOutput::LoadPersistedVolume() + { + nvs_handle_t handle = 0; + if (nvs_open(kVolumeNamespace, NVS_READONLY, &handle) != ESP_OK) + { + return; + } + uint8_t stored = 0; + const esp_err_t read = nvs_get_u8(handle, kVolumeKey, &stored); + nvs_close(handle); + if (read != ESP_OK) + { + return; + } + const uint8_t clamped = std::min(stored, 100); + volume_percent_.store(clamped, std::memory_order_relaxed); + ESP_LOGI(kTag, "restored volume=%u%%", + static_cast(clamped)); + } + + void Es8311AudioOutput::PersistVolume(uint8_t volume_percent) const + { + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kVolumeNamespace, NVS_READWRITE, &handle); + if (result == ESP_OK) + { + result = nvs_set_u8(handle, kVolumeKey, volume_percent); + } + if (result == ESP_OK) + { + result = nvs_commit(handle); + } + if (handle != 0) + { + nvs_close(handle); + } + if (result != ESP_OK) + { + // Losing the setting is not worth failing playback over. + ESP_LOGW(kTag, "volume persist failed: %s",esp_err_to_name(result)); + } + } + + uint8_t Es8311AudioOutput::VolumePercent() const + { + return volume_percent_.load(std::memory_order_relaxed); + } + + uint32_t Es8311AudioOutput::SampleRate() const + { + return board_config::kAudioOutputSampleRate; + } + + uint32_t Es8311AudioOutput::InputSampleRate() const + { + return board_config::kAudioInputHardwareSampleRate; + } + + bool Es8311AudioOutput::InitializeI2s() + { + // 6 x 360 frames @ 24 kHz = 90 ms per direction — the previous firmware's + // DMA depth in TIME, not in numbers. It ran 6 x 240 at 16 kHz (= 90 ms); + // copying "6 x 240" verbatim to a 24 kHz clock silently cut the buffer to + // 60 ms. On TX that 60 ms was the playback task's ONLY runway (decode and + // write are fused here, there is no decoded-PCM queue like the previous + // firmware's 480 ms one), so any scheduling delay past one frame time + // underran the DAC and stuttered audibly. On RX the deeper buffer absorbs + // capture-loop jitter that previously overflowed and cost microphone + // frames. 720 bytes per descriptor stays well under the 4092-byte limit. + i2s_chan_config_t channel = { + .id = I2S_NUM_0, + .role = I2S_ROLE_MASTER, + .dma_desc_num = 6, + //.dma_frame_num = 360, + .dma_frame_num = 720, + .auto_clear_after_cb = true, + .auto_clear_before_cb = false, + .allow_pd = false, + .intr_priority = 0, + }; + esp_err_t result = + i2s_new_channel(&channel, &tx_handle_, &rx_handle_); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "I2S channel creation failed: %s", + esp_err_to_name(result)); + return false; + } + + i2s_std_config_t standard = { + .clk_cfg = { + .sample_rate_hz = SampleRate(), + .clk_src = I2S_CLK_SRC_DEFAULT, + .ext_clk_freq_hz = 0, + .mclk_multiple = I2S_MCLK_MULTIPLE_256, + }, + .slot_cfg = { + .data_bit_width = I2S_DATA_BIT_WIDTH_16BIT, + .slot_bit_width = I2S_SLOT_BIT_WIDTH_AUTO, + // .slot_mode = I2S_SLOT_MODE_MONO, + //.slot_mask = I2S_STD_SLOT_LEFT,//2026-8-28 ckkj debug + .slot_mode = I2S_SLOT_MODE_STEREO, + .slot_mask = I2S_STD_SLOT_BOTH, + .ws_width = I2S_DATA_BIT_WIDTH_16BIT, + .ws_pol = false, + .bit_shift = true, + .left_align = false, // true, + .big_endian = false, + .bit_order_lsb = false, + }, + .gpio_cfg = { + .mclk = board_config::kAudioI2sMclkGpio, + .bclk = board_config::kAudioI2sBclkGpio, + .ws = board_config::kAudioI2sWordSelectGpio, + .dout = board_config::kAudioI2sDataOutGpio, + .din = board_config::kAudioI2sDataInGpio, + .invert_flags = { + .mclk_inv = false, + .bclk_inv = false, + .ws_inv = false, + }, + }, + }; + result = i2s_channel_init_std_mode(tx_handle_, &standard); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "I2S standard mode failed: %s", + esp_err_to_name(result)); + return false; + } + result = i2s_channel_init_std_mode(rx_handle_, &standard); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "I2S RX standard mode failed: %s", + esp_err_to_name(result)); + return false; + } + result = i2s_channel_enable(rx_handle_); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "I2S RX enable failed: %s", + esp_err_to_name(result)); + return false; + } + rx_enabled_ = true; + result = i2s_channel_enable(tx_handle_); + if (result != ESP_OK) + { + ESP_LOGE(kTag, "I2S TX enable failed: %s", + esp_err_to_name(result)); + return false; + } + tx_enabled_ = true; + return true; + } + + bool Es8311AudioOutput::InitializeCodec() + { + audio_codec_i2s_cfg_t i2s = { + .port = I2S_NUM_0, + .rx_handle = rx_handle_, + .tx_handle = tx_handle_, + }; + data_interface_ = audio_codec_new_i2s_data(&i2s); + + audio_codec_i2c_cfg_t i2c = { + .port = I2C_NUM_0, + //.addr = kEs8311Address, + .addr = kEs8389Address, + .bus_handle = i2c_bus_.Handle(), + }; + control_interface_ = audio_codec_new_i2c_ctrl(&i2c); + gpio_interface_ = audio_codec_new_gpio(); + if (data_interface_ == nullptr || control_interface_ == nullptr || + gpio_interface_ == nullptr) + { + ESP_LOGE(kTag, "codec transport interface creation failed"); + return false; + } + + // es8311_codec_cfg_t codec = {}; + es8389_codec_cfg_t codec = {}; + codec.ctrl_if = control_interface_; + codec.gpio_if = gpio_interface_; + codec.codec_mode = ESP_CODEC_DEV_WORK_MODE_BOTH; + codec.pa_pin = board_config::kAudioPowerAmplifierGpio; // 2026-8-18 ckkj 已改为扩展芯片引脚 + // codec.pa_pin = -1;//跳过 + codec.use_mclk = false; + codec.hw_gain.pa_voltage = 5.0f; + codec.hw_gain.codec_dac_voltage = 3.3f; + // codec_interface_ = es8311_codec_new(&codec); + codec_interface_ = es8389_codec_new(&codec); + + if (codec_interface_ == nullptr) + { + ESP_LOGE(kTag, "ES8389 interface creation failed"); + return false; + } + + esp_codec_dev_cfg_t device = { + .dev_type = ESP_CODEC_DEV_TYPE_IN_OUT, + .codec_if = codec_interface_, + .data_if = data_interface_, + }; + device_ = esp_codec_dev_new(&device); + if (device_ == nullptr) + { + ESP_LOGE(kTag, "codec device creation failed"); + return false; + } + + esp_codec_dev_sample_info_t sample = { + .bits_per_sample = 16, + .channel = 2, // 1, + .channel_mask = 0, + .sample_rate = SampleRate(), + .mclk_multiple = 0, + }; + int result = esp_codec_dev_open(device_, &sample); + if (result != ESP_CODEC_DEV_OK) + { + ESP_LOGE(kTag, "codec open failed code=%d", result); + return false; + } + + // esp_codec_dev_write_reg(device_, 0xf0, 0x13); + result = esp_codec_dev_set_out_vol(device_, 100); + if (result != ESP_CODEC_DEV_OK) + { + ESP_LOGE(kTag, "codec volume initialization failed code=%d", result); + return false; + } + result = esp_codec_dev_set_in_gain(device_, 40.0f); + if (result != ESP_CODEC_DEV_OK) + { + ESP_LOGE(kTag, "codec input gain initialization failed code=%d", + result); + return false; + } + + // int val = 0; + // for (int reg = 0; reg <= 0xFF; reg++) // ES8389有效寄存器0~0xFF + // { + // esp_err_t ret = esp_codec_dev_read_reg(device_, (uint8_t)reg, &val); + + // if (ret == ESP_OK) + // { + // ESP_LOGI("DUMP", "REG[%02X] = 0x%02X", reg, val); + // } + // else + // { + // ESP_LOGW("DUMP", "REG[%02X] read failed ret:%d", reg, ret); + // } + // } + + return true; + } + + void Es8311AudioOutput::DestroyCodec() + { + if (device_ != nullptr) + { + esp_codec_dev_close(device_); + esp_codec_dev_delete(device_); + device_ = nullptr; + } + if (codec_interface_ != nullptr) + { + audio_codec_delete_codec_if(codec_interface_); + codec_interface_ = nullptr; + } + if (control_interface_ != nullptr) + { + audio_codec_delete_ctrl_if(control_interface_); + control_interface_ = nullptr; + } + if (gpio_interface_ != nullptr) + { + audio_codec_delete_gpio_if(gpio_interface_); + gpio_interface_ = nullptr; + } + if (data_interface_ != nullptr) + { + audio_codec_delete_data_if(data_interface_); + data_interface_ = nullptr; + } + if (tx_handle_ != nullptr) + { + if (tx_enabled_) { + i2s_channel_disable(tx_handle_); + tx_enabled_ = false; + } + i2s_del_channel(tx_handle_); + tx_handle_ = nullptr; + } + if (rx_handle_ != nullptr) + { + if (rx_enabled_) { + i2s_channel_disable(rx_handle_); + rx_enabled_ = false; + } + i2s_del_channel(rx_handle_); + rx_handle_ = nullptr; + } + } + +} // namespace borla diff --git a/main/platform/borla_s3/es8311_audio_output.h b/main/platform/borla_s3/es8311_audio_output.h new file mode 100644 index 0000000..f5cd7af --- /dev/null +++ b/main/platform/borla_s3/es8311_audio_output.h @@ -0,0 +1,83 @@ +#pragma once + +#include "audio/audio_output.h" +#include "audio/audio_input.h" +#include "platform/borla_s3/i2c_bus.h" +#include "tca9555.h" +#include +#include +#include + +#include +#include +#include +#include + +namespace borla { + +class AudioTap; + +class Es8311AudioOutput final + : public IAudioOutput, + public IAudioInput { +public: + //explicit Es8311AudioOutput(BorlaS3I2cBus& i2c_bus); + explicit Es8311AudioOutput(BorlaS3I2cBus& i2c_bus, TCA9555& tca9555); + ~Es8311AudioOutput(); + + bool Initialize() override; + void Shutdown() override; + bool Write(const int16_t* samples, size_t sample_count) override; + void SetVolume(uint8_t volume_percent) override; + uint8_t VolumePercent() const override; + uint32_t SampleRate() const override; + bool Read( + int16_t* samples, + size_t sample_count, + uint32_t timeout_ms) override; + uint32_t InputSampleRate() const override; + // Debug recorder. This is the hardware boundary, so tapping here captures + // exactly what the ADC produced and exactly what the DAC received — + // prompts, TTS, tones, everything — regardless of which pipeline made it. + void SetAudioTap(AudioTap* tap) + { + audio_tap_.store(tap, std::memory_order_release); + } + +private: + bool InitializeI2s(); + bool InitializeCodec(); + void DestroyCodec(); + // Volume survives a reboot, as it did in the previous firmware + // (audio_codec.cc: Settings("audio").GetInt/SetInt("output_volume")). + // Without this every flash or power cycle came back at the 70% default and + // startled whoever had turned it down. + void LoadPersistedVolume(); + void PersistVolume(uint8_t volume_percent) const; + + BorlaS3I2cBus& i2c_bus_; + TCA9555& tca9555_; + mutable std::mutex mutex_; + i2s_chan_handle_t tx_handle_ = nullptr; + i2s_chan_handle_t rx_handle_ = nullptr; + bool tx_enabled_ = false;////// + bool rx_enabled_ = false;///// + const audio_codec_data_if_t* data_interface_ = nullptr; + const audio_codec_ctrl_if_t* control_interface_ = nullptr; + const audio_codec_if_t* codec_interface_ = nullptr; + const audio_codec_gpio_if_t* gpio_interface_ = nullptr; + esp_codec_dev_handle_t device_ = nullptr; + int16_t* scaled_buffer_ = nullptr; + size_t scaled_buffer_samples_ = 0; + // Lock-free on purpose. VolumePercent() is read on the playback hot path + // (once per 60 ms frame) and by the periodic status frame on the esp_timer + // task; taking mutex_ there would block behind a full blocking I2S write. + std::atomic volume_percent_{70}; + std::atomic initialized_{false}; + std::atomic audio_tap_{nullptr}; + // Playback-task only (Write holds mutex_): timestamp of the previous + // tap-recorded write, used to insert gap silence into spk.wav. + uint64_t last_tap_write_us_ = 0; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/esp_websocket_transport.cc b/main/platform/borla_s3/esp_websocket_transport.cc new file mode 100644 index 0000000..efd4130 --- /dev/null +++ b/main/platform/borla_s3/esp_websocket_transport.cc @@ -0,0 +1,747 @@ +#include "platform/borla_s3/esp_websocket_transport.h" + +#include "connectivity/wifi_types.h" +#include "diagnostics/trace_context.h" +#include "protocol/websocket_uri.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "EspWebsocket2"; + +// Wall-clock milliseconds, or 0 while the clock still reads 1970 because NTP +// has not landed. Callers omit the header in that case rather than reporting a +// skew of half a century. +int64_t EpochMs() +{ + struct timeval now {}; + if (gettimeofday(&now, nullptr) != 0 || + now.tv_sec < 1700000000) { + return 0; + } + return static_cast(now.tv_sec) * 1000 + + now.tv_usec / 1000; +} +constexpr int kReadTimeoutMs = 25; +constexpr int kWriteTimeoutMs = 2000; +constexpr uint32_t kCloseDrainTimeoutMs = 750; +constexpr int kRxOverflowError = -3201; +constexpr int kConnectError = -3202; +constexpr int kReadError = -3203; +constexpr int kWriteError = -3204; + +} // namespace + +EspWebsocketTransport::~EspWebsocketTransport() +{ + connected_.store(false); + CleanupHandles(); + if (rx_message_ != nullptr) { + heap_caps_free(rx_message_); + rx_message_ = nullptr; + } + if (rx_chunk_ != nullptr) { + heap_caps_free(rx_chunk_); + rx_chunk_ = nullptr; + } + if (command_pool_ != nullptr) { + heap_caps_free(command_pool_); + command_pool_ = nullptr; + telemetry_pool_ = nullptr; + } +} + +bool EspWebsocketTransport::Initialize() +{ + if (initialized_) { + return true; + } + + rx_message_ = static_cast(heap_caps_malloc( + kMaxRxMessage, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + rx_chunk_ = static_cast(heap_caps_malloc( + kReadChunkSize, + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + command_pool_ = static_cast(heap_caps_calloc( + kCommandQueueDepth + kTelemetrySlotCount, + sizeof(Command), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + if (rx_message_ == nullptr || rx_chunk_ == nullptr || + command_pool_ == nullptr) { + ESP_LOGE(kTag, + "PSRAM allocation failed rx=%p chunk=%p commands=%p", + rx_message_, + rx_chunk_, + command_pool_); + return false; + } + for (size_t index = 0; + index < kCommandQueueDepth + kTelemetrySlotCount; + ++index) { + new (&command_pool_[index]) Command(); + } + telemetry_pool_ = command_pool_ + kCommandQueueDepth; + + free_commands_ = xQueueCreateStatic( + kCommandQueueDepth, + sizeof(uint16_t), + free_commands_storage_.data(), + &free_commands_control_); + command_queue_ = xQueueCreateStatic( + kCommandQueueDepth, + sizeof(uint16_t), + command_queue_storage_.data(), + &command_queue_control_); + close_completed_ = xSemaphoreCreateBinaryStatic( + &close_completed_storage_); + if (free_commands_ == nullptr || command_queue_ == nullptr || + close_completed_ == nullptr) { + ESP_LOGE(kTag, "command index queue creation failed"); + return false; + } + for (uint16_t index = 0; index < kCommandQueueDepth; ++index) { + if (xQueueSend(free_commands_, &index, 0) != pdTRUE) { + ESP_LOGE(kTag, "failed to seed command slot=%u", index); + return false; + } + } + + task_ = xTaskCreateStatic( + &EspWebsocketTransport::TaskEntry, + "websocket2", + task_stack_budget::kWebsocketTransportBytes, + this, + 4, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + ESP_LOGE(kTag, "transport task creation failed"); + return false; + } + initialized_ = true; + ESP_LOGI(kTag, + "initialized tx_depth=%u tx_payload=%u rx_message=%u " + "command_pool=PSRAM telemetry=latest-wins " + "stack_bytes=%u memory=internal", + static_cast(kCommandQueueDepth), + static_cast(kMaxTxPayload), + static_cast(kMaxRxMessage), + static_cast( + task_stack_budget::kWebsocketTransportBytes)); + return true; +} + +bool EspWebsocketTransport::Open( + const WebsocketTransportConfig& config, + IWebsocketTransportObserver& observer) +{ + if (!initialized_) { + return false; + } + portENTER_CRITICAL(&state_lock_); + config_ = config; + observer_ = &observer; + portEXIT_CRITICAL(&state_lock_); + return PostControl(CommandType::kOpen); +} + +void EspWebsocketTransport::Close() +{ + if (!initialized_) { + return; + } + if (xTaskGetCurrentTaskHandle() == task_) { + DoClose(true, 0); + return; + } + while (xSemaphoreTake(close_completed_, 0) == pdTRUE) { + } + if (!PostControl(CommandType::kClose)) { + ESP_LOGE(kTag, "close command queue full"); + return; + } + if (xSemaphoreTake( + close_completed_, + pdMS_TO_TICKS(kCloseDrainTimeoutMs)) != pdTRUE) { + ESP_LOGW( + kTag, + "close drain timed out after %lu ms", + static_cast(kCloseDrainTimeoutMs)); + } +} + +bool EspWebsocketTransport::SendText(const char* data, size_t size) +{ + return PostPayload(CommandType::kText, data, size); +} + +bool EspWebsocketTransport::SendTelemetryText( + const char* data, + size_t size) +{ + return PostTelemetry(data, size); +} + +bool EspWebsocketTransport::SendBinary( + const uint8_t* data, + size_t size) +{ + return PostPayload(CommandType::kBinary, data, size); +} + +void EspWebsocketTransport::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void EspWebsocketTransport::Run() +{ + ESP_LOGI(kTag, "transport task started"); + while (true) { + if (!connected_.load()) { + uint16_t slot_index = 0; + if (xQueueReceive( + command_queue_, + &slot_index, + portMAX_DELAY) == pdTRUE) { + if (slot_index >= kCommandQueueDepth) { + ESP_LOGE(kTag, + "invalid command slot=%u", + slot_index); + continue; + } + HandleCommand(command_pool_[slot_index]); + ReleaseCommand(slot_index); + } + continue; + } + + if (connected_notification_pending_) { + NotifyConnected(); + if (!connected_.load()) { + continue; + } + } + + uint16_t slot_index = 0; + for (size_t handled = 0; + handled < kCommandsPerRead && + xQueueReceive( + command_queue_, &slot_index, 0) == pdTRUE; + ++handled) { + if (slot_index >= kCommandQueueDepth) { + ESP_LOGE(kTag, + "invalid command slot=%u", + slot_index); + continue; + } + HandleCommand(command_pool_[slot_index]); + ReleaseCommand(slot_index); + if (!connected_.load()) { + break; + } + } + if (connected_.load()) { + SendPendingTelemetry(); + } + if (connected_.load()) { + ReadOnce(); + } + } +} + +bool EspWebsocketTransport::PostControl(CommandType type) +{ + return PostPayload(type, nullptr, 0); +} + +bool EspWebsocketTransport::PostPayload( + CommandType type, + const void* data, + size_t size) +{ + const bool control = + type == CommandType::kOpen || type == CommandType::kClose; + if ((!control && (data == nullptr || size == 0)) || + size > kMaxTxPayload) { + ESP_LOGW(kTag, "invalid tx payload type=%u size=%u", + static_cast(type), + static_cast(size)); + return false; + } + if (!initialized_ || free_commands_ == nullptr || + command_queue_ == nullptr || command_pool_ == nullptr) { + return false; + } + + if (type == CommandType::kBinary && + uxQueueMessagesWaiting(free_commands_) <= + kControlReserveSlots) { + return false; + } + + uint16_t slot_index = 0; + if (xQueueReceive(free_commands_, &slot_index, 0) != pdTRUE) { + ESP_LOGE(kTag, "command pool exhausted type=%u", + static_cast(type)); + return false; + } + Command& command = command_pool_[slot_index]; + command.type = type; + command.size = static_cast(size); + if (size > 0) { + std::memcpy(command.payload.data(), data, size); + } + if (xQueueSend(command_queue_, &slot_index, 0) != pdTRUE) { + ReleaseCommand(slot_index); + ESP_LOGE(kTag, "tx command queue full type=%u", + static_cast(type)); + return false; + } + return true; +} + +bool EspWebsocketTransport::PostTelemetry( + const void* data, + size_t size) +{ + if (!initialized_ || !connected_.load() || + telemetry_pool_ == nullptr || data == nullptr || size == 0 || + size > kMaxTxPayload) { + return false; + } + + portENTER_CRITICAL(&telemetry_lock_); + int8_t slot = telemetry_pending_slot_; + if (slot < 0) { + slot = telemetry_sending_slot_ == 0 ? 1 : 0; + } + Command& command = telemetry_pool_[slot]; + command.type = CommandType::kText; + command.size = static_cast(size); + std::memcpy(command.payload.data(), data, size); + telemetry_pending_slot_ = slot; + portEXIT_CRITICAL(&telemetry_lock_); + return true; +} + +void EspWebsocketTransport::SendPendingTelemetry() +{ + int8_t slot = -1; + portENTER_CRITICAL(&telemetry_lock_); + if (telemetry_pending_slot_ >= 0) { + slot = telemetry_pending_slot_; + telemetry_pending_slot_ = -1; + telemetry_sending_slot_ = slot; + } + portEXIT_CRITICAL(&telemetry_lock_); + if (slot < 0) { + return; + } + + const Command& command = telemetry_pool_[slot]; + const bool sent = SendFrame( + command.payload.data(), command.size, false); + portENTER_CRITICAL(&telemetry_lock_); + telemetry_sending_slot_ = -1; + portEXIT_CRITICAL(&telemetry_lock_); + if (!sent) { + DoClose(true, kWriteError); + } +} + +void EspWebsocketTransport::ReleaseCommand(uint16_t slot_index) +{ + if (slot_index >= kCommandQueueDepth || free_commands_ == nullptr || + xQueueSend(free_commands_, &slot_index, 0) != pdTRUE) { + ESP_LOGE(kTag, "failed to release command slot=%u", slot_index); + } +} + +void EspWebsocketTransport::HandleCommand(const Command& command) +{ + switch (command.type) { + case CommandType::kOpen: + if (!connected_.load()) { + DoOpen(); + } + return; + case CommandType::kClose: + DoClose(true, 0); + if (close_completed_ != nullptr) { + xSemaphoreGive(close_completed_); + } + return; + case CommandType::kText: + if (!SendFrame( + command.payload.data(), + command.size, + false)) { + DoClose(true, kWriteError); + } + return; + case CommandType::kBinary: + if (!SendFrame( + command.payload.data(), + command.size, + true)) { + DoClose(true, kWriteError); + } + return; + } +} + +void EspWebsocketTransport::DoOpen() +{ + WebsocketTransportConfig config; + portENTER_CRITICAL(&state_lock_); + config = config_; + portEXIT_CRITICAL(&state_lock_); + + WebsocketUri uri; + if (!ParseWebsocketUri(config.url.data(), &uri)) { + ESP_LOGE(kTag, "invalid WebSocket URL"); + DoClose(true, kConnectError); + return; + } + + CleanupHandles(); + parent_transport_ = + uri.secure ? esp_transport_ssl_init() : esp_transport_tcp_init(); + if (parent_transport_ == nullptr) { + DoClose(true, kConnectError); + return; + } + if (uri.secure) { + esp_transport_ssl_crt_bundle_attach( + parent_transport_, esp_crt_bundle_attach); + } + + websocket_transport_ = + esp_transport_ws_init(parent_transport_); + if (websocket_transport_ == nullptr) { + DoClose(true, kConnectError); + return; + } + esp_transport_ws_set_path(websocket_transport_, uri.path.data()); + + // The server correlates its own trace with the device's using these + // headers (websocket_server.py: X-Borla-Trace-Id / X-Borla-Session-Id) and + // derives the device-to-server clock delta from the two timestamps. When + // they are absent it mints fresh ids instead, and the two halves of a + // session can no longer be joined — which is the state this firmware was + // in until now. + // + // client_epoch_ms is omitted entirely rather than sent as 0 when the wall + // clock has not been synced: the handshake often happens before NTP, and a + // 1970 timestamp would read as a 56-year skew. + const int64_t client_epoch_ms = EpochMs(); + char epoch_header[64]{}; + if (client_epoch_ms > 0) { + std::snprintf( + epoch_header, + sizeof(epoch_header), + "X-Borla-Client-Epoch-Ms: %lld\r\n", + static_cast(client_epoch_ms)); + } + + // A connect attempt opens a new exchange, so it gets a fresh trace id — + // same lifecycle rule as the session id below. This also covers the very + // first connect of a boot, where no subsystem has minted a trace yet and + // TraceId() still reads "-": the server's `get_header(...) or + // new_trace_id()` treats "-" as a present value and would adopt it + // verbatim. ServerHello handling refreshes the trace again afterwards, + // which is fine — this one correlates the handshake, that one the first + // turn. + TraceContext::RefreshTrace("ws"); + + char headers[512]{}; + const int header_size = std::snprintf( + headers, + sizeof(headers), + "Device-Id: %s\r\n" + "Protocol-Version: %u\r\n" + "Firmware-Version: %s\r\n" + "X-Borla-Trace-Id: %s\r\n" + "X-Borla-Session-Id: %s\r\n" + "X-Request-Id: %s\r\n" + "X-Borla-Client-Send-Ms: %llu\r\n" + "%s", + config.device_id.data(), + static_cast(config.protocol_version), + config.firmware_version.data(), + TraceContext::TraceId(), + // Minted per connect attempt, not reused: the session is connection- + // scoped and the server adopts whatever it is handed here until its own + // ServerHello id replaces it. + TraceContext::RefreshSession(), + TraceContext::NewRequestId(), + static_cast( + esp_timer_get_time() / 1000), + epoch_header); + if (header_size <= 0 || + header_size >= static_cast(sizeof(headers)) || + esp_transport_ws_set_headers( + websocket_transport_, headers) != ESP_OK) { + DoClose(true, kConnectError); + return; + } + + char authorization[kWebsocketTokenCapacity + 16]{}; + if (config.token[0] != '\0') { + const bool has_scheme = + std::strchr(config.token.data(), ' ') != nullptr; + const int auth_size = std::snprintf( + authorization, + sizeof(authorization), + has_scheme ? "%s" : "Bearer %s", + config.token.data()); + if (auth_size <= 0 || + auth_size >= static_cast(sizeof(authorization)) || + esp_transport_ws_set_auth( + websocket_transport_, authorization) != ESP_OK) { + DoClose(true, kConnectError); + return; + } + } + + ESP_LOGI(kTag, "connecting secure=%d host=%s port=%u path=%s", + uri.secure ? 1 : 0, + uri.host.data(), + static_cast(uri.port), + uri.path.data()); + const int result = esp_transport_connect( + websocket_transport_, + uri.host.data(), + uri.port, + static_cast(config.connect_timeout_ms)); + if (result != 0) { + ESP_LOGE(kTag, "WebSocket upgrade failed result=%d http=%d", + result, + esp_transport_ws_get_upgrade_request_status( + websocket_transport_)); + DoClose(true, kConnectError); + return; + } + + rx_message_size_ = 0; + frame_bytes_remaining_ = 0; + rx_message_started_ = false; + rx_overflow_ = false; + frame_capture_ = false; + connected_.store(true); + connected_notification_pending_ = true; + ESP_LOGI(kTag, "WebSocket connected"); +} + +void EspWebsocketTransport::DoClose(bool notify, int error_code) +{ + const bool had_transport = + connected_.exchange(false) || + websocket_transport_ != nullptr || + parent_transport_ != nullptr; + if (websocket_transport_ != nullptr && error_code == 0) { + esp_transport_ws_send_raw( + websocket_transport_, + static_cast( + WS_TRANSPORT_OPCODES_CLOSE | + WS_TRANSPORT_OPCODES_FIN), + nullptr, + 0, + 100); + } + CleanupHandles(); + connected_notification_pending_ = false; + portENTER_CRITICAL(&telemetry_lock_); + telemetry_pending_slot_ = -1; + telemetry_sending_slot_ = -1; + portEXIT_CRITICAL(&telemetry_lock_); + rx_message_size_ = 0; + frame_bytes_remaining_ = 0; + rx_message_started_ = false; + rx_overflow_ = false; + frame_capture_ = false; + + if (notify && had_transport) { + IWebsocketTransportObserver* observer = ObserverSnapshot(); + if (observer != nullptr) { + observer->OnWebsocketDisconnected(error_code); + } + } +} + +void EspWebsocketTransport::NotifyConnected() +{ + connected_notification_pending_ = false; + IWebsocketTransportObserver* observer = ObserverSnapshot(); + if (observer != nullptr) { + observer->OnWebsocketConnected(); + } +} + +bool EspWebsocketTransport::SendFrame( + const void* data, + size_t size, + bool binary) +{ + if (!connected_.load() || websocket_transport_ == nullptr) { + return false; + } + const auto opcode = static_cast( + (binary + ? WS_TRANSPORT_OPCODES_BINARY + : WS_TRANSPORT_OPCODES_TEXT) | + WS_TRANSPORT_OPCODES_FIN); + const int written = esp_transport_ws_send_raw( + websocket_transport_, + opcode, + static_cast(data), + static_cast(size), + kWriteTimeoutMs); + return written == static_cast(size); +} + +void EspWebsocketTransport::ReadOnce() +{ + if (rx_chunk_ == nullptr) { + DoClose(true, kReadError); + return; + } + const int received = esp_transport_read( + websocket_transport_, + rx_chunk_, + static_cast(kReadChunkSize), + kReadTimeoutMs); + if (received > 0) { + HandleReadChunk(rx_chunk_, static_cast(received)); + vTaskDelay(1); + } else if (received < 0) { + ESP_LOGW(kTag, "WebSocket read failed result=%d", received); + DoClose(true, kReadError); + } +} + +void EspWebsocketTransport::HandleReadChunk( + const char* data, + size_t size) +{ + if (frame_bytes_remaining_ == 0) { + const int payload_size = + esp_transport_ws_get_read_payload_len(websocket_transport_); + if (payload_size < 0) { + DoClose(true, kReadError); + return; + } + frame_bytes_remaining_ = static_cast(payload_size); + frame_fin_ = + esp_transport_ws_get_fin_flag(websocket_transport_); + const ws_transport_opcodes_t opcode = + esp_transport_ws_get_read_opcode(websocket_transport_); + + if (opcode == WS_TRANSPORT_OPCODES_TEXT || + opcode == WS_TRANSPORT_OPCODES_BINARY) { + frame_capture_ = true; + if (rx_message_started_) { + rx_overflow_ = true; + } else { + rx_message_started_ = true; + rx_message_binary_ = + opcode == WS_TRANSPORT_OPCODES_BINARY; + rx_message_size_ = 0; + } + } else if (opcode == WS_TRANSPORT_OPCODES_CONT) { + frame_capture_ = rx_message_started_; + } else { + // Control frame (ping/pong/close). Its payload must still be + // consumed here: returning early would leave the remaining byte + // counter set and make the next data frame's header be skipped, + // splicing control bytes into the application message. + frame_capture_ = false; + } + } + + if (size > frame_bytes_remaining_) { + DoClose(true, kReadError); + return; + } + frame_bytes_remaining_ -= size; + + if (!frame_capture_) { + return; + } + + if (!rx_overflow_ && + rx_message_size_ + size <= kMaxRxMessage) { + std::memcpy(rx_message_ + rx_message_size_, data, size); + rx_message_size_ += size; + } else { + rx_overflow_ = true; + } + + if (frame_bytes_remaining_ == 0 && frame_fin_) { + if (rx_overflow_) { + ESP_LOGE(kTag, "WebSocket message exceeds %u bytes", + static_cast(kMaxRxMessage)); + DoClose(true, kRxOverflowError); + return; + } + DispatchMessage(); + rx_message_size_ = 0; + rx_message_started_ = false; + } +} + +void EspWebsocketTransport::DispatchMessage() +{ + IWebsocketTransportObserver* observer = ObserverSnapshot(); + if (observer == nullptr) { + return; + } + if (rx_message_binary_) { + observer->OnWebsocketBinary(rx_message_, rx_message_size_); + } else { + observer->OnWebsocketText( + reinterpret_cast(rx_message_), + rx_message_size_); + } +} + +void EspWebsocketTransport::CleanupHandles() +{ + if (websocket_transport_ != nullptr) { + esp_transport_close(websocket_transport_); + esp_transport_destroy(websocket_transport_); + websocket_transport_ = nullptr; + } + if (parent_transport_ != nullptr) { + esp_transport_destroy(parent_transport_); + parent_transport_ = nullptr; + } +} + +IWebsocketTransportObserver* +EspWebsocketTransport::ObserverSnapshot() const +{ + portENTER_CRITICAL(&state_lock_); + IWebsocketTransportObserver* const observer = observer_; + portEXIT_CRITICAL(&state_lock_); + return observer; +} + +} // namespace borla diff --git a/main/platform/borla_s3/esp_websocket_transport.h b/main/platform/borla_s3/esp_websocket_transport.h new file mode 100644 index 0000000..d6773b6 --- /dev/null +++ b/main/platform/borla_s3/esp_websocket_transport.h @@ -0,0 +1,131 @@ +#pragma once + +#include "core/task_stack_budget.h" +#include "protocol/websocket_transport.h" +#include "protocol/binary_audio_protocol.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace borla { + +class EspWebsocketTransport final : public IWebsocketTransport { +public: + ~EspWebsocketTransport(); + + bool Initialize() override; + bool Open( + const WebsocketTransportConfig& config, + IWebsocketTransportObserver& observer) override; + void Close() override; + bool SendText(const char* data, size_t size) override; + bool SendTelemetryText( + const char* data, + size_t size) override; + bool SendBinary(const uint8_t* data, size_t size) override; + bool IsConnected() const override { return connected_.load(); } + +private: + enum class CommandType : uint8_t { + kOpen, + kClose, + kText, + kBinary, + }; + + static constexpr size_t kMaxTxPayload = + kBinaryAudioMaximumPacketBytes; + static constexpr size_t kMaxRxMessage = 8192; + static constexpr size_t kReadChunkSize = 2048; + static constexpr size_t kCommandQueueDepth = 10; + static constexpr size_t kTelemetrySlotCount = 2; + static constexpr size_t kControlReserveSlots = 2; + static constexpr size_t kCommandsPerRead = 2; + + struct Command { + CommandType type = CommandType::kOpen; + uint16_t size = 0; + std::array payload{}; + }; + + static void TaskEntry(void* context); + [[noreturn]] void Run(); + bool PostControl(CommandType type); + bool PostPayload( + CommandType type, + const void* data, + size_t size); + bool PostTelemetry(const void* data, size_t size); + void SendPendingTelemetry(); + void ReleaseCommand(uint16_t slot_index); + void HandleCommand(const Command& command); + void DoOpen(); + void DoClose(bool notify, int error_code); + void NotifyConnected(); + bool SendFrame( + const void* data, + size_t size, + bool binary); + void ReadOnce(); + void HandleReadChunk(const char* data, size_t size); + void DispatchMessage(); + void CleanupHandles(); + IWebsocketTransportObserver* ObserverSnapshot() const; + + mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED; + WebsocketTransportConfig config_{}; + IWebsocketTransportObserver* observer_ = nullptr; + + Command* command_pool_ = nullptr; + Command* telemetry_pool_ = nullptr; + QueueHandle_t free_commands_ = nullptr; + QueueHandle_t command_queue_ = nullptr; + StaticQueue_t free_commands_control_{}; + StaticQueue_t command_queue_control_{}; + SemaphoreHandle_t close_completed_ = nullptr; + StaticSemaphore_t close_completed_storage_{}; + alignas(uint16_t) + std::array + free_commands_storage_{}; + alignas(uint16_t) + std::array + command_queue_storage_{}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array< + StackType_t, + task_stack_budget::kWebsocketTransportBytes / sizeof(StackType_t)> + task_stack_{}; + + bool initialized_ = false; + std::atomic connected_{false}; + bool connected_notification_pending_ = false; + portMUX_TYPE telemetry_lock_ = portMUX_INITIALIZER_UNLOCKED; + int8_t telemetry_pending_slot_ = -1; + int8_t telemetry_sending_slot_ = -1; + + esp_transport_handle_t parent_transport_ = nullptr; + esp_transport_handle_t websocket_transport_ = nullptr; + uint8_t* rx_message_ = nullptr; + // Read scratch lives in PSRAM instead of on the transport task stack: the + // same stack frame also carries the ServerHello parser and the TLS write. + char* rx_chunk_ = nullptr; + size_t rx_message_size_ = 0; + size_t frame_bytes_remaining_ = 0; + bool rx_message_binary_ = false; + bool rx_message_started_ = false; + bool rx_overflow_ = false; + bool frame_fin_ = false; + bool frame_capture_ = false; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/esp_wifi_transport.cc b/main/platform/borla_s3/esp_wifi_transport.cc new file mode 100644 index 0000000..ce9d2dc --- /dev/null +++ b/main/platform/borla_s3/esp_wifi_transport.cc @@ -0,0 +1,502 @@ +#include "platform/borla_s3/esp_wifi_transport.h" + +#include "core/psram_object.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +namespace borla { +namespace { + +constexpr const char* kTag = "EspWifiTransport2"; +constexpr size_t kMaximumScanRecords = 32; + +using ScanRecords = std::array; + +// Guard rail: this buffer overflowed the 4 KB provisioning stack once already. +// It now lives in PSRAM, so the only way it can come back is if someone makes +// it a stack local again — keep the size visible and bounded. +static_assert( + sizeof(ScanRecords) > 1024, + "scan record buffer is large; it must stay off the task stack"); + +bool IsBenignStopResult(esp_err_t result) +{ + return result == ESP_OK || + result == ESP_ERR_WIFI_NOT_INIT || + result == ESP_ERR_WIFI_NOT_STARTED || + result == ESP_ERR_WIFI_NOT_CONNECT || + result == ESP_ERR_INVALID_STATE; +} + +} // namespace + +bool EspWifiTransport::Start(IWifiTransportObserver& observer) +{ + portENTER_CRITICAL(&link_lock_); + observer_ = &observer; + portEXIT_CRITICAL(&link_lock_); + if (started_) { + Publish({WifiTransportEventType::kStarted, 0}); + return true; + } + + if (!InitializeDriver() || !RegisterHandlers()) { + portENTER_CRITICAL(&link_lock_); + observer_ = nullptr; + portEXIT_CRITICAL(&link_lock_); + return false; + } + + const esp_err_t result = esp_wifi_start(); + if (result != ESP_OK) { + ESP_LOGE(kTag, "esp_wifi_start failed: %s", + esp_err_to_name(result)); + UnregisterHandlers(); + portENTER_CRITICAL(&link_lock_); + observer_ = nullptr; + portEXIT_CRITICAL(&link_lock_); + return false; + } + started_ = true; + ESP_LOGI(kTag, "WiFi STA transport started"); + return true; +} + +void EspWifiTransport::Stop() +{ + portENTER_CRITICAL(&link_lock_); + observer_ = nullptr; + portEXIT_CRITICAL(&link_lock_); + if (started_) { + const esp_err_t disconnect_result = esp_wifi_disconnect(); + if (!IsBenignStopResult(disconnect_result)) { + ESP_LOGW(kTag, "esp_wifi_disconnect failed: %s", + esp_err_to_name(disconnect_result)); + } + + const esp_err_t stop_result = esp_wifi_stop(); + if (!IsBenignStopResult(stop_result)) { + ESP_LOGW(kTag, "esp_wifi_stop failed: %s", + esp_err_to_name(stop_result)); + } + started_ = false; + } + UnregisterHandlers(); + ClearLinkState(0); + ESP_LOGI(kTag, "WiFi STA transport stopped"); +} + +void EspWifiTransport::UseLowMemoryProfile(bool enabled) +{ + low_memory_profile_ = enabled; +} + +void EspWifiTransport::ReleaseDriver() +{ + if (!driver_initialized_) { + return; + } + if (started_) { + Stop(); + } + const size_t before = + heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + const esp_err_t result = esp_wifi_deinit(); + if (!IsBenignStopResult(result)) { + ESP_LOGW(kTag, "esp_wifi_deinit failed: %s", + esp_err_to_name(result)); + return; + } + // The netif is deliberately kept: esp_netif_create_default_wifi_sta() is + // not idempotent, and InitializeDriver() reuses the existing handle. + driver_initialized_ = false; + const size_t after = + heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + ESP_LOGI(kTag, + "WiFi driver released internal_free=%u (+%d) largest=%u", + static_cast(after), + static_cast(after) - static_cast(before), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL))); +} + +bool EspWifiTransport::Connect(const WifiCredential& credential) +{ + if (!started_ || !credential.IsValid()) { + return false; + } + + wifi_config_t config{}; + const size_t ssid_length = + BoundedStringLength(credential.ssid.data(), credential.ssid.size()); + const size_t password_length = + BoundedStringLength( + credential.password.data(), credential.password.size()); + std::memcpy( + config.sta.ssid, + credential.ssid.data(), + std::min(ssid_length, sizeof(config.sta.ssid))); + std::memcpy( + config.sta.password, + credential.password.data(), + std::min(password_length, sizeof(config.sta.password))); + config.sta.threshold.authmode = password_length == 0 + ? WIFI_AUTH_OPEN + : WIFI_AUTH_WPA2_PSK; + config.sta.pmf_cfg.capable = true; + config.sta.pmf_cfg.required = false; + + esp_err_t result = esp_wifi_set_config(WIFI_IF_STA, &config); + if (result != ESP_OK) { + ESP_LOGE(kTag, "set config for ssid=%s failed: %s", + credential.ssid.data(), esp_err_to_name(result)); + return false; + } + + portENTER_CRITICAL(&link_lock_); + link_info_.online = false; + link_info_.rssi_dbm = -127; + link_info_.channel = 0; + link_info_.ipv4.fill('\0'); + link_info_.ssid = credential.ssid; + portEXIT_CRITICAL(&link_lock_); + + result = esp_wifi_connect(); + if (result != ESP_OK) { + ESP_LOGW(kTag, "connect request for ssid=%s failed: %s", + credential.ssid.data(), esp_err_to_name(result)); + return false; + } + ESP_LOGI(kTag, "connecting to ssid=%s", credential.ssid.data()); + return true; +} + +bool EspWifiTransport::Scan( + WifiNetwork* output, + size_t capacity, + size_t* count) +{ + if (!started_ || output == nullptr || capacity == 0 || + count == nullptr) { + return false; + } + *count = 0; + + wifi_scan_config_t config{}; + config.scan_type = WIFI_SCAN_TYPE_ACTIVE; + config.scan_time.active.min = 80; + config.scan_time.active.max = 160; + esp_err_t result = esp_wifi_scan_start(&config, true); + if (result != ESP_OK) { + ESP_LOGE(kTag, "WiFi scan failed: %s", + esp_err_to_name(result)); + return false; + } + + // wifi_ap_record_t is ~96 bytes, so 32 of them is ~3 KB. The only caller + // is the BLE provisioning worker, whose stack also has to carry + // esp_wifi_scan_start and nimble_port_init underneath this frame — the + // array must not live on it. + auto records = MakePsramObject(); + if (!records) { + ESP_LOGE(kTag, "scan record buffer allocation failed"); + return false; + } + uint16_t record_count = + static_cast(records->size()); + result = esp_wifi_scan_get_ap_records( + &record_count, records->data()); + if (result != ESP_OK) { + ESP_LOGE(kTag, "read WiFi scan results failed: %s", + esp_err_to_name(result)); + return false; + } + + std::sort( + records->begin(), + records->begin() + record_count, + [](const wifi_ap_record_t& left, + const wifi_ap_record_t& right) { + return left.rssi > right.rssi; + }); + + for (uint16_t index = 0; + index < record_count && *count < capacity; + ++index) { + const auto& record = (*records)[index]; + const char* ssid = + reinterpret_cast(record.ssid); + const size_t ssid_length = + BoundedStringLength(ssid, sizeof(record.ssid)); + if (ssid_length == 0 || + ssid_length >= kWifiSsidCapacity) { + continue; + } + + bool duplicate = false; + for (size_t existing = 0; existing < *count; ++existing) { + if (std::strncmp( + output[existing].ssid.data(), + ssid, + kWifiSsidCapacity) == 0) { + duplicate = true; + break; + } + } + if (duplicate) { + continue; + } + + WifiNetwork& network = output[(*count)++]; + network = {}; + std::memcpy(network.ssid.data(), ssid, ssid_length); + network.rssi_dbm = record.rssi; + network.auth_mode = + static_cast(record.authmode); + } + + ESP_LOGI(kTag, "WiFi pre-scan complete raw=%u unique=%u", + static_cast(record_count), + static_cast(*count)); + return true; +} + +WifiLinkInfo EspWifiTransport::GetLinkInfo() const +{ + portENTER_CRITICAL(&link_lock_); + const WifiLinkInfo snapshot = link_info_; + portEXIT_CRITICAL(&link_lock_); + return snapshot; +} + +void EspWifiTransport::WifiEventHandler( + void* context, + esp_event_base_t, + int32_t event_id, + void* event_data) +{ + auto* self = static_cast(context); + if (event_id == WIFI_EVENT_STA_START) { + self->Publish({WifiTransportEventType::kStarted, 0}); + return; + } + if (event_id == WIFI_EVENT_STA_DISCONNECTED) { + const auto* disconnected = + static_cast(event_data); + const uint16_t reason = + disconnected == nullptr ? 0 : disconnected->reason; + self->ClearLinkState(reason); + self->Publish({WifiTransportEventType::kDisconnected, reason}); + } +} + +void EspWifiTransport::IpEventHandler( + void* context, + esp_event_base_t, + int32_t event_id, + void* event_data) +{ + if (event_id != IP_EVENT_STA_GOT_IP || event_data == nullptr) { + return; + } + + auto* self = static_cast(context); + const auto* got_ip = static_cast(event_data); + char ipv4[kWifiIpv4Capacity]{}; + esp_ip4addr_ntoa(&got_ip->ip_info.ip, ipv4, sizeof(ipv4)); + + wifi_ap_record_t access_point{}; + const esp_err_t ap_result = esp_wifi_sta_get_ap_info(&access_point); + + portENTER_CRITICAL(&self->link_lock_); + self->link_info_.online = true; + self->link_info_.ipv4.fill('\0'); + strlcpy( + self->link_info_.ipv4.data(), + ipv4, + self->link_info_.ipv4.size()); + if (ap_result == ESP_OK) { + self->link_info_.rssi_dbm = access_point.rssi; + self->link_info_.channel = access_point.primary; + } + portEXIT_CRITICAL(&self->link_lock_); + + ESP_LOGI(kTag, "DHCP ready ip=%s", ipv4); + self->Publish({WifiTransportEventType::kGotIp, 0}); +} + +bool EspWifiTransport::InitializeDriver() +{ + if (driver_initialized_) { + return true; + } + + esp_err_t result = esp_netif_init(); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { + ESP_LOGE(kTag, "esp_netif_init failed: %s", + esp_err_to_name(result)); + return false; + } + + station_netif_ = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"); + if (station_netif_ == nullptr) { + station_netif_ = esp_netif_create_default_wifi_sta(); + } + if (station_netif_ == nullptr) { + ESP_LOGE(kTag, "default WiFi STA netif creation failed"); + return false; + } + + wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); + config.nvs_enable = false; + if (low_memory_profile_) { + // Enough to associate and complete DHCP, nothing more. The static RX + // buffers dominate (10 x 1600 bytes by default) and are what actually + // ran out; AMPDU is switched off because its reorder buffers scale + // with the same pool and only buy throughput this link never uses. + // Field log with static_rx_buf_num = 4: "Expected to init 4 rx buffer, + // actual is 2" at dma_free=31019 / dma_largest=6912 — the pool is both + // small and fragmented, and the driver's own 6656-byte task stack takes + // the one usable block. Ask for the documented minimum instead; this + // link only has to associate and pull a DHCP lease. + config.static_rx_buf_num = 2; + config.dynamic_rx_buf_num = 6; + config.static_tx_buf_num = 4;//2026-9-8 ckkj add + config.dynamic_tx_buf_num = 6; + config.cache_tx_buf_num = 4;//2026-9-8 ckkj add + config.rx_mgmt_buf_num = 2; + config.mgmt_sbuf_num = 6; + config.ampdu_rx_enable = 0; + config.ampdu_tx_enable = 0; + config.rx_ba_win = 0; + } + // boot 提示音和 WiFi 驱动初始化会并发抢 DMA 内部 RAM:boot 音在 7.0-7.3s 区间瞬时吃光内部堆 + // (min=107 字节),esp_wifi_init 申请 static rx buffer 时恰好撞到峰值。 + // 在低内存配置下仅需 ~12KB (2*1600 rx + 2*~300 mgmt + 6656 task stack);完整配置 + // 要多出 4 个 static rx 和更多的静态 TX,阈值相应抬高。等到内部堆总空闲量超过 + // 阈值再进入 esp_wifi_init。最多等 3 秒,boot 音 200ms 内必然抽完。 + const size_t kWifiInitRequiredFree = + low_memory_profile_ ? 12000 : 50000; + // const size_t kWifiInitRequiredLargest = + // low_memory_profile_ ? 8000 : 32000; + constexpr uint32_t kWifiInitWaitMaxMs = 3000; + constexpr uint32_t kWifiInitPollMs = 100; + for (uint32_t waited = 0; + waited < kWifiInitWaitMaxMs; + waited += kWifiInitPollMs) { + const size_t free = + heap_caps_get_free_size(MALLOC_CAP_INTERNAL); + if (free >= kWifiInitRequiredFree) { + break; + } + vTaskDelay(pdMS_TO_TICKS(kWifiInitPollMs)); + }//2026-9-3 ckkj debug :wifi start fail + ESP_LOGI(kTag, + "WiFi driver init profile=%s internal_free=%u largest=%u", + low_memory_profile_ ? "low_memory" : "default", + static_cast( + heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL))); + + heap_caps_print_heap_info(MALLOC_CAP_INTERNAL); + result = esp_wifi_init(&config); + if (result != ESP_OK) { + ESP_LOGE(kTag, "esp_wifi_init failed: %s", + esp_err_to_name(result)); + return false; + } + driver_initialized_ = true; + + result = esp_wifi_set_storage(WIFI_STORAGE_RAM); + if (result == ESP_OK) { + result = esp_wifi_set_mode(WIFI_MODE_STA); + } + if (result == ESP_OK) { + //result = esp_wifi_set_ps(WIFI_PS_NONE);//2026-9-8 ckkj mod 省电模式 + result = esp_wifi_set_ps(WIFI_PS_MIN_MODEM); + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "WiFi STA setup failed: %s", + esp_err_to_name(result)); + return false; + } + return true; +} + +bool EspWifiTransport::RegisterHandlers() +{ + if (wifi_handler_ == nullptr) { + const esp_err_t result = esp_event_handler_instance_register( + WIFI_EVENT, + ESP_EVENT_ANY_ID, + &EspWifiTransport::WifiEventHandler, + this, + &wifi_handler_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "register WIFI_EVENT failed: %s", + esp_err_to_name(result)); + return false; + } + } + + if (ip_handler_ == nullptr) { + const esp_err_t result = esp_event_handler_instance_register( + IP_EVENT, + IP_EVENT_STA_GOT_IP, + &EspWifiTransport::IpEventHandler, + this, + &ip_handler_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "register IP_EVENT failed: %s", + esp_err_to_name(result)); + UnregisterHandlers(); + return false; + } + } + return true; +} + +void EspWifiTransport::UnregisterHandlers() +{ + if (wifi_handler_ != nullptr) { + esp_event_handler_instance_unregister( + WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_handler_); + wifi_handler_ = nullptr; + } + if (ip_handler_ != nullptr) { + esp_event_handler_instance_unregister( + IP_EVENT, IP_EVENT_STA_GOT_IP, ip_handler_); + ip_handler_ = nullptr; + } +} + +void EspWifiTransport::Publish(const WifiTransportEvent& event) +{ + portENTER_CRITICAL(&link_lock_); + IWifiTransportObserver* const observer = observer_; + portEXIT_CRITICAL(&link_lock_); + if (observer != nullptr) { + observer->OnWifiTransportEvent(event); + } +} + +void EspWifiTransport::ClearLinkState(uint16_t reason) +{ + portENTER_CRITICAL(&link_lock_); + link_info_.online = false; + link_info_.rssi_dbm = -127; + link_info_.channel = 0; + link_info_.last_disconnect_reason = reason; + link_info_.ipv4.fill('\0'); + portEXIT_CRITICAL(&link_lock_); +} + +} // namespace borla diff --git a/main/platform/borla_s3/esp_wifi_transport.h b/main/platform/borla_s3/esp_wifi_transport.h new file mode 100644 index 0000000..017e3be --- /dev/null +++ b/main/platform/borla_s3/esp_wifi_transport.h @@ -0,0 +1,58 @@ +#pragma once + +#include "connectivity/wifi_transport.h" + +#include +#include +#include +#include + +namespace borla { + +class EspWifiTransport final : public IWifiTransport { +public: + bool Start(IWifiTransportObserver& observer) override; + void Stop() override; + void ReleaseDriver() override; + void UseLowMemoryProfile(bool enabled) override; + bool Connect(const WifiCredential& credential) override; + bool Scan( + WifiNetwork* output, + size_t capacity, + size_t* count) override; + WifiLinkInfo GetLinkInfo() const override; + +private: + static void WifiEventHandler( + void* context, + esp_event_base_t event_base, + int32_t event_id, + void* event_data); + static void IpEventHandler( + void* context, + esp_event_base_t event_base, + int32_t event_id, + void* event_data); + + bool InitializeDriver(); + bool RegisterHandlers(); + void UnregisterHandlers(); + void Publish(const WifiTransportEvent& event); + void ClearLinkState(uint16_t reason); + + mutable portMUX_TYPE link_lock_ = portMUX_INITIALIZER_UNLOCKED; + WifiLinkInfo link_info_{}; + IWifiTransportObserver* observer_ = nullptr; + esp_netif_t* station_netif_ = nullptr; + esp_event_handler_instance_t wifi_handler_ = nullptr; + esp_event_handler_instance_t ip_handler_ = nullptr; + // 正常开机必须用完整缓冲配置(sdkconfig 里的 rx6/dyn8/ba8),否则 OTA + // 版本检查的 HTTPS 会打爆动态 RX 缓冲("wifi:mem fail" → HTTP write 失败)。 + // 低内存配置只用于配网时与 BT 控制器共存,由 BleProvisioningService 显式 + // 通过 UseLowMemoryProfile() 切换(HandleStart/HandleConnect/HandleStop)。 + bool low_memory_profile_ = false; + bool driver_initialized_ = false; + bool started_ = false; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/i2c_bus.cc b/main/platform/borla_s3/i2c_bus.cc new file mode 100644 index 0000000..99c616f --- /dev/null +++ b/main/platform/borla_s3/i2c_bus.cc @@ -0,0 +1,63 @@ +#include "platform/borla_s3/i2c_bus.h" + +#include "platform/borla_s3/board_config.h" + +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "BorlaI2cBus2"; + +} // namespace + +BorlaS3I2cBus::~BorlaS3I2cBus() +{ + if (handle_ != nullptr) { + i2c_del_master_bus(handle_); + } +} + +bool BorlaS3I2cBus::Initialize() +{ + if (handle_ != nullptr) { + return true; + } + + gpio_hold_dis(board_config::kAudioI2cSdaGpio); + gpio_hold_dis(board_config::kAudioI2cSclGpio); + rtc_gpio_hold_dis(board_config::kAudioI2cSdaGpio); + rtc_gpio_hold_dis(board_config::kAudioI2cSclGpio); + + const i2c_master_bus_config_t config = { + .i2c_port = I2C_NUM_0, + .sda_io_num = board_config::kAudioI2cSdaGpio, + .scl_io_num = board_config::kAudioI2cSclGpio, + .clk_source = I2C_CLK_SRC_DEFAULT, + .glitch_ignore_cnt = 7, + .intr_priority = 0, + .trans_queue_depth = 0, + .flags = { + //.enable_internal_pullup = true, + .enable_internal_pullup = false, + .allow_pd = false, + }, + }; + const esp_err_t result = i2c_new_master_bus(&config, &handle_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "bus initialization failed: %s", + esp_err_to_name(result)); + handle_ = nullptr; + return false; + } + + ESP_LOGI(kTag, "I2C0 initialized SDA=%d SCL=%d", + static_cast(board_config::kAudioI2cSdaGpio), + static_cast(board_config::kAudioI2cSclGpio)); + return true; +} + +} // namespace borla diff --git a/main/platform/borla_s3/i2c_bus.h b/main/platform/borla_s3/i2c_bus.h new file mode 100644 index 0000000..c211a5b --- /dev/null +++ b/main/platform/borla_s3/i2c_bus.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace borla { + +class BorlaS3I2cBus final { +public: + BorlaS3I2cBus() = default; + ~BorlaS3I2cBus(); + + bool Initialize(); + i2c_master_bus_handle_t Handle() const { return handle_; } + +private: + i2c_master_bus_handle_t handle_ = nullptr; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/ml307_transport.cc b/main/platform/borla_s3/ml307_transport.cc new file mode 100644 index 0000000..a0d07c8 --- /dev/null +++ b/main/platform/borla_s3/ml307_transport.cc @@ -0,0 +1,863 @@ +#include "platform/borla_s3/ml307_transport.h" + +#include "connectivity/ml307_at_parser.h" +#include "platform/borla_s3/board_config.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "Ml307Transport2"; +constexpr uint16_t kModemMissingReason = 0xF201; +constexpr uint16_t kRegistrationReason = 0xF202; +constexpr uint16_t kDialReason = 0xF203; +constexpr uint16_t kPppSetupReason = 0xF204; +constexpr uint16_t kPppLostReason = 0xF205; +// 2026-9-4 ckkj add :ML307 从上电到 AT 就绪的典型耗时,留出余量。 +constexpr uint32_t kModemPowerOnDelayMs = 3000;// +TaskHandle_t const kTaskStarting = + reinterpret_cast(1); + +} // namespace +//2026-9-4 ckkj add +void Ml307Transport::PowerOn() +{ + if (power_control_ != nullptr) { + power_control_(true); + } + // if (!powered_.exchange(true)) { + // vTaskDelay(pdMS_TO_TICKS(kModemPowerOnDelayMs)); + // } + bool was_off = !powered_.exchange(true); + // 只要模块刚被上电,就做上电延时;如果之前已经上电,跳过长延时 + if(was_off) + { + vTaskDelay(pdMS_TO_TICKS(kModemPowerOnDelayMs)); + } +} + +void Ml307Transport::PowerOff() +{ + if (powered_.exchange(false) && power_control_ != nullptr) { + power_control_(false); + } +}//////add end +bool Ml307Transport::Start(ICellularTransportObserver& observer) +{ + portENTER_CRITICAL(&state_lock_); + observer_ = &observer; + portEXIT_CRITICAL(&state_lock_); + if (task_.load() != nullptr) { + return true; + } + if (stopped_ == nullptr) { + stopped_ = xSemaphoreCreateBinaryStatic(&stopped_control_); + if (stopped_ == nullptr) { + return false; + } + } + xSemaphoreTake(stopped_, 0); + stop_requested_.store(false); + ppp_lost_.store(false); + task_.store(kTaskStarting); + TaskHandle_t handle = xTaskCreateStatic( + &Ml307Transport::TaskEntry, + "ml307_ppp2", + task_stack_.size(), + this, + 5, + task_stack_.data(), + &task_control_); + if (handle == nullptr) { + task_.store(nullptr); + return false; + } + TaskHandle_t expected = kTaskStarting; + task_.compare_exchange_strong(expected, handle); + return true; +} + +void Ml307Transport::Stop() +{ + if (task_.load() == nullptr) { + return; + } + stop_requested_.store(true); + if (stopped_ != nullptr && + xSemaphoreTake(stopped_, pdMS_TO_TICKS(5000)) != pdTRUE) { + ESP_LOGE(kTag, "timed out waiting for modem task"); + } + PowerOff();//2026-9-4 ckkj add +} + +//bool Ml307Transport::ProbePresent() +CellularProbeResult Ml307Transport::ProbePresent() +{ + if (running_.load()) { + //return true; + return CellularProbeResult::kPresent; + } + stop_requested_.store(false); + PowerOn();//2026-9-4 ckkj add + if (!InitializeUart(kProbeUartRxBufferSize, 0)) { + PowerOff();//2026-9-4 ckkj add + // return false; + // 2026-9-7 ckkj add: 开机窗口内部 RAM 紧张,探测 UART 可能装不上; + // 这不代表模块不在位,返回 kUnknown 避免污染在位状态。 + return CellularProbeResult::kUnknown; + } + bool present = false; + unsigned rx_bytes_total = 0; + uint8_t rx_first[8] = {}; + size_t rx_first_len = 0; + + for (uint8_t attempt = 0; attempt < 3 && !present; ++attempt) { + // 2026-9-17 ckkj 诊断: 传入 echo 缓冲区,把 AT 等待期内收到的原始 + // 字节(含乱码)打出来。旧实现 response=nullptr 时窗口内字节被丢弃, + // "rx=0" 只反映超时后 60ms 的统计,无法证明线上没信号。 + char echo[64] = {}; + present = SendCommand("AT", "OK", 600, echo, sizeof(echo)); + ESP_LOGI(kTag, "probe AT attempt=%u/3 ok=%d rx=%u echo=[%s]", + attempt, present, rx_bytes_total, echo); + if (!present) { + uint8_t scratch[32] = {}; + const int n = uart_read_bytes( + kUart, scratch, sizeof(scratch), pdMS_TO_TICKS(60)); + if (n > 0) { + rx_bytes_total += static_cast(n); + if (rx_first_len == 0) { + rx_first_len = std::min(static_cast(n), sizeof(rx_first)); + std::memcpy(rx_first, scratch, rx_first_len); + } + } + vTaskDelay(pdMS_TO_TICKS(500)); + } + } + if (!present) { + ESP_LOGW(kTag, + "modem silent rx=%u first=%02x %02x %02x %02x (rx=0 => no boot or TX wire dead)", + rx_bytes_total, + rx_first[0], rx_first[1], rx_first[2], rx_first[3]); + } + CleanupUart(); + // 2026-9-17 ckkj 诊断: 探测失败后暂不断电,保持 EN_4G=1,便于万用表 + // 测量模组 VBAT / TCA9555 P0.2 电平并观察 NETLIGHT;定位完成后恢复。 + // if (!present) { + // PowerOff(); + // } + if (!present) { + ESP_LOGW(kTag, "probe failed, EN_4G left ON for hardware check (diag)"); + } + portENTER_CRITICAL(&state_lock_); + link_info_.modem_present = present; + portEXIT_CRITICAL(&state_lock_); + //return present; + return present ? CellularProbeResult::kPresent: CellularProbeResult::kAbsent; +} + +CellularLinkInfo Ml307Transport::GetLinkInfo() const +{ + portENTER_CRITICAL(&state_lock_); + const CellularLinkInfo snapshot = link_info_; + portEXIT_CRITICAL(&state_lock_); + return snapshot; +} + +void Ml307Transport::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +esp_err_t Ml307Transport::Transmit( + void* handle, + void* buffer, + size_t length) +{ + auto* self = static_cast(handle); + if (self == nullptr || !self->uart_installed_) { + return ESP_FAIL; + } + const int written = uart_write_bytes( + kUart, + static_cast(buffer), + length); + // 2026-9-19 ckkj diag: 打印 PPP 发送帧前 8 字节,确认 lwIP 是否在发 LCP。 + const uint8_t* p = static_cast(buffer); + ESP_LOGI(kTag, "ppp tx len=%u %02x %02x %02x %02x %02x %02x %02x %02x", + static_cast(length), + p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);///////// + return written == static_cast(length) ? ESP_OK : ESP_FAIL; +} + +void Ml307Transport::IpEventHandler( + void* context, + esp_event_base_t, + int32_t event_id, + void* event_data) +{ + auto* self = static_cast(context); + if (self == nullptr) { + return; + } + if (event_id == IP_EVENT_PPP_GOT_IP) { + if (event_data == nullptr) { + return; + } + const auto* got_ip = + static_cast(event_data); + if (got_ip->esp_netif != self->netif_) { + return; + } + char ipv4[kCellularIpv4Capacity]{}; + esp_ip4addr_ntoa( + &got_ip->ip_info.ip, ipv4, sizeof(ipv4)); + portENTER_CRITICAL(&self->state_lock_); + self->link_info_.online = true; + self->link_info_.ipv4.fill('\0'); + // std::strncpy( + // self->link_info_.ipv4.data(), + // ipv4, + // self->link_info_.ipv4.size() - 1); + strlcpy(self->link_info_.ipv4.data(),ipv4,self->link_info_.ipv4.size()); + portEXIT_CRITICAL(&self->state_lock_); + ESP_LOGI(kTag, "PPP online ip=%s", ipv4); + self->Publish({CellularTransportEventType::kGotIp, 0}); + } else if (event_id == IP_EVENT_PPP_LOST_IP) { + self->ppp_lost_.store(true); + } +} + +void Ml307Transport::Run() +{ + running_.store(true); + PowerOn();//2026-9-4 ckkj add + uint16_t failure = 0; + //2026-9-6 ckkj add: PPP 环形缓冲需要内部 RAM 最大连续块,切网时 WiFi + //资源异步释放中,install 可能 malloc 失败;等待重试,并随重试次数逐级 + //降档缓冲:115200 波特率下 1024B 环形缓冲仍可缓冲 ~89ms,保证 WiFi + //卸载后任意 ≥1KB 连续块都能完成安装。 + bool uart_ready = false; + for (uint8_t attempt = 0;attempt < 6 && !uart_ready && !stop_requested_.load();++attempt) { + const size_t rx_bytes = (attempt < 2) ? kPppUartRxBufferSize: (attempt < 4) ? 2048U : 1024U; + uart_ready = InitializeUart(rx_bytes, rx_bytes / 2); + if (!uart_ready) { + ESP_LOGW(kTag, "PPP uart install retry=%u/6 rx=%u (waiting wifi teardown memory)",static_cast(attempt + 1),static_cast(rx_bytes)); + vTaskDelay(pdMS_TO_TICKS(800)); + } + } + // if (!uart_ready || !DetectAndConfigure()) { + // failure = kModemMissingReason; + // } else { + // Publish({CellularTransportEventType::kStarted, 0}); + // if (!WaitForRegistration()) { + // failure = kRegistrationReason; + // } else if (!Dial()) { + // failure = kDialReason; + // } else if (!CreatePppNetif()) { + // failure = kPppSetupReason; + // } else { + //2026-9-7 ckkj add: 注网/拨号阶段成功时静默,排障无法定位卡点,补充阶段日志 + if (uart_ready) { + ESP_LOGI(kTag, "ppp uart installed"); + } + if (!uart_ready || !DetectAndConfigure()) { + failure = kModemMissingReason; + } else { + ESP_LOGI(kTag, "modem configured, waiting registration"); + Publish({CellularTransportEventType::kStarted, 0}); + if (!WaitForRegistration()) { + ESP_LOGW(kTag, "registration failed"); + failure = kRegistrationReason; + } else if (!Dial()) { + ESP_LOGW(kTag, "dial failed"); + failure = kDialReason; + //} else if (!CreatePppNetif()) { + } else { + // 2026-9-19 ckkj fix: CGDATA OK 后模组需要时间从 AT 模式切换到 + // PPP 数据模式。立即发送 LCP 可能被模组当作 AT 命令丢弃。 + vTaskDelay(pdMS_TO_TICKS(1000)); + if (!CreatePppNetif()) { + ESP_LOGW(kTag, "ppp netif create failed"); + failure = kPppSetupReason; + } else { + RunPpp(); + if (ppp_lost_.load() && !stop_requested_.load()) { + failure = kPppLostReason; + } + } + } + } + + CleanupPpp(); + CleanupUart(); + const bool explicit_stop = stop_requested_.load(); + running_.store(false); + task_.store(nullptr); + if (!explicit_stop) { + if (failure != 0) { + ESP_LOGE(kTag, "modem task failed reason=0x%04x", failure); + } + SetDisconnected(failure == 0 ? kPppLostReason : failure); + } + if (stopped_ != nullptr) { + xSemaphoreGive(stopped_); + } + vTaskDelete(nullptr); +} + +bool Ml307Transport::InitializeUart( + size_t rx_buffer_size, + size_t tx_buffer_size) +{ + if (uart_installed_) { + return true; + } + //2026-8-25 ckkj add for warning + gpio_reset_pin(board_config::kMl307TxGpio); + gpio_reset_pin(board_config::kMl307RxGpio); + //end + const esp_err_t install = uart_driver_install( + kUart, + rx_buffer_size, + tx_buffer_size, + 0, + nullptr, + ESP_INTR_FLAG_IRAM); + if (install != ESP_OK) { + ESP_LOGW(kTag, "UART install failed: %s", + esp_err_to_name(install)); + return false; + } + uart_config_t config{}; + config.baud_rate = board_config::kMl307BaudRate; + config.data_bits = UART_DATA_8_BITS; + config.parity = UART_PARITY_DISABLE; + config.stop_bits = UART_STOP_BITS_1; + config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE; + config.source_clk = UART_SCLK_DEFAULT; + const esp_err_t configured = uart_param_config(kUart, &config); + const esp_err_t pins = configured == ESP_OK + ? uart_set_pin( + kUart, + board_config::kMl307TxGpio, + board_config::kMl307RxGpio, + UART_PIN_NO_CHANGE, + UART_PIN_NO_CHANGE) + : ESP_FAIL; + if (configured != ESP_OK || pins != ESP_OK) { + ESP_LOGE(kTag, "UART setup failed config=%s pins=%s", + esp_err_to_name(configured), esp_err_to_name(pins)); + uart_driver_delete(kUart); + return false; + } + uart_set_rx_timeout(kUart, 2); + uart_installed_ = true; + ESP_LOGI(kTag, "ppp uart installed rx=%u",static_cast(rx_buffer_size)); + return true; +} + +void Ml307Transport::CleanupUart() +{ + if (uart_installed_) { + uart_driver_delete(kUart); + uart_installed_ = false; + } +} + +bool Ml307Transport::DetectAndConfigure() +{ + bool detected = false; + for (uint8_t attempt = 0; + attempt < 3 && !detected && !stop_requested_.load(); + ++attempt) { + detected = SendCommand("AT", "OK", 800); + } + if (!detected) { + ESP_LOGE(kTag, "modem silent 30s: not booted / baud mismatch / TX wire dead"); + return false; + } + portENTER_CRITICAL(&state_lock_); + link_info_ = {}; + link_info_.modem_present = true; + portEXIT_CRITICAL(&state_lock_); + // 硬件未连 RTS/CTS 导致模组 PPP 帧完全静默(ppp rx=0)。 + // 2026-9-19 ckkj diag: 打印关键 AT 命令响应,确认模组是否接受流控/DTR 设置。 + std::array diag{}; + bool ifc_ok = SendCommand("AT+IFC=0,0", "OK", 1000, diag.data(), diag.size()); + ESP_LOGI(kTag, "AT+IFC=0,0 ok=%d resp=%s", ifc_ok ? 1 : 0, diag.data()); + // AT&D0: 忽略 DTR 信号(硬件未连 DTR,否则模组可能不发送 PPP 数据) + bool d0_ok = SendCommand("AT&D0", "OK", 1000, diag.data(), diag.size()); + ESP_LOGI(kTag, "AT&D0 ok=%d resp=%s", d0_ok ? 1 : 0, diag.data()); + // AT&C0: DCD 始终有效 + bool c0_ok = SendCommand("AT&C0", "OK", 1000, diag.data(), diag.size()); + ESP_LOGI(kTag, "AT&C0 ok=%d resp=%s", c0_ok ? 1 : 0, diag.data()); + + // 2026-9-20 ckkj: 启用详细错误码,否则ATD失败只返回裸ERROR无法诊断。 + bool cmee_ok = SendCommand("AT+CMEE=2", "OK", 1000, diag.data(), diag.size()); + ESP_LOGI(kTag, "AT+CMEE=2 ok=%d resp=%s", cmee_ok ? 1 : 0, diag.data()); + + SendCommand("ATE0", "OK", 1000); + SendCommand("AT+CMEE=2", "OK", 1000); + SendCommand("AT+CFUN=1", "OK", 5000); + SendCommand("AT+CEREG=2", "OK", 1000); + UpdateModemInformation(); + return true; +} + +bool Ml307Transport::WaitForRegistration() +{ + std::array response{}; + for (uint8_t attempt = 0;attempt < 30 && !stop_requested_.load();++attempt) { + // if (SendCommand("AT+CPIN?", "READY", 1500, response.data(), response.size()) && + // SendCommand("AT+CEREG?", "+CEREG:", 1500,response.data(), response.size())) + const bool sim_ready = SendCommand("AT+CPIN?", "READY", 1500,response.data(), response.size()); + ESP_LOGI(kTag, "registration poll %u/30 sim=%d resp=%s",static_cast(attempt + 1),sim_ready ? 1 : 0, response.data()); + if (sim_ready && SendCommand("AT+CEREG?", "+CEREG:", 1500,response.data(), response.size())) + { + ESP_LOGI(kTag, "registration poll %u/30 cereg=%s",static_cast(attempt + 1),response.data()); + CellularRegistration registration; + if (ParseMl307Registration(response.data(), ®istration)) { + portENTER_CRITICAL(&state_lock_); + link_info_.registration_status = registration.status; + link_info_.registered = registration.IsRegistered(); + portEXIT_CRITICAL(&state_lock_); + if (registration.IsRegistered()) { + UpdateModemInformation(); + return true; + } + if (registration.status == 3) { + ESP_LOGW(kTag, "registration denied (CEREG stat=3)"); + return false; + } + } + } + //2026-9-7 ckkj add: 注网轮询进度,打印原始 CEREG 响应便于定位 + ESP_LOGI(kTag, "registration poll attempt=%u/30 resp=%s", + static_cast(attempt + 1), response.data()); + vTaskDelay(pdMS_TO_TICKS(2000)); + } + return false; +} +/* +bool Ml307Transport::Dial() +{ + // 2026-9-7 ckkj add: 合并为单个 response buffer 复用,避免 4 个 + // std::array 撑爆 ml307_ppp2 任务的 4KB 栈(Dial 自身栈帧 + // 从 2048B 降回 512B)。每步执行前重置保证日志不残留上一步内容。 + std::array response{}; + + char command[128]{}; + const int length = std::snprintf( + command, + sizeof(command), + "AT+CGDCONT=1,\"IP\",\"%s\"", + CONFIG_BORLA_ML307_APN); + const bool ctx_ok = + length > 0 && length < static_cast(sizeof(command)) && + SendCommand(command, "OK", 3000, + response.data(), response.size()); + ESP_LOGI(kTag, "cgdcont cid=1 apn=%s ok=%d resp=%s", + CONFIG_BORLA_ML307_APN, ctx_ok ? 1 : 0, response.data()); + if (!ctx_ok) { + return false; + } + // 2. 检查PS域附着状态 + response.fill('\0'); + if (!SendCommand("AT+CGATT?", "+CGATT", 2000, response.data(), response.size())) + { + ESP_LOGW(kTag, "AT+CGATT? query fail"); + return false; + } + ESP_LOGI(kTag, "cgatt check resp=%s", response.data()); + // 3. 2026-9-19 ckkj: 不再预激活PDP上下文。实测"CGACT预激活+CGDATA拨号" + // 组合使ML307卡在中间态:OK已回但不发CONNECT、不跑PPP、ATD/ATH全ERROR。 + // 标准做法是让拨号命令自行触发激活,激活结果由CEER与PPP协商体现。 + + // 4. 预检PDP状态 + response.fill('\0'); + SendCommand("AT+CGDCONT?", "+CGDCONT", 2000, + response.data(), response.size()); + ESP_LOGI(kTag, "cgdcont query resp=%s", response.data()); + response.fill('\0'); + SendCommand("AT+CGACT?", "+CGACT", 2000, + response.data(), response.size()); + ESP_LOGI(kTag, "cgact query resp=%s", response.data()); + + + std::array probe{}; + bool dialed = false; + + // 主路径:ATD*99#(隐式cid=1) + probe.fill('\0'); + dialed = SendCommand("ATD*99#", "CONNECT", 30000, + probe.data(), probe.size()); + ESP_LOGI(kTag, "ATD*99# ret=%d resp=[%s]", + dialed ? 1 : 0, probe.data()); + + + if (!dialed) { + probe.fill('\0'); + dialed = SendCommand("ATD*99***1#", "CONNECT", 30000, + probe.data(), probe.size()); + ESP_LOGI(kTag, "ATD*99***1# ret=%d resp=[%s]", + dialed ? 1 : 0, probe.data()); + } + + if (!dialed) { + ESP_LOGE(kTag, "all dial attempts failed, hard power cycle modem"); + PowerOff(); + vTaskDelay(pdMS_TO_TICKS(2000)); + PowerOn(); + return false; + } + + ESP_LOGI(kTag, "dial accepted, observing PPP data stream"); + // 数据模式观察窗:等HDLC标志帧0x7e(PPP LCP起始)。ATD的CONNECT已 + // 证明状态机切换成功,此时静默只能是硬件层(TX 4.3V电平/供电)问题。 + bool saw_bytes = false; + for (int i = 0; i < 150 && !saw_bytes && !stop_requested_.load(); ++i) { + uint8_t scratch[64] = {}; + const int n = uart_read_bytes( + kUart, scratch, sizeof(scratch), pdMS_TO_TICKS(100)); + if (n > 0) { + saw_bytes = true; + ESP_LOGI(kTag, "data-mode first rx=%d %02x %02x %02x %02x", + n, scratch[0], scratch[1], scratch[2], scratch[3]); + } + } + if (!saw_bytes) { + ESP_LOGE(kTag, + "dial returned CONNECT but no PPP bytes: " + "check ML307 TX 4.3V level / power supply"); + PowerOff(); + vTaskDelay(pdMS_TO_TICKS(2000)); + PowerOn(); + return false; + } + + return true; +} +*/ +bool Ml307Transport::Dial() +{ + std::array response{}; + char command[128]{}; + const int length = std::snprintf( + command, + sizeof(command), + "AT+CGDCONT=1,\"IP\",\"%s\"", + CONFIG_BORLA_ML307_APN); + const bool ctx_ok = + length > 0 && length < static_cast(sizeof(command)) && + SendCommand(command, "OK", 3000, + response.data(), response.size()); + ESP_LOGI(kTag, "cgdcont cid=1 apn=%s ok=%d resp=%s", + CONFIG_BORLA_ML307_APN, ctx_ok ? 1 : 0, response.data()); + if (!ctx_ok) { + return false; + } + + response.fill('\0'); + if (!SendCommand("AT+CGATT?", "+CGATT", 2000, response.data(), response.size())) + { + ESP_LOGW(kTag, "AT+CGATT? query fail"); + return false; + } + ESP_LOGI(kTag, "cgatt check resp=%s", response.data()); + + response.fill('\0'); + SendCommand("AT+CGDCONT?", "+CGDCONT", 2000, + response.data(), response.size()); + ESP_LOGI(kTag, "cgdcont query resp=%s", response.data()); + response.fill('\0'); + SendCommand("AT+CGACT?", "+CGACT", 2000, + response.data(), response.size()); + ESP_LOGI(kTag, "cgact query resp=%s", response.data()); + + std::array probe{}; + bool dialed = false; + bool used_cgdata_fallback = false; + + // 路径1: ATD拨号 + probe.fill('\0'); + dialed = SendCommand("ATD*99#", "CONNECT", 30000, + probe.data(), probe.size()); + ESP_LOGI(kTag, "ATD*99# ret=%d resp=[%s]", + dialed ? 1 : 0, probe.data()); + if (!dialed) { + probe.fill('\0'); + dialed = SendCommand("ATD*99***1#", "CONNECT", 30000, + probe.data(), probe.size()); + ESP_LOGI(kTag, "ATD*99***1# ret=%d resp=[%s]", + dialed ? 1 : 0, probe.data()); + } + + // ATD全部失败 → 切换CGDATA fallback + if (!dialed) + { + ESP_LOGW(kTag, "ATD commands rejected by modem, fallback to AT+CGDATA"); + used_cgdata_fallback = true; + probe.fill('\0'); + // CGDATA命令:不等待CONNECT,只等待OK + dialed = SendCommand("AT+CGDATA=\"PPP\",1", "OK", 15000, + probe.data(), probe.size()); + ESP_LOGI(kTag, "AT+CGDATA=\"PPP\",1 ret=%d resp=[%s]", + dialed ? 1 : 0, probe.data()); + if(!dialed) + { + ESP_LOGE(kTag, "ATD and CGDATA both failed, hard power cycle modem"); + PowerOff(); + vTaskDelay(pdMS_TO_TICKS(2000)); + PowerOn(); + return false; + } + } + + ESP_LOGI(kTag, "dial accepted (%s path), observing PPP data stream", + used_cgdata_fallback ? "CGDATA" : "ATD"); + + bool saw_bytes = false; + for (int i = 0; i < 150 && !saw_bytes && !stop_requested_.load(); ++i) { + uint8_t scratch[64] = {}; + const int n = uart_read_bytes( + kUart, scratch, sizeof(scratch), pdMS_TO_TICKS(100)); + if (n > 0) { + saw_bytes = true; + ESP_LOGI(kTag, "data-mode first rx=%d %02x %02x %02x %02x", + n, scratch[0], scratch[1], scratch[2], scratch[3]); + } + } + + if (!saw_bytes) { + ESP_LOGE(kTag, + "dial returned ok but no PPP bytes: " + "check ML307 TX 4.3V level / power supply"); + + // 尝试 +++ 退出PPP数据模式,再复位 + ESP_LOGI(kTag, "try send +++ to escape ppp data mode"); + uart_flush_input(kUart); + vTaskDelay(pdMS_TO_TICKS(1000)); // 静默至少1s,+++时序硬性要求 + uart_write_bytes(kUart, "+++", 3); + uart_wait_tx_done(kUart, pdMS_TO_TICKS(500)); + vTaskDelay(pdMS_TO_TICKS(500)); + + // 丢弃逃逸期间收到的二进制垃圾 + uint8_t trash[128]; + uart_read_bytes(kUart, trash, sizeof(trash), pdMS_TO_TICKS(200)); + + ESP_LOGI(kTag, "escape done, power‑cycle modem"); + PowerOff(); + vTaskDelay(pdMS_TO_TICKS(2000)); + PowerOn(); + return false; + } + + return true; +} + +bool Ml307Transport::CreatePppNetif() +{ + esp_netif_inherent_config_t base = + ESP_NETIF_INHERENT_DEFAULT_PPP(); + base.if_desc = "ml307_ppp"; + base.route_prio = 20; + driver_config_ = {}; + driver_config_.handle = this; + driver_config_.transmit = &Ml307Transport::Transmit; + const esp_netif_config_t config = { + .base = &base, + .driver = &driver_config_, + .stack = ESP_NETIF_NETSTACK_DEFAULT_PPP, + }; + + netif_ = esp_netif_new(&config); + if (netif_ == nullptr) { + return false; + } + if (esp_event_handler_instance_register( + IP_EVENT, + ESP_EVENT_ANY_ID, + &Ml307Transport::IpEventHandler, + this, + &ip_handler_) != ESP_OK) { + esp_netif_destroy(netif_); + netif_ = nullptr; + return false; + } + esp_netif_action_start(netif_, nullptr, 0, nullptr); + esp_netif_action_connected(netif_, nullptr, 0, nullptr); + return true; +} + +void Ml307Transport::RunPpp() +{ + ESP_LOGI(kTag,"RunPpp PPP main loop enter"); + esp_err_t ret=0; + while (!stop_requested_.load() && !ppp_lost_.load()) { + const int received = uart_read_bytes( + kUart, + ppp_buffer_.data(), + ppp_buffer_.size(), + pdMS_TO_TICKS(100)); + + if (received > 0 && netif_ != nullptr) { + // 2026-9-19 ckkj diag: 打印 PPP 接收帧前 8 字节,确认模组是否回包。 + ESP_LOGI(kTag, "ppp rx len=%d %02x %02x %02x %02x %02x %02x %02x %02x", + received, + ppp_buffer_[0], ppp_buffer_[1], ppp_buffer_[2], ppp_buffer_[3], + ppp_buffer_[4], ppp_buffer_[5], ppp_buffer_[6], ppp_buffer_[7]);///// + ret=esp_netif_receive( + netif_, + ppp_buffer_.data(), + static_cast(received), + nullptr); + if (ret != ESP_OK) { + //ppp_lost_.store(true); + ESP_LOGW(kTag,"esp_netif_receive ret=%s drop frame",esp_err_to_name(ret)); + } + } + } + ESP_LOGI(kTag,"RunPpp PPP main loop exit stop_req=%d ppp_lost=%d", + stop_requested_.load(),ppp_lost_.load()); +} + +void Ml307Transport::CleanupPpp() +{ + if (netif_ != nullptr) { + esp_netif_action_disconnected(netif_, nullptr, 0, nullptr); + esp_netif_action_stop(netif_, nullptr, 0, nullptr); + } + if (ip_handler_ != nullptr) { + esp_event_handler_instance_unregister( + IP_EVENT, ESP_EVENT_ANY_ID, ip_handler_); + ip_handler_ = nullptr; + } + if (netif_ != nullptr) { + esp_netif_destroy(netif_); + netif_ = nullptr; + } + portENTER_CRITICAL(&state_lock_); + link_info_.online = false; + link_info_.ipv4.fill('\0'); + portEXIT_CRITICAL(&state_lock_); +} + +bool Ml307Transport::SendCommand( + const char* command, + const char* expected, + uint32_t timeout_ms, + char* response, + size_t response_capacity) +{ + if (!uart_installed_ || command == nullptr || expected == nullptr) { + return false; + } + uart_flush_input(kUart); + char outgoing[160]{}; + const int outgoing_size = + std::snprintf(outgoing, sizeof(outgoing), "%s\r\n", command); + if (outgoing_size <= 0 || + outgoing_size >= static_cast(sizeof(outgoing)) || + uart_write_bytes(kUart, outgoing, outgoing_size) != outgoing_size || + uart_wait_tx_done(kUart, pdMS_TO_TICKS(500)) != ESP_OK) { + return false; + } + + std::array local{}; + size_t used = 0; + uint32_t waited = 0; + while (waited < timeout_ms && !stop_requested_.load()) { + const uint32_t slice = std::min(100, timeout_ms - waited); + const int received = uart_read_bytes( + kUart, + reinterpret_cast(local.data() + used), + local.size() - used - 1, + pdMS_TO_TICKS(slice)); + waited += slice; + if (received > 0) { + used += static_cast(received); + local[used] = '\0'; + if (std::strstr(local.data(), expected) != nullptr) { + if (response != nullptr && response_capacity > 0) { + std::strncpy( + response, local.data(), response_capacity - 1); + response[response_capacity - 1] = '\0'; + } + return true; + } + if (std::strstr(local.data(), "ERROR") != nullptr || + used + 1 >= local.size()) { + break; + } + } + } + if (response != nullptr && response_capacity > 0) { + std::strncpy(response, local.data(), response_capacity - 1); + response[response_capacity - 1] = '\0'; + } + return false; +} + +void Ml307Transport::UpdateModemInformation() +{ + std::array response{}; + CellularLinkInfo next = GetLinkInfo(); + if (SendCommand( + "AT+CSQ", "+CSQ:", 1200, + response.data(), response.size())) { + ParseMl307SignalQuality(response.data(), &next.csq); + } + if (SendCommand( + "AT+CGSN", "OK", 1200, + response.data(), response.size())) { + CopyMl307ResponseLine( + response.data(), "", + next.imei.data(), next.imei.size()); + } + if (SendCommand( + "AT+COPS?", "+COPS:", 1500, + response.data(), response.size())) { + const char* quote = std::strchr(response.data(), '"'); + if (quote != nullptr) { + CopyMl307ResponseLine( + quote, "", + next.operator_name.data(), + next.operator_name.size()); + } + } + portENTER_CRITICAL(&state_lock_); + link_info_ = next; + portEXIT_CRITICAL(&state_lock_); +} + +void Ml307Transport::Publish( + const CellularTransportEvent& event) +{ + portENTER_CRITICAL(&state_lock_); + ICellularTransportObserver* const observer = observer_; + portEXIT_CRITICAL(&state_lock_); + if (observer != nullptr) { + observer->OnCellularTransportEvent(event); + } +} + +void Ml307Transport::SetDisconnected(uint16_t reason) +{ + portENTER_CRITICAL(&state_lock_); + link_info_.online = false; + link_info_.ipv4.fill('\0'); + portEXIT_CRITICAL(&state_lock_); + Publish({CellularTransportEventType::kDisconnected, reason}); +} + +} // namespace borla diff --git a/main/platform/borla_s3/ml307_transport.h b/main/platform/borla_s3/ml307_transport.h new file mode 100644 index 0000000..5cbd94f --- /dev/null +++ b/main/platform/borla_s3/ml307_transport.h @@ -0,0 +1,93 @@ +#pragma once + +#include "connectivity/cellular_transport.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace borla { + +class Ml307Transport final : public ICellularTransport { +public: + // 2026-9-4 ckkj add 注入模组供电开关(EN_4G);nullptr 表示模组常供电。 + void SetPowerControl(std::function control) + { + power_control_ = std::move(control); + }///// + bool Start(ICellularTransportObserver& observer) override; + void Stop() override; + //bool ProbePresent() override; + CellularProbeResult ProbePresent() override; + CellularLinkInfo GetLinkInfo() const override; + +private: + static constexpr uart_port_t kUart = UART_NUM_1; + static constexpr uint32_t kTaskStackDepth = 4096; + static constexpr size_t kAtResponseCapacity = 256;//512; + static constexpr size_t kPppReadBufferSize = 1536; + static constexpr size_t kProbeUartRxBufferSize = 512; + static constexpr size_t kPppUartRxBufferSize = 4096; + static constexpr size_t kPppUartTxBufferSize = 2048; + + static void TaskEntry(void* context); + static esp_err_t Transmit( + void* handle, + void* buffer, + size_t length); + static void IpEventHandler( + void* context, + esp_event_base_t event_base, + int32_t event_id, + void* event_data); + + void Run(); + void PowerOn(); + void PowerOff();///2026-9-4 ckkj add + bool InitializeUart(size_t rx_buffer_size, size_t tx_buffer_size); + void CleanupUart(); + bool DetectAndConfigure(); + bool WaitForRegistration(); + bool Dial(); + bool CreatePppNetif(); + void RunPpp(); + void CleanupPpp(); + bool SendCommand( + const char* command, + const char* expected, + uint32_t timeout_ms, + char* response = nullptr, + size_t response_capacity = 0); + void UpdateModemInformation(); + void Publish(const CellularTransportEvent& event); + void SetDisconnected(uint16_t reason); + + mutable portMUX_TYPE state_lock_ = portMUX_INITIALIZER_UNLOCKED; + ICellularTransportObserver* observer_ = nullptr; + CellularLinkInfo link_info_{}; + std::atomic stop_requested_{false}; + std::atomic running_{false}; + std::atomic ppp_lost_{false}; + std::atomic task_{nullptr}; + std::function power_control_;//2026-9-4 ckkj add + std::atomic powered_{false};//2026-9-4 ckkj add 模组是否供电 + StaticTask_t task_control_{}; + std::array task_stack_{}; + SemaphoreHandle_t stopped_ = nullptr; + StaticSemaphore_t stopped_control_{}; + + esp_netif_t* netif_ = nullptr; + esp_event_handler_instance_t ip_handler_ = nullptr; + esp_netif_driver_ifconfig_t driver_config_{}; + bool uart_installed_ = false; + std::array ppp_buffer_{}; +}; + +} // namespace borla diff --git a/main/platform/borla_s3/tca9555.cc b/main/platform/borla_s3/tca9555.cc new file mode 100644 index 0000000..d9b655a --- /dev/null +++ b/main/platform/borla_s3/tca9555.cc @@ -0,0 +1,244 @@ +#include "platform/borla_s3/tca9555.h" +#include "platform/borla_s3/i2c_bus.h" +#include +#include + +namespace borla { +namespace { +constexpr const char* kTag = "TCA9555"; + +} + +TCA9555::TCA9555(BorlaS3I2cBus& bus): bus_ref_(bus) +{} + +esp_err_t TCA9555::Init() +{ + i2c_mtx_ = xSemaphoreCreateMutex(); + if(i2c_mtx_ == nullptr){ + ESP_LOGE(kTag, "create mutex fail"); + return ESP_ERR_NO_MEM; + } + + bus_ = bus_ref_.Handle(); + if (!bus_) { + ESP_LOGE(kTag, "I2C bus handle null"); + return ESP_ERR_INVALID_ARG; + } + + // 挂载TCA设备到I2C总线 + i2c_device_config_t dev_cfg = { + .dev_addr_length = I2C_ADDR_BIT_LEN_7, + .device_address = TCA9555_ADDR, + .scl_speed_hz = 100000, + .scl_wait_us = 0, // 使用驱动默认超时 + .flags={.disable_ack_check=0}, // 开启ACK校验(推荐默认) + }; + esp_err_t ret = i2c_master_bus_add_device(bus_, &dev_cfg, &dev_handle_); + if(ret != ESP_OK) + { + ESP_LOGE(kTag, "TCA9555 add iic fail"); + // i2c_del_master_bus(bus_); + // bus_ = nullptr; + return ret; + } + + // 3. 配置Port0方向:P0.0~P0.7全部设为输出(bit=0输出) + // LEDA(0), SC_RESET(1), ADD_IO(2), OV_RESET(3), FLASH(6), PWDN(7) + ret = write_reg(TCA9555_REG_CFG0, 0x00); + if(ret != ESP_OK) { + ESP_LOGI(kTag, "SDA(GPIO%d)=%d SCL(GPIO%d)=%d (1=high/normal, 0=low/bad)", + TCA_SDA_GPIO, gpio_get_level(TCA_SDA_GPIO), + TCA_SCL_GPIO, gpio_get_level(TCA_SCL_GPIO)); + return ret; + } + + // 4. 配置Port1方向:仅KEY(P1.0)为输入(bit=1),P1.1~P1.7全部输出(bit=0) + // KEY(0,输入), MCU_VCC(2), 5V_EN(3), PREP_VCC(5), IMU_INT(6), PA_CTL(7) + ret = write_reg(TCA9555_REG_CFG1, (1U << TCA_P1_KEY));// | (1U << TCA_P1_IMU_INT)); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "CFG1 write fail: %s", esp_err_to_name(ret)); + return ret; + } + + // 5. 极性反转寄存器清零(不反转) + write_reg(TCA9555_REG_POL0, 0x00); + write_reg(TCA9555_REG_POL1, 0x00); + + // 6. 输出寄存器清零,并检查返回值 + ret = p0_write_all(0x00); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "OUT0 write fail: %s", esp_err_to_name(ret)); + return ret; + } + ret = p1_write_all(0x00); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "OUT1 write fail: %s", esp_err_to_name(ret)); + return ret; + } + + ESP_LOGI(kTag, "TCA9555 addr 0x%02x init ok", TCA9555_ADDR); + return ESP_OK; +} + +// 底层写寄存器 +esp_err_t TCA9555::write_reg(uint8_t reg, uint8_t data) +{ + if (dev_handle_ == nullptr || i2c_mtx_ == nullptr) { + return ESP_ERR_INVALID_STATE; + } + if(xSemaphoreTake(i2c_mtx_, pdMS_TO_TICKS(100)) != pdTRUE) + { + return ESP_ERR_TIMEOUT; + } + uint8_t buf[2] = {reg, data}; + esp_err_t ret = i2c_master_transmit(dev_handle_, buf, sizeof(buf), pdMS_TO_TICKS(100)); + xSemaphoreGive(i2c_mtx_); + return ret; +} + +// 底层读寄存器 +esp_err_t TCA9555::read_reg(uint8_t reg, uint8_t* data) +{ + if (dev_handle_ == nullptr || i2c_mtx_ == nullptr) { + return ESP_ERR_INVALID_STATE; + } + if(xSemaphoreTake(i2c_mtx_, pdMS_TO_TICKS(100)) != pdTRUE) + { + return ESP_ERR_TIMEOUT; + } + uint8_t buf = reg; + esp_err_t ret = i2c_master_transmit_receive(dev_handle_, &buf, 1, data, 1, pdMS_TO_TICKS(100)); + xSemaphoreGive(i2c_mtx_); + return ret; +} + +esp_err_t TCA9555::deinit(void) +{ + if(dev_handle_) + { + i2c_master_bus_rm_device(dev_handle_); + dev_handle_ = nullptr; + } + if(i2c_mtx_) + { + vSemaphoreDelete(i2c_mtx_); + i2c_mtx_ = nullptr; + } + bus_ = nullptr; + return ESP_OK; +} + +// Port0 置1 +esp_err_t TCA9555::p0_set_bit(uint8_t bit) +{ + if(bit >= 8) return ESP_ERR_INVALID_ARG; + uint8_t val; + esp_err_t ret = read_reg(TCA9555_REG_OUT0, &val); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "p0_set_bit read OUT0 fail: %s", esp_err_to_name(ret)); + return ret; + } + val |= (1U << bit); + return write_reg(TCA9555_REG_OUT0, val); +} +// Port0 清0 +esp_err_t TCA9555::p0_clr_bit(uint8_t bit) +{ + if(bit >= 8) return ESP_ERR_INVALID_ARG; + uint8_t val; + esp_err_t ret = read_reg(TCA9555_REG_OUT0, &val); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "p0_clr_bit read OUT0 fail: %s", esp_err_to_name(ret)); + return ret; + } + val &= ~(1U << bit); + return write_reg(TCA9555_REG_OUT0, val); +} +esp_err_t TCA9555::p0_write_all(uint8_t val) +{ + return write_reg(TCA9555_REG_OUT0, val); +} + +// Port1 置1 +esp_err_t TCA9555::p1_set_bit(uint8_t bit) +{ + if(bit >= 8) return ESP_ERR_INVALID_ARG; + uint8_t val = 0; + esp_err_t ret = read_reg(TCA9555_REG_OUT1, &val); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "p1_set_bit(%u) read OUT1 fail: %s", bit, esp_err_to_name(ret)); + return ret; + } + const uint8_t old_val = val; + val |= (1U << bit); + ret = write_reg(TCA9555_REG_OUT1, val); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "p1_set_bit(%u) write OUT1 fail: %s", bit, esp_err_to_name(ret)); + return ret; + } + + uint8_t verify = 0; + if (read_reg(TCA9555_REG_OUT1, &verify) == ESP_OK && + (verify & (1U << bit)) == 0) { + ESP_LOGE(kTag, "p1_set_bit(%u) verify FAIL: wrote 0x%02x read 0x%02x " + "(bit may be input in CFG1)", bit, val, verify); + return ESP_FAIL; + } + ESP_LOGI(kTag, "p1_set_bit(%u) OK OUT1 0x%02x->0x%02x", bit, old_val, verify); + return ESP_OK; +} +// Port1 清0 +esp_err_t TCA9555::p1_clr_bit(uint8_t bit) +{ + if(bit >= 8) return ESP_ERR_INVALID_ARG; + uint8_t val; + + esp_err_t ret = read_reg(TCA9555_REG_OUT1, &val); + if(ret != ESP_OK) { + ESP_LOGE(kTag, "p1_clr_bit read OUT1 fail: %s", esp_err_to_name(ret)); + return ret; + } + val &= ~(1U << bit); + return write_reg(TCA9555_REG_OUT1, val); +} +esp_err_t TCA9555::p1_write_all(uint8_t val) +{ + return write_reg(TCA9555_REG_OUT1, val); +} + +esp_err_t TCA9555::read_p0_input(uint8_t* val) +{ + if(val == nullptr) return ESP_ERR_INVALID_ARG; + return read_reg(TCA9555_REG_IN0, val); +} +esp_err_t TCA9555::read_p1_input(uint8_t* val) +{ + if(val == nullptr) return ESP_ERR_INVALID_ARG; + return read_reg(TCA9555_REG_IN1, val); +} + +esp_err_t TCA9555::set_pin(uint16_t pin_code) +{ + uint8_t port = TCA_GET_PORT(pin_code);//static_cast((pin_code >> 8) & 0xFFU); + uint8_t bit = TCA_GET_BIT(pin_code);//static_cast(pin_code & 0xFFU); + if(port == 0) + return p0_set_bit(bit); + else if(port == 1) + return p1_set_bit(bit); + return ESP_ERR_INVALID_ARG; +} + +esp_err_t TCA9555::clr_pin(uint16_t pin_code) +{ + uint8_t port = TCA_GET_PORT(pin_code); + uint8_t bit = TCA_GET_BIT(pin_code); + if(port == 0) + return p0_clr_bit(bit); + else if(port == 1) + return p1_clr_bit(bit); + return ESP_ERR_INVALID_ARG; +} + + +} // borla \ No newline at end of file diff --git a/main/platform/borla_s3/tca9555.h b/main/platform/borla_s3/tca9555.h new file mode 100644 index 0000000..af81fe7 --- /dev/null +++ b/main/platform/borla_s3/tca9555.h @@ -0,0 +1,122 @@ +#pragma once +#include "driver/gpio.h" +#include +#include +#include +#include "freertos/FreeRTOS.h" +namespace borla +{ + class BorlaS3I2cBus; + // 硬件引脚定义(ESP32-S3 I2C总线) + #define TCA_I2C_NUM I2C_NUM_0 + #define TCA_SCL_GPIO GPIO_NUM_1 + #define TCA_SDA_GPIO GPIO_NUM_2 + // 端口定义 Port0 / Port1 + enum TCA_PORT : uint8_t + { + PORT0 = 0, + PORT1 = 1, + }; + // TCA9555 寄存器定义 + enum TCA9555_REG : uint8_t + { + TCA9555_REG_IN0 = 0x00, // Port0 输入寄存器 + TCA9555_REG_IN1 = 0x01, // Port1 输入寄存器 + TCA9555_REG_OUT0 = 0x02, // Port0 输出寄存器 + TCA9555_REG_OUT1 = 0x03, // Port1 输出寄存器 + TCA9555_REG_POL0 = 0x04, // Port0 极性反转 + TCA9555_REG_POL1 = 0x05, // Port1 极性反转 + TCA9555_REG_CFG0 = 0x06, // Port0 方向配置 1=输入 0=输出 + TCA9555_REG_CFG1 = 0x07, // Port1 方向配置 + }; + + // TCA9555 硬件地址(原理图 IIC ADDR:0x20) + constexpr uint8_t TCA9555_ADDR = 0x20; + + // 原理图引脚映射宏 + // Port0 P0~P7 + #define TCA_P0_LEDA 0U + #define TCA_P0_SC_RESET 1U + #define TCA_P0_ADD_IO 2U + #define TCA_P0_OV_RESET 3U + #define TCA_P0_FLASH 6U + #define TCA_P0_PWDN 7U + // Port1 P10~P17 + #define TCA_P1_KEY 0U // 输入引脚 P10 Port1 bit0 + + #define TCA_P1_MCU_VCC 2U + #define TCA_P1_5V_EN 3U + #define TCA_P1_PREP_VCC 5U + #define TCA_P1_IMU_INT 6U + #define TCA_P1_PA_CTL 7U + //tcap555扩展芯片引脚配置接口 + constexpr uint16_t TCA_IO(uint8_t port, uint8_t bit) + { + return (static_cast(port) << 8) | static_cast(bit); + } + constexpr uint8_t TCA_GET_PORT(uint16_t pin_code) + { + return static_cast((pin_code >> 8) & 0xFFU); + } + constexpr uint8_t TCA_GET_BIT(uint16_t pin_code) + { + return static_cast(pin_code & 0xFFU); + } + + // PORT0 P00~P07 + constexpr uint16_t SC_LEDA = TCA_IO(PORT0, TCA_P0_LEDA); + constexpr uint16_t SC_RESET = TCA_IO(PORT0, TCA_P0_SC_RESET); + constexpr uint16_t EN_4G = TCA_IO(PORT0, TCA_P0_ADD_IO); // 4G + constexpr uint16_t OV_RESET = TCA_IO(PORT0, TCA_P0_OV_RESET); + constexpr uint16_t OV_FLASH = TCA_IO(PORT0, TCA_P0_FLASH); + constexpr uint16_t OV_PWDN = TCA_IO(PORT0, TCA_P0_PWDN); + + // PORT1 P10~P17 + constexpr uint16_t KEY = TCA_IO(PORT1, TCA_P1_KEY); // 按键输入 + constexpr uint16_t MCU_VCC_CTL = TCA_IO(PORT1, TCA_P1_MCU_VCC); + constexpr uint16_t V5_EN = TCA_IO(PORT1, TCA_P1_5V_EN); + constexpr uint16_t PREP_VCC_CTL = TCA_IO(PORT1, TCA_P1_PREP_VCC); + constexpr uint16_t IMU_INT = TCA_IO(PORT1, TCA_P1_IMU_INT); + constexpr uint16_t PA_CTL = TCA_IO(PORT1, TCA_P1_PA_CTL); + + class TCA9555 + { + public: + SemaphoreHandle_t i2c_mtx_ = nullptr; + // 传入已初始化完成的I2C总线句柄 + explicit TCA9555(BorlaS3I2cBus &bus); + ~TCA9555() = default; + + // 初始化:配置全部端口默认输出0(外设断电) + esp_err_t Init(); + // 底层寄存器读写 + esp_err_t read_reg(uint8_t reg, uint8_t* data); + esp_err_t write_reg(uint8_t reg, uint8_t data); + + // 释放I2C资源 + esp_err_t deinit(void); + + // Port0 位操作 P0~P7 + esp_err_t p0_set_bit(uint8_t bit); // 置高 + esp_err_t p0_clr_bit(uint8_t bit); // 置低 + esp_err_t p0_write_all(uint8_t val); // 整端口输出 + + // Port1 位操作 P10~P17 + esp_err_t p1_set_bit(uint8_t bit); + esp_err_t p1_clr_bit(uint8_t bit); + esp_err_t p1_write_all(uint8_t val); + + // 读取输入电平 + esp_err_t read_p0_input(uint8_t* val); + esp_err_t read_p1_input(uint8_t* val); + + esp_err_t set_pin(uint16_t pin_code); + esp_err_t clr_pin(uint16_t pin_code); + private: + + i2c_master_bus_handle_t bus_ = nullptr; + i2c_master_dev_handle_t dev_handle_ = nullptr; + BorlaS3I2cBus &bus_ref_; + }; + +} // namespace borla \ No newline at end of file diff --git a/main/platform/borla_s3/ws2812_led.cc b/main/platform/borla_s3/ws2812_led.cc new file mode 100644 index 0000000..aca729e --- /dev/null +++ b/main/platform/borla_s3/ws2812_led.cc @@ -0,0 +1,241 @@ +#include "platform/borla_s3/ws2812_led.h" + +#include +#include +#include + +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "Ws2812Led2"; +constexpr uint32_t kAnimationTickMs = 30; + +} // namespace + +Ws2812Led::~Ws2812Led() +{ + if (timer_ != nullptr) { + esp_timer_stop(timer_); + esp_timer_delete(timer_); + } + if (strip_ != nullptr) { + led_strip_clear(strip_); + led_strip_del(strip_); + } +} + +bool Ws2812Led::Initialize(gpio_num_t gpio) +{ + led_strip_config_t strip_config = {}; + strip_config.strip_gpio_num = gpio; + strip_config.max_leds = 1; + strip_config.color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB; + strip_config.led_model = LED_MODEL_WS2812; + + led_strip_rmt_config_t rmt_config = {}; + rmt_config.resolution_hz = 10 * 1000 * 1000; + + esp_err_t result = + led_strip_new_rmt_device(&strip_config, &rmt_config, &strip_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to create LED strip: %s", + esp_err_to_name(result)); + return false; + } + + const esp_timer_create_args_t timer_args = { + .callback = &Ws2812Led::TimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "borla_led", + .skip_unhandled_events = true, + }; + result = esp_timer_create(&timer_args, &timer_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to create animation timer: %s", + esp_err_to_name(result)); + led_strip_del(strip_); + strip_ = nullptr; + return false; + } + + result = led_strip_clear(strip_); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to clear LED: %s", esp_err_to_name(result)); + return false; + } + + ESP_LOGI(kTag, "WS2812 initialized on GPIO%d", static_cast(gpio)); + return true; +} + +void Ws2812Led::SetPattern(LedPattern pattern) +{ + std::lock_guard lock(mutex_); + if (strip_ == nullptr || timer_ == nullptr) { + ESP_LOGW(kTag, "ignored LED pattern before initialization"); + return; + } + if (pattern == current_pattern_) { + return; + } + + StopTimer(); + current_pattern_ = pattern; + phase_ms_ = 0; + Configure(pattern); + + if (animation_ == Animation::kOff) { + led_strip_clear(strip_); + } else if (animation_ == Animation::kSteady) { + Render(255); + } else { + Render(animation_ == Animation::kBlink ? 255 : 0); + const esp_err_t result = + esp_timer_start_periodic(timer_, kAnimationTickMs * 1000); + if (result != ESP_OK) { + ESP_LOGE(kTag, "failed to start animation: %s", + esp_err_to_name(result)); + led_strip_clear(strip_); + } + } +} + +void Ws2812Led::TimerCallback(void* context) +{ + static_cast(context)->OnTimer(); +} + +void Ws2812Led::OnTimer() +{ + std::lock_guard lock(mutex_); + if (strip_ == nullptr || period_ms_ == 0) { + return; + } + + phase_ms_ = (phase_ms_ + kAnimationTickMs) % period_ms_; + if (animation_ == Animation::kBlink) { + Render(phase_ms_ < period_ms_ / 2 ? 255 : 0); + return; + } + + if (animation_ == Animation::kBreathe) { + const uint32_t half = std::max(period_ms_ / 2, 1); + const uint32_t distance = + phase_ms_ <= half ? phase_ms_ : period_ms_ - phase_ms_; + Render(static_cast((distance * 255) / half)); + } +} + +void Ws2812Led::StopTimer() +{ + const esp_err_t result = esp_timer_stop(timer_); + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { + ESP_LOGW(kTag, "failed to stop animation: %s", + esp_err_to_name(result)); + } +} + +void Ws2812Led::Render(uint8_t scale) +{ + const uint8_t red = + static_cast((static_cast(red_) * scale) / 255); + const uint8_t green = + static_cast((static_cast(green_) * scale) / 255); + const uint8_t blue = + static_cast((static_cast(blue_) * scale) / 255); + led_strip_set_pixel(strip_, 0, red, green, blue); + led_strip_refresh(strip_); +} + +void Ws2812Led::Configure(LedPattern pattern) +{ + switch (pattern) { + case LedPattern::kOff: + animation_ = Animation::kOff; + red_ = green_ = blue_ = 0; + period_ms_ = 0; + break; + case LedPattern::kStarting: + animation_ = Animation::kBreathe; + red_ = 8; + green_ = 2; + blue_ = 0; + period_ms_ = 1500; + break; + case LedPattern::kConnecting: + animation_ = Animation::kBreathe; + red_ = 0; + green_ = 0; + blue_ = 8; + period_ms_ = 1000; + break; + case LedPattern::kIdle: + animation_ = Animation::kBreathe; + red_ = 8; + green_ = 6; + blue_ = 2; + period_ms_ = 4000; + break; + case LedPattern::kListening: + animation_ = Animation::kSteady; + red_ = 16; + green_ = 0; + blue_ = 0; + period_ms_ = 0; + break; + case LedPattern::kSpeaking: + animation_ = Animation::kBreathe; + red_ = 0; + green_ = 8; + blue_ = 0; + period_ms_ = 1500; + break; + case LedPattern::kRinging: + animation_ = Animation::kBlink; + red_ = 12; + green_ = 0; + blue_ = 12; + period_ms_ = 500; + break; + case LedPattern::kCalling: + animation_ = Animation::kSteady; + red_ = 0; + green_ = 16; + blue_ = 0; + period_ms_ = 0; + break; + case LedPattern::kFriendMode: + animation_ = Animation::kBreathe; + red_ = 8; + green_ = 0; + blue_ = 12; + period_ms_ = 800; + break; + case LedPattern::kProvisioning: + animation_ = Animation::kBlink; + red_ = 0; + green_ = 8; + blue_ = 8; + period_ms_ = 500; + break; + case LedPattern::kUpgrading: + animation_ = Animation::kBlink; + red_ = 12; + green_ = 8; + blue_ = 0; + period_ms_ = 200; + break; + case LedPattern::kError: + animation_ = Animation::kBlink; + red_ = 16; + green_ = 0; + blue_ = 0; + period_ms_ = 100; + break; + } +} + +} // namespace borla diff --git a/main/platform/borla_s3/ws2812_led.h b/main/platform/borla_s3/ws2812_led.h new file mode 100644 index 0000000..7de38c5 --- /dev/null +++ b/main/platform/borla_s3/ws2812_led.h @@ -0,0 +1,49 @@ +#pragma once + +#include "core/runtime_state.h" + +#include +#include +#include + +#include +#include + +namespace borla { + +class Ws2812Led final { +public: + Ws2812Led() = default; + ~Ws2812Led(); + + bool Initialize(gpio_num_t gpio); + void SetPattern(LedPattern pattern); + +private: + enum class Animation : uint8_t { + kOff, + kSteady, + kBlink, + kBreathe, + }; + + static void TimerCallback(void* context); + + void OnTimer(); + void StopTimer(); + void Render(uint8_t scale); + void Configure(LedPattern pattern); + + std::mutex mutex_; + led_strip_handle_t strip_ = nullptr; + esp_timer_handle_t timer_ = nullptr; + LedPattern current_pattern_ = LedPattern::kOff; + Animation animation_ = Animation::kOff; + uint8_t red_ = 0; + uint8_t green_ = 0; + uint8_t blue_ = 0; + uint32_t period_ms_ = 0; + uint32_t phase_ms_ = 0; +}; + +} // namespace borla diff --git a/main/ports/alert_ringer.h b/main/ports/alert_ringer.h new file mode 100644 index 0000000..0a4bb73 --- /dev/null +++ b/main/ports/alert_ringer.h @@ -0,0 +1,14 @@ +#pragma once + +#include "core/playback_types.h" + +namespace borla { + +class IAlertRinger { +public: + virtual ~IAlertRinger() = default; + virtual void Start(AlertKind kind) = 0; + virtual void Stop() = 0; +}; + +} // namespace borla diff --git a/main/ports/application_observer.h b/main/ports/application_observer.h new file mode 100644 index 0000000..13b6508 --- /dev/null +++ b/main/ports/application_observer.h @@ -0,0 +1,16 @@ +#pragma once + +#include "core/app_event.h" +#include "core/runtime_state.h" + +namespace borla { + +class IApplicationObserver { +public: + virtual ~IApplicationObserver() = default; + virtual void OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) = 0; +}; + +} // namespace borla diff --git a/main/ports/audio_engine.h b/main/ports/audio_engine.h new file mode 100644 index 0000000..1722293 --- /dev/null +++ b/main/ports/audio_engine.h @@ -0,0 +1,69 @@ +#pragma once + +#include "core/playback_types.h" +#include "core/runtime_state.h" +#include "ports/volume_status_provider.h" + +#include +#include + +namespace borla { + +class IAudioEngine : public IVolumeStatusProvider { +public: + ~IAudioEngine() override = default; + + virtual bool Start() = 0; + virtual void Stop() = 0; + virtual void ApplyPolicy(AudioPolicy policy) = 0; + virtual void SetVolume(uint8_t volume_percent) = 0; + virtual void SetWakeWordEnabled(bool enabled) = 0; + virtual void SetBargeInEnabled(bool enabled) = 0; + virtual void SetPlaybackPaused(bool paused) = 0; + // Frees the WakeNet instance. Only for entering BLE provisioning, where the + // BT controller needs every spare byte and the wake word is unused; the + // device reboots out of provisioning anyway. Never call this on an ordinary + // policy change — reloading the model takes ~110 ms and stalls capture. + virtual void ReleaseWakeWord() = 0; + // Blocks until nothing owns the speaker, or the timeout elapses. Returns + // true when playback actually finished. Only for callers that are about to + // destroy the audio path — chiefly the provisioning reboot, which used to + // cut "配网成功啦" mid-sentence. + virtual bool WaitForPlaybackIdle(uint32_t timeout_ms) = 0; + // Emits the voice frontend counters (AEC reference misses in particular) to + // the log. Called by diagnostics; the counters are otherwise invisible. + virtual void LogAudioMetrics(const char* reason) = 0; + // Emits one aggregated line covering the capture DSP chain for the frames + // seen since the previous call: microphone/AEC/reference levels, echo + // return loss, AGC gain, NS state, VAD state, reference ring depth and the + // measured frame period. Returns false when nothing was captured, so the + // caller can stay quiet while the microphone is off. Must be called from a + // diagnostics task: the capture task cannot afford a console write. + virtual bool LogAudioFrameStats() = 0; + virtual void CancelPlayback(PlaybackSessionId session_id) = 0; + virtual void BeginRemotePlayback( + PlaybackSessionId session_id, + PlaybackPriority priority) = 0; + virtual void EndPlaybackInput(PlaybackSessionId session_id) = 0; + virtual bool SubmitOpusFrame( + PlaybackSessionId session_id, + const uint8_t* data, + size_t size) = 0; + virtual PlaybackSessionId PlayLocalPrompt( + LocalPrompt prompt, + PlaybackPriority priority, + int16_t selector = -1) = 0; + virtual PlaybackSessionId PlayLocalSequence( + const LocalPromptSequence& sequence, + PlaybackPriority priority) = 0; + // Plays a prompt WITHOUT publishing kLocalPromptStarted. Used for the + // wake acknowledgement, which must be audible while the device is already + // listening: routing it through the normal lifecycle would drive the + // conversation state to kSpeaking and close the uplink the child is about + // to talk into. + virtual PlaybackSessionId PlayDetachedPrompt( + LocalPrompt prompt, + PlaybackPriority priority) = 0; +}; + +} // namespace borla diff --git a/main/ports/battery_status_provider.h b/main/ports/battery_status_provider.h new file mode 100644 index 0000000..700a764 --- /dev/null +++ b/main/ports/battery_status_provider.h @@ -0,0 +1,13 @@ +#pragma once + +#include "sensor/sensor_types.h" + +namespace borla { + +class IBatteryStatusProvider { +public: + virtual ~IBatteryStatusProvider() = default; + virtual BatteryStatus GetBatteryStatus() const = 0; +}; + +} // namespace borla diff --git a/main/ports/connectivity_manager.h b/main/ports/connectivity_manager.h new file mode 100644 index 0000000..40e8475 --- /dev/null +++ b/main/ports/connectivity_manager.h @@ -0,0 +1,50 @@ +#pragma once + +#include "connectivity/wifi_types.h" + +#include +#include + +namespace borla { + +enum class ConnectivityPhase : uint8_t { + kStopped, + kCredentialsMissing, + kStartingTransport, + kConnecting, + kWaitingRetry, + kOnline, +}; + +struct ConnectivityDiagnostics { + ConnectivityPhase phase = ConnectivityPhase::kStopped; + bool online = false; + int8_t rssi_dbm = -127; + uint8_t channel = 0; + uint16_t last_disconnect_reason = 0; + uint32_t retry_attempt_count = 0; + size_t active_credential_index = 0; + size_t credential_count = 0; + std::array ssid{}; + std::array ipv4{}; +}; + +class IConnectivityManager { +public: + virtual ~IConnectivityManager() = default; + + virtual void Start() = 0; + virtual void Stop() = 0; + virtual void SwitchNetwork() = 0; + // 2026-9-7 ckkj add: BLE 好友模式启动前静默挂起网络。BT 控制器需要 + // ~65KB 内部 RAM,与已初始化的 WiFi 驱动无法共存(配网服务已验证), + // 挂起期间不发布断开事件,避免打断应用层状态机;结束后 ResumeAfterBle() + // 立即按正常流程重连。默认空实现供无此需求的实现者忽略。 + virtual void SuspendForBle() {} + virtual void ResumeAfterBle() {} + //////// + virtual bool IsOnline() const = 0; + virtual ConnectivityDiagnostics GetDiagnostics() const = 0; +}; + +} // namespace borla diff --git a/main/ports/device_platform.h b/main/ports/device_platform.h new file mode 100644 index 0000000..9f329f6 --- /dev/null +++ b/main/ports/device_platform.h @@ -0,0 +1,39 @@ +#pragma once + +#include "core/runtime_state.h" + +#include + +namespace borla { + +struct DeviceIdentity { + char board[24]{}; + char mac[18]{}; + char app_version[32]{}; + char chip_model[24]{}; +}; + +enum class SoftOffWakeReason : uint8_t { + kNone, + kButton, + kTimer, + kOther, +}; + +class IDevicePlatform { +public: + virtual ~IDevicePlatform() = default; + + virtual bool Initialize() = 0; + virtual const DeviceIdentity& Identity() const = 0; + virtual void SetLed(LedPattern pattern) = 0; + virtual void ShowTemporaryLedAlert(uint32_t duration_ms) = 0; + virtual void ReportError(uint32_t error_id) = 0; + virtual void Reboot() = 0; + virtual void EnterSoftOff(uint64_t timer_wakeup_us) = 0; + virtual SoftOffWakeReason ConsumeSoftOffWakeReason() = 0; + //2026-8-26 ckkj add + virtual bool ReadWakeButton() = 0; +}; + +} // namespace borla diff --git a/main/ports/device_profile_sink.h b/main/ports/device_profile_sink.h new file mode 100644 index 0000000..caed10e --- /dev/null +++ b/main/ports/device_profile_sink.h @@ -0,0 +1,11 @@ +#pragma once + +namespace borla { + +class IDeviceProfileSink { +public: + virtual ~IDeviceProfileSink() = default; + virtual void SetDeviceName(const char* device_name) = 0; +}; + +} // namespace borla diff --git a/main/ports/effect_sink.h b/main/ports/effect_sink.h new file mode 100644 index 0000000..f5ae507 --- /dev/null +++ b/main/ports/effect_sink.h @@ -0,0 +1,15 @@ +#pragma once + +#include "core/app_effect.h" +#include "core/runtime_state.h" + +namespace borla { + +class IEffectSink { +public: + virtual ~IEffectSink() = default; + virtual void Handle(const AppEffect& effect, + const RuntimeState& resulting_state) = 0; +}; + +} // namespace borla diff --git a/main/ports/event_publisher.h b/main/ports/event_publisher.h new file mode 100644 index 0000000..8f59f7a --- /dev/null +++ b/main/ports/event_publisher.h @@ -0,0 +1,13 @@ +#pragma once + +#include "core/app_event.h" + +namespace borla { + +class IEventPublisher { +public: + virtual ~IEventPublisher() = default; + virtual bool Publish(const AppEvent& event) = 0; +}; + +} // namespace borla diff --git a/main/ports/friend_service.h b/main/ports/friend_service.h new file mode 100644 index 0000000..c8451e6 --- /dev/null +++ b/main/ports/friend_service.h @@ -0,0 +1,12 @@ +#pragma once + +namespace borla { + +class IFriendService { +public: + virtual ~IFriendService() = default; + virtual void Start() = 0; + virtual void Stop() = 0; +}; + +} // namespace borla diff --git a/main/ports/local_sequence_handler.h b/main/ports/local_sequence_handler.h new file mode 100644 index 0000000..b367abb --- /dev/null +++ b/main/ports/local_sequence_handler.h @@ -0,0 +1,15 @@ +#pragma once + +#include "core/playback_types.h" + +namespace borla { + +class ILocalSequenceHandler { +public: + virtual ~ILocalSequenceHandler() = default; + virtual bool StartLocalSequence( + const LocalPromptSequence& sequence) = 0; + virtual void StopLocalSequence() = 0; +}; + +} // namespace borla diff --git a/main/ports/memory_cache.h b/main/ports/memory_cache.h new file mode 100644 index 0000000..dbb62ad --- /dev/null +++ b/main/ports/memory_cache.h @@ -0,0 +1,19 @@ +#pragma once + +#include "memory/memory_types.h" + +namespace borla { + +class IMemoryCache { +public: + virtual ~IMemoryCache() = default; + virtual bool Load() = 0; + // Deliberately an out-parameter rather than a by-value return: a returned + // MemorySnapshot materialises a ~2 KB temporary in the caller's frame, and + // the only caller is the WebSocket/TLS task building ClientHello, whose + // stack cannot absorb that on top of the message buffer. + virtual void CopySnapshot(MemorySnapshot* output) const = 0; + virtual bool Update(const MemorySnapshot& snapshot) = 0; +}; + +} // namespace borla diff --git a/main/ports/ota_service.h b/main/ports/ota_service.h new file mode 100644 index 0000000..9430944 --- /dev/null +++ b/main/ports/ota_service.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace borla { + +class IOtaService { +public: + virtual ~IOtaService() = default; + virtual void StartUpgrade(uint32_t request_id) = 0; +}; + +} // namespace borla diff --git a/main/ports/power_service.h b/main/ports/power_service.h new file mode 100644 index 0000000..9756094 --- /dev/null +++ b/main/ports/power_service.h @@ -0,0 +1,11 @@ +#pragma once + +namespace borla { + +class IPowerService { +public: + virtual ~IPowerService() = default; + virtual void EnterSoftOff() = 0; +}; + +} // namespace borla diff --git a/main/ports/provisioning_service.h b/main/ports/provisioning_service.h new file mode 100644 index 0000000..6b1f2f0 --- /dev/null +++ b/main/ports/provisioning_service.h @@ -0,0 +1,12 @@ +#pragma once + +namespace borla { + +class IProvisioningService { +public: + virtual ~IProvisioningService() = default; + virtual void Start() = 0; + virtual void Stop() = 0; +}; + +} // namespace borla diff --git a/main/ports/realtime_protocol.h b/main/ports/realtime_protocol.h new file mode 100644 index 0000000..623946f --- /dev/null +++ b/main/ports/realtime_protocol.h @@ -0,0 +1,44 @@ +#pragma once + +#include "core/playback_types.h" +#include "core/runtime_state.h" + +#include + +namespace borla { + +class IRealtimeProtocol { +public: + virtual ~IRealtimeProtocol() = default; + + virtual void Open() = 0; + virtual void Close() = 0; + virtual void SendStartListening() = 0; + virtual void SendStopListening() = 0; + virtual void SendAbortSpeaking( + ConversationInterruptSource source) = 0; + virtual void SendGoodbye() = 0; + virtual void SendAcceptCall() = 0; + virtual void SendHangupCall() = 0; + virtual void SendButtonClick(uint8_t click_count) = 0; + virtual void SendLocalPlaybackState( + LocalPrompt prompt, + bool started) = 0; + virtual bool SendFriendAdd( + const char* local_mac, + const char* local_name, + const char* remote_mac, + const char* remote_name) = 0; + // Asks the server to speak an upgrade announcement. `optional` marks an + // advisory notice the user may decline; otherwise the device is about to + // start installing. Returns false when the channel is not open. + virtual bool SendOtaNotify( + const char* text, + bool optional) = 0; + // Publishes the remote-configured connection-error prompt. Used when + // playback of a server reply dies mid-sentence so the child hears that + // something broke instead of silence. + virtual void RequestConnectionErrorPrompt() = 0; +}; + +} // namespace borla diff --git a/main/ports/remote_behavior_config.h b/main/ports/remote_behavior_config.h new file mode 100644 index 0000000..fb33229 --- /dev/null +++ b/main/ports/remote_behavior_config.h @@ -0,0 +1,27 @@ +#pragma once + +#include "core/playback_types.h" +#include "core/remote_behavior.h" + +namespace borla { + +class IRemoteBehaviorConfig { +public: + virtual ~IRemoteBehaviorConfig() = default; + + virtual ButtonAction ResolveButtonAction( + uint8_t click_count) const = 0; + virtual LocalPrompt ServerUnreachablePrompt() const = 0; + virtual LocalPrompt NoNetworkPrompt() const = 0; + + virtual bool UpdateButtonActions( + ButtonAction triple_click, + ButtonAction quadruple_click) = 0; + virtual bool UpdateConnectionPrompts( + bool has_server_unreachable, + LocalPrompt server_unreachable, + bool has_no_network, + LocalPrompt no_network) = 0; +}; + +} // namespace borla diff --git a/main/ports/sensor_message_sink.h b/main/ports/sensor_message_sink.h new file mode 100644 index 0000000..c477b43 --- /dev/null +++ b/main/ports/sensor_message_sink.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace borla { + +class ISensorMessageSink { +public: + virtual ~ISensorMessageSink() = default; + + // Sensor data is best effort. A false result means the connection is not + // ready or the bounded transport queue is full; callers must drop it. + virtual bool SendSensorMessage(const char* data, size_t size) = 0; +}; + +} // namespace borla diff --git a/main/ports/volume_status_provider.h b/main/ports/volume_status_provider.h new file mode 100644 index 0000000..d43f8e6 --- /dev/null +++ b/main/ports/volume_status_provider.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace borla { + +// Narrow read-only view the protocol layer uses for the periodic status frame. +// Keeps RealtimeProtocol from depending on the whole audio engine. +class IVolumeStatusProvider { +public: + virtual ~IVolumeStatusProvider() = default; + virtual uint8_t OutputVolumePercent() const = 0; +}; + +} // namespace borla diff --git a/main/power/idle_service.cc b/main/power/idle_service.cc new file mode 100644 index 0000000..d5a5d5b --- /dev/null +++ b/main/power/idle_service.cc @@ -0,0 +1,167 @@ +#include "power/idle_service.h" + +#include "core/playback_types.h" + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "IdleService2"; + +} // namespace + +bool IdleService::Initialize(IEventPublisher& publisher) +{ + if (running_.load()) { + return true; + } + if (config_.check_after_ms == 0 || + config_.soft_off_after_ms <= config_.check_after_ms || + config_.response_window_ms == 0) { + return false; + } + publisher_ = &publisher; + running_.store(true); + task_ = xTaskCreateStatic( + &IdleService::TaskEntry, + "idle_service2", + task_stack_.size(), + this, + 3, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + running_.store(false); + return false; + } + return true; +} + +void IdleService::Stop() +{ + running_.store(false); + phase_.store(IdlePhase::kStopped); +} + +void IdleService::OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) +{ + busy_.store( + state.call != CallState::kInactive || + state.conversation == ConversationState::kSpeaking || + state.playback != PlaybackState::kIdle || + state.alert_ringing); + + if (state.lifecycle != LifecycleState::kRunning) { + phase_.store(IdlePhase::kStopped); + return; + } + if (event.type == AppEventType::kRealtimeConnected && + phase_.load() == IdlePhase::kStopped) { + Reset(NowMs()); + return; + } + if (IsActivity(event)) { + Reset(NowMs()); + return; + } + if (event.type == AppEventType::kLocalPromptStarted && + event.value == + static_cast(LocalPrompt::kIdleCheck) && + phase_.load() == IdlePhase::kPromptingCheck) { + prompt_session_id_.store(event.correlation_id); + return; + } + if ((event.type == AppEventType::kPlaybackDrained || + event.type == AppEventType::kPlaybackFailed) && + prompt_session_id_.load() != 0 && + event.correlation_id == prompt_session_id_.load() && + phase_.load() == IdlePhase::kPromptingCheck) { + prompt_session_id_.store(0); + phase_.store(IdlePhase::kAwaitingResponse); + phase_deadline_ms_.store( + NowMs() + config_.response_window_ms); + } +} + +void IdleService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void IdleService::Run() +{ + while (running_.load()) { + const uint64_t now_ms = NowMs(); + const IdlePhase phase = phase_.load(); + const uint64_t idle_since = idle_since_ms_.load(); + + if (phase == IdlePhase::kRunning && + idle_since != 0 && + now_ms - idle_since >= config_.check_after_ms && + !busy_.load()) { + phase_.store(IdlePhase::kPromptingCheck); + phase_deadline_ms_.store( + now_ms + config_.prompt_start_timeout_ms); + publisher_->Publish( + AppEvent::Make(AppEventType::kIdleCheckDue)); + } else if (phase == IdlePhase::kPromptingCheck && + phase_deadline_ms_.load() <= now_ms && + prompt_session_id_.load() == 0) { + // Missing/rejected prompt still receives the normal response + // window instead of immediately sleeping. + phase_.store(IdlePhase::kAwaitingResponse); + phase_deadline_ms_.store( + now_ms + config_.response_window_ms); + } else if (phase == IdlePhase::kAwaitingResponse && + phase_deadline_ms_.load() <= now_ms) { + phase_.store(IdlePhase::kIdleSleeping); + publisher_->Publish(AppEvent::Make( + AppEventType::kIdleResponseExpired)); + } else if (phase == IdlePhase::kIdleSleeping && + idle_since != 0 && + now_ms - idle_since >= + config_.soft_off_after_ms) { + phase_.store(IdlePhase::kGoodbyeTriggered); + publisher_->Publish(AppEvent::Make( + AppEventType::kIdleGoodbyeDue)); + } + vTaskDelay(pdMS_TO_TICKS(100)); + } + task_ = nullptr; + vTaskDelete(nullptr); +} + +void IdleService::Reset(uint64_t now_ms) +{ + idle_since_ms_.store(now_ms); + phase_deadline_ms_.store(0); + prompt_session_id_.store(0); + phase_.store(IdlePhase::kRunning); +} + +bool IdleService::IsActivity(const AppEvent& event) +{ + switch (event.type) { + case AppEventType::kButtonClicked: + case AppEventType::kButtonLongPressed: + case AppEventType::kWakeWordDetected: + case AppEventType::kUserActivityDetected: + case AppEventType::kTtsStarted: + case AppEventType::kIncomingCall: + case AppEventType::kCallConnected: + return true; + default: + return false; + } +} + +uint64_t IdleService::NowMs() +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace borla diff --git a/main/power/idle_service.h b/main/power/idle_service.h new file mode 100644 index 0000000..e5c3507 --- /dev/null +++ b/main/power/idle_service.h @@ -0,0 +1,68 @@ +#pragma once + +#include "ports/application_observer.h" +#include "ports/event_publisher.h" + +#include +#include +#include + +#include +#include + +namespace borla { + +struct IdleServiceConfig { + uint32_t check_after_ms = 3U * 60U * 1000U; + uint32_t soft_off_after_ms = 10U * 60U * 1000U; + uint32_t response_window_ms = 15U * 1000U; + uint32_t prompt_start_timeout_ms = 10U * 1000U; +}; + +enum class IdlePhase : uint8_t { + kStopped, + kRunning, + kPromptingCheck, + kAwaitingResponse, + kIdleSleeping, + kGoodbyeTriggered, +}; + +class IdleService final : public IApplicationObserver { +public: + explicit IdleService( + const IdleServiceConfig& config = IdleServiceConfig{}) + : config_(config) + { + } + + bool Initialize(IEventPublisher& publisher); + void Stop(); + void OnApplicationEvent( + const AppEvent& event, + const RuntimeState& state) override; + + IdlePhase phase() const { return phase_.load(); } + +private: + static constexpr uint32_t kTaskStackDepth = 2048; + static void TaskEntry(void* context); + void Run(); + void Reset(uint64_t now_ms); + static bool IsActivity(const AppEvent& event); + static uint64_t NowMs(); + + IdleServiceConfig config_; + IEventPublisher* publisher_ = nullptr; + std::atomic phase_{IdlePhase::kStopped}; + std::atomic idle_since_ms_{0}; + std::atomic phase_deadline_ms_{0}; + std::atomic prompt_session_id_{0}; + std::atomic busy_{false}; + std::atomic running_{false}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array task_stack_{}; +}; + +} // namespace borla diff --git a/main/power/power_service.cc b/main/power/power_service.cc new file mode 100644 index 0000000..7ab0b65 --- /dev/null +++ b/main/power/power_service.cc @@ -0,0 +1,129 @@ +#include "power/power_service.h" + +#include + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "PowerService2"; +constexpr uint8_t kLowBatteryPercent = 20; +constexpr uint8_t kCriticalBatteryPercent = 10; +constexpr uint8_t kWarningResetPercent = 25; +RTC_DATA_ATTR uint32_t g_reminder_timer_wake_pending = 0; + +uint64_t MinimumDelay(uint64_t left, uint64_t right) +{ + if (left == 0) { + return right; + } + if (right == 0) { + return left; + } + return std::min(left, right); +} + +} // namespace + +bool PowerService::Initialize(IEventPublisher& publisher) +{ + if (running_.load()) { + return true; + } + publisher_ = &publisher; + const SoftOffWakeReason wake_reason = + platform_.ConsumeSoftOffWakeReason(); + if (wake_reason == SoftOffWakeReason::kTimer && + g_reminder_timer_wake_pending != 0) { + publisher_->Publish( + AppEvent::Make(AppEventType::kReminderDue)); + } + g_reminder_timer_wake_pending = 0; + + running_.store(true); + task_ = xTaskCreateStatic( + &PowerService::TaskEntry, + "power_service2", + task_stack_.size(), + this, + 3, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + running_.store(false); + return false; + } + return true; +} + +void PowerService::Stop() +{ + running_.store(false); +} + +void PowerService::EnterSoftOff() +{ + if (entering_soft_off_.exchange(true)) { + return; + } + const uint64_t alarm_delay = alarms_.NextWakeupDelayUs(); + const uint64_t reminder_delay = reminders_.NextWakeupDelayUs(); + const uint64_t wake_delay = + MinimumDelay(alarm_delay, reminder_delay); + g_reminder_timer_wake_pending = + reminder_delay != 0 && + (alarm_delay == 0 || reminder_delay <= alarm_delay) + ? 1 + : 0; + + ESP_LOGI(kTag, + "soft-off prepare alarm_us=%llu reminder_us=%llu selected_us=%llu", + static_cast(alarm_delay), + static_cast(reminder_delay), + static_cast(wake_delay)); + running_.store(false); + sensors_.Stop(); + alarms_.Stop(); + reminders_.Stop(); + platform_.EnterSoftOff(wake_delay); +} + +void PowerService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void PowerService::Run() +{ + bool warned = false; + bool critical = false; + while (running_.load()) { + const BatteryStatus status = battery_.GetBatteryStatus(); + if (status.valid) { + if (status.charging || status.percent > kWarningResetPercent) { + warned = false; + critical = false; + } else if (!critical && + status.percent <= kCriticalBatteryPercent) { + critical = true; + publisher_->Publish( + AppEvent::Make(AppEventType::kCriticalBattery)); + } else if (!warned && + status.percent <= kLowBatteryPercent) { + warned = true; + publisher_->Publish(AppEvent::Make( + AppEventType::kLowBatteryWarning)); + } + } + for (uint32_t waited = 0;running_.load() && waited < 30000;waited += 100) + { + vTaskDelay(pdMS_TO_TICKS(100)); + } + } + task_ = nullptr; + vTaskDelete(nullptr); +} + +} // namespace borla diff --git a/main/power/power_service.h b/main/power/power_service.h new file mode 100644 index 0000000..d5b196c --- /dev/null +++ b/main/power/power_service.h @@ -0,0 +1,57 @@ +#pragma once + +#include "ports/battery_status_provider.h" +#include "ports/device_platform.h" +#include "ports/event_publisher.h" +#include "ports/power_service.h" +#include "schedule/alarm_service.h" +#include "schedule/reminder_service.h" +#include "sensor/sensor_service.h" + +#include +#include + +#include +#include + +namespace borla { + +class PowerService final : public IPowerService { +public: + PowerService( + IBatteryStatusProvider& battery, + SensorService& sensors, + AlarmService& alarms, + ReminderService& reminders, + IDevicePlatform& platform) + : battery_(battery), + sensors_(sensors), + alarms_(alarms), + reminders_(reminders), + platform_(platform) + { + } + + bool Initialize(IEventPublisher& publisher); + void Stop(); + void EnterSoftOff() override; + +private: + static constexpr uint32_t kTaskStackDepth = 2048; + static void TaskEntry(void* context); + void Run(); + + IBatteryStatusProvider& battery_; + SensorService& sensors_; + AlarmService& alarms_; + ReminderService& reminders_; + IDevicePlatform& platform_; + IEventPublisher* publisher_ = nullptr; + std::atomic running_{false}; + std::atomic entering_soft_off_{false}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array task_stack_{}; +}; + +} // namespace borla diff --git a/main/protocol/binary_audio_protocol.cc b/main/protocol/binary_audio_protocol.cc new file mode 100644 index 0000000..6e632e4 --- /dev/null +++ b/main/protocol/binary_audio_protocol.cc @@ -0,0 +1,176 @@ +#include "protocol/binary_audio_protocol.h" + +#include + +namespace borla { +namespace { + +uint16_t ReadBigEndian(const uint8_t* data) +{ + return static_cast( + (static_cast(data[0]) << 8U) | + static_cast(data[1])); +} + +void WriteBigEndian(uint8_t* data, uint16_t value) +{ + data[0] = static_cast(value >> 8U); + data[1] = static_cast(value & 0xffU); +} + +} // namespace + +bool BinaryAudioBatchBuilder::Push( + const uint8_t* opus, + size_t size) +{ + if (opus == nullptr || size == 0 || + size > kBinaryAudioMaximumUplinkOpusBytes || + Full()) { + return false; + } + Frame& frame = frames_[frame_count_++]; + frame.size = static_cast(size); + std::memcpy(frame.payload.data(), opus, size); + return true; +} + +bool BinaryAudioBatchBuilder::Build( + uint8_t* output, + size_t capacity, + size_t* output_size) const +{ + if (output == nullptr || output_size == nullptr || Empty()) { + return false; + } + size_t payload_size = 0; + for (size_t index = 0; index < frame_count_; ++index) { + payload_size += sizeof(uint16_t) + frames_[index].size; + } + const size_t packet_size = + kBinaryAudioHeaderSize + payload_size; + if (packet_size > capacity || payload_size > UINT16_MAX) { + return false; + } + + output[0] = kBinaryAudioTypeOpus; + output[1] = kBinaryAudioFlagBatch; + WriteBigEndian(output + 2, static_cast(payload_size)); + size_t cursor = kBinaryAudioHeaderSize; + for (size_t index = 0; index < frame_count_; ++index) { + WriteBigEndian(output + cursor, frames_[index].size); + cursor += sizeof(uint16_t); + std::memcpy( + output + cursor, + frames_[index].payload.data(), + frames_[index].size); + cursor += frames_[index].size; + } + *output_size = cursor; + return true; +} + +void BinaryAudioBatchBuilder::Reset() +{ + frame_count_ = 0; +} + +bool BuildBinaryAudioSingleFrame( + const uint8_t* opus, + size_t size, + uint8_t* output, + size_t capacity, + size_t* output_size) +{ + if (opus == nullptr || size == 0 || + size > kBinaryAudioMaximumOpusBytes || + output == nullptr || output_size == nullptr || + capacity < kBinaryAudioHeaderSize + size || + size > UINT16_MAX) { + return false; + } + output[0] = kBinaryAudioTypeOpus; + output[1] = 0; + WriteBigEndian(output + 2, static_cast(size)); + std::memcpy(output + kBinaryAudioHeaderSize, opus, size); + *output_size = kBinaryAudioHeaderSize + size; + return true; +} + +bool VisitBinaryAudioPacket( + const uint8_t* packet, + size_t size, + IBinaryAudioFrameVisitor& visitor, + size_t* frame_count) +{ + if (frame_count != nullptr) { + *frame_count = 0; + } + if (packet == nullptr || size < kBinaryAudioHeaderSize || + packet[0] != kBinaryAudioTypeOpus || + (packet[1] & ~kBinaryAudioFlagBatch) != 0) { + return false; + } + const size_t payload_size = ReadBigEndian(packet + 2); + if (payload_size == 0 || + payload_size != size - kBinaryAudioHeaderSize) { + return false; + } + + const uint8_t* cursor = packet + kBinaryAudioHeaderSize; + size_t remaining = payload_size; + size_t visited = 0; + if ((packet[1] & kBinaryAudioFlagBatch) == 0) { + if (remaining > kBinaryAudioMaximumOpusBytes) { + return false; + } + } else { + // Validate the complete envelope first. A malformed trailing frame + // must not leave the playback pipeline with partially delivered data. + while (remaining != 0) { + if (remaining < sizeof(uint16_t)) { + return false; + } + const size_t frame_size = ReadBigEndian(cursor); + cursor += sizeof(uint16_t); + remaining -= sizeof(uint16_t); + if (frame_size == 0 || + frame_size > kBinaryAudioMaximumOpusBytes || + frame_size > remaining || + visited >= kBinaryAudioBatchFrames) { + return false; + } + cursor += frame_size; + remaining -= frame_size; + visited++; + } + } + + cursor = packet + kBinaryAudioHeaderSize; + remaining = payload_size; + visited = 0; + if ((packet[1] & kBinaryAudioFlagBatch) == 0) { + if (!visitor.OnOpusFrame(cursor, remaining)) { + return false; + } + visited = 1; + } else { + while (remaining != 0) { + const size_t frame_size = ReadBigEndian(cursor); + cursor += sizeof(uint16_t); + remaining -= sizeof(uint16_t); + if (!visitor.OnOpusFrame(cursor, frame_size)) { + return false; + } + cursor += frame_size; + remaining -= frame_size; + visited++; + } + } + if (frame_count != nullptr) { + *frame_count = visited; + } + return visited != 0; +} + +} // namespace borla diff --git a/main/protocol/binary_audio_protocol.h b/main/protocol/binary_audio_protocol.h new file mode 100644 index 0000000..8f61c11 --- /dev/null +++ b/main/protocol/binary_audio_protocol.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +inline constexpr uint8_t kBinaryAudioTypeOpus = 0; +inline constexpr uint8_t kBinaryAudioFlagBatch = 0x01; +inline constexpr size_t kBinaryAudioHeaderSize = 4; +inline constexpr size_t kBinaryAudioMaximumOpusBytes = 1536; +inline constexpr size_t kBinaryAudioMaximumUplinkOpusBytes = 512; +inline constexpr size_t kBinaryAudioBatchFrames = 5; +inline constexpr size_t kBinaryAudioMaximumPacketBytes = + kBinaryAudioHeaderSize + + kBinaryAudioBatchFrames * + (sizeof(uint16_t) + kBinaryAudioMaximumUplinkOpusBytes); + +class BinaryAudioBatchBuilder final { +public: + bool Push(const uint8_t* opus, size_t size); + bool Full() const { return frame_count_ == kBinaryAudioBatchFrames; } + bool Empty() const { return frame_count_ == 0; } + size_t FrameCount() const { return frame_count_; } + bool Build( + uint8_t* output, + size_t capacity, + size_t* output_size) const; + void Reset(); + +private: + struct Frame { + uint16_t size = 0; + std::array< + uint8_t, + kBinaryAudioMaximumUplinkOpusBytes> + payload{}; + }; + + std::array frames_{}; + size_t frame_count_ = 0; +}; + +class IBinaryAudioFrameVisitor { +public: + virtual ~IBinaryAudioFrameVisitor() = default; + virtual bool OnOpusFrame( + const uint8_t* data, + size_t size) = 0; +}; + +bool BuildBinaryAudioSingleFrame( + const uint8_t* opus, + size_t size, + uint8_t* output, + size_t capacity, + size_t* output_size); + +bool VisitBinaryAudioPacket( + const uint8_t* packet, + size_t size, + IBinaryAudioFrameVisitor& visitor, + size_t* frame_count = nullptr); + +} // namespace borla diff --git a/main/protocol/protocol_message_builder.cc b/main/protocol/protocol_message_builder.cc new file mode 100644 index 0000000..7b7b80a --- /dev/null +++ b/main/protocol/protocol_message_builder.cc @@ -0,0 +1,416 @@ +#include "protocol/protocol_message_builder.h" + +#include "protocol/utf8_text.h" + +#include + +#include + +namespace borla { + +bool ProtocolMessageBuilder::BuildHello( + uint8_t protocol_version, + char* output, + size_t capacity, + size_t* output_size) const +{ + return BuildHello( + protocol_version, + nullptr, + output, + capacity, + output_size); +} + +bool ProtocolMessageBuilder::BuildHello( + uint8_t protocol_version, + const MemorySnapshot* memory, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + cJSON* features = cJSON_CreateObject(); + cJSON* audio = cJSON_CreateObject(); + if (root == nullptr || features == nullptr || audio == nullptr) { + cJSON_Delete(root); + cJSON_Delete(features); + cJSON_Delete(audio); + return false; + } + + cJSON_AddStringToObject(root, "type", "hello"); + cJSON_AddNumberToObject(root, "version", protocol_version); + cJSON_AddStringToObject(root, "transport", "websocket"); + cJSON_AddBoolToObject(features, "mcp", true); + cJSON_AddBoolToObject(features, "local_audio", true); + cJSON_AddBoolToObject( + features, "play_local_sequence", true); + cJSON_AddBoolToObject( + features, "barge_in_two_phase", true); + cJSON_AddItemToObject(root, "features", features); + cJSON_AddStringToObject(audio, "format", "opus"); + cJSON_AddNumberToObject(audio, "sample_rate", 16000); + cJSON_AddNumberToObject(audio, "channels", 1); + cJSON_AddNumberToObject(audio, "frame_duration", 60); + cJSON_AddItemToObject(root, "audio_params", audio); + if (memory != nullptr && memory->HasData() && + IsValidMemorySnapshot(*memory)) { + cJSON* cache = cJSON_CreateObject(); + if (cache == nullptr) { + cJSON_Delete(root); + return false; + } + if (memory->child_name[0] != '\0') { + cJSON_AddStringToObject( + cache, + "child_name", + memory->child_name.data()); + } + if (memory->brain_text[0] != '\0') { + cJSON_AddStringToObject( + cache, + "brain_text", + memory->brain_text.data()); + } + cJSON_AddNumberToObject( + cache, + "interaction_count", + memory->interaction_count); + cJSON_AddItemToObject(root, "memory_cache", cache); + } + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildStartListening( + const char* session_id, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || session_id == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "session_id", session_id); + cJSON_AddStringToObject(root, "type", "listen"); + cJSON_AddStringToObject(root, "state", "start"); + cJSON_AddStringToObject(root, "mode", "auto"); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildStopListening( + const char* session_id, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || session_id == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "session_id", session_id); + cJSON_AddStringToObject(root, "type", "listen"); + cJSON_AddStringToObject(root, "state", "stop"); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildAbort( + const char* session_id, + ConversationInterruptSource source, + const char* playback_text, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || session_id == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "session_id", session_id); + cJSON_AddStringToObject(root, "type", "abort"); + cJSON_AddStringToObject( + root, + "reason", + source == ConversationInterruptSource::kWakeWordDetected + ? "wake_word_detected" + : "user_initiated"); + if (playback_text != nullptr && playback_text[0] != '\0') { + const size_t kept = utf8_text::SafeTruncatedLength( + playback_text, + std::strlen(playback_text), + kPlaybackTextBytes); + if (kept != 0) { + // cJSON escapes quotes and control characters on its own, so the + // only way this field can corrupt the frame is an encoding split — + // which is exactly what SafeTruncatedLength rules out. + char truncated[kPlaybackTextBytes + 1] = {}; + std::memcpy(truncated, playback_text, kept); + cJSON_AddStringToObject( + root, "playback_text", truncated); + } + } + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildPing( + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON_AddStringToObject(root, "type", "ping"); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildTraceMarker( + const char* trace_id, + const char* stage, + uint64_t sequence, + size_t frames, + size_t bytes, + uint64_t client_send_ms, + int64_t client_epoch_ms, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || stage == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "type", "trace"); + if (trace_id != nullptr && trace_id[0] != '\0') { + cJSON_AddStringToObject(root, "trace_id", trace_id); + } + cJSON_AddStringToObject(root, "stage", stage); + cJSON_AddNumberToObject( + root, "seq", static_cast(sequence)); + cJSON_AddNumberToObject( + root, "frames", static_cast(frames)); + cJSON_AddNumberToObject( + root, "bytes", static_cast(bytes)); + cJSON_AddNumberToObject( + root, + "client_send_ms", + static_cast(client_send_ms)); + cJSON_AddNumberToObject( + root, + "client_epoch_ms", + static_cast(client_epoch_ms)); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildGoodbye( + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON_AddStringToObject(root, "type", "goodbye"); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildPong( + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON_AddStringToObject(root, "type", "pong"); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildButton( + uint8_t click_count, + char* output, + size_t capacity, + size_t* output_size) const +{ + if (click_count != 3 && click_count != 4) { + return false; + } + cJSON* root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON_AddStringToObject(root, "type", "button"); + cJSON_AddNumberToObject(root, "count", click_count); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildLocalPlaybackState( + const char* group, + bool started, + char* output, + size_t capacity, + size_t* output_size) const +{ + if (group == nullptr || group[0] == '\0') { + return false; + } + cJSON* root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON_AddStringToObject(root, "type", "play_local"); + cJSON_AddStringToObject( + root, "state", started ? "start" : "done"); + cJSON_AddStringToObject(root, "group", group); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildStatus( + uint8_t battery_percent, + uint16_t battery_voltage_mv, + bool charging, + const char* version, + int16_t volume_percent, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || version == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "type", "status"); + cJSON_AddNumberToObject(root, "battery", battery_percent); + cJSON_AddNumberToObject( + root, "battery_voltage_mv", battery_voltage_mv); + cJSON_AddBoolToObject(root, "charging", charging); + cJSON_AddStringToObject(root, "version", version); + if (volume_percent >= 0) { + cJSON_AddNumberToObject(root, "volume", volume_percent); + } + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildAlarmFired( + int32_t alarm_id, + int64_t fired_at_epoch, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON_AddStringToObject(root, "type", "alarm_fired"); + cJSON_AddNumberToObject(root, "id", alarm_id); + cJSON_AddNumberToObject( + root, "fired_at", static_cast(fired_at_epoch)); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildCallAction( + const char* state, + const char* call_id, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || state == nullptr || call_id == nullptr || + call_id[0] == '\0') { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "type", "call"); + cJSON_AddStringToObject(root, "state", state); + cJSON_AddStringToObject(root, "call_id", call_id); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildOtaNotify( + const char* text, + bool optional, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || text == nullptr || text[0] == '\0') { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "type", "ota_notify"); + cJSON_AddStringToObject(root, "text", text); + if (optional) { + // Only emitted for advisory notices so the existing server contract + // (absent field == mandatory upgrade) is preserved byte for byte. + cJSON_AddBoolToObject(root, "optional", true); + } + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::BuildFriendAdd( + const char* local_mac, + const char* local_name, + const char* remote_mac, + const char* remote_name, + char* output, + size_t capacity, + size_t* output_size) const +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || local_mac == nullptr || + local_name == nullptr || remote_mac == nullptr || + remote_name == nullptr || local_mac[0] == '\0' || + remote_mac[0] == '\0') { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(root, "type", "friend_add"); + cJSON_AddStringToObject(root, "local_mac", local_mac); + cJSON_AddStringToObject(root, "local_name", local_name); + cJSON_AddStringToObject(root, "remote_mac", remote_mac); + cJSON_AddStringToObject(root, "remote_name", remote_name); + return Print(root, output, capacity, output_size); +} + +bool ProtocolMessageBuilder::Print( + void* opaque_root, + char* output, + size_t capacity, + size_t* output_size) const +{ + auto* root = static_cast(opaque_root); + if (root == nullptr || output == nullptr || + capacity == 0 || output_size == nullptr) { + cJSON_Delete(root); + return false; + } + + char* rendered = cJSON_PrintUnformatted(root); + cJSON_Delete(root); + if (rendered == nullptr) { + return false; + } + const size_t size = std::strlen(rendered); + if (size >= capacity) { + cJSON_free(rendered); + return false; + } + std::memcpy(output, rendered, size + 1); + *output_size = size; + cJSON_free(rendered); + return true; +} + +} // namespace borla diff --git a/main/protocol/protocol_message_builder.h b/main/protocol/protocol_message_builder.h new file mode 100644 index 0000000..8a810c2 --- /dev/null +++ b/main/protocol/protocol_message_builder.h @@ -0,0 +1,136 @@ +#pragma once + +#include "core/runtime_state.h" +#include "memory/memory_types.h" + +#include +#include + +namespace borla { + +class ProtocolMessageBuilder final { +public: + bool BuildHello( + uint8_t protocol_version, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildHello( + uint8_t protocol_version, + const MemorySnapshot* memory, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildStartListening( + const char* session_id, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildStopListening( + const char* session_id, + char* output, + size_t capacity, + size_t* output_size) const; + // playback_text is the sentence the speaker was in the middle of when the + // turn was interrupted, or nullptr/"" when nothing was playing. The server + // needs it to know how much of its reply the child actually heard, so the + // next turn continues from there instead of from the full untruncated + // reply. Capped at kPlaybackTextBytes on a UTF-8 character boundary. + static constexpr size_t kPlaybackTextBytes = 100; + + bool BuildAbort( + const char* session_id, + ConversationInterruptSource source, + const char* playback_text, + char* output, + size_t capacity, + size_t* output_size) const; + // Latency/clock-skew marker for one uplink audio batch. The server reads + // client_send_ms and client_epoch_ms out of this message + // (connection.py _update_trace_from_payload) and derives the device-to- + // server clock delta from them. client_epoch_ms is 0 when the wall clock + // has not been synced yet, which the server treats as "unknown" rather + // than as a bogus 1970 timestamp. + bool BuildTraceMarker( + const char* trace_id, + const char* stage, + uint64_t sequence, + size_t frames, + size_t bytes, + uint64_t client_send_ms, + int64_t client_epoch_ms, + char* output, + size_t capacity, + size_t* output_size) const; + + bool BuildGoodbye( + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildPing( + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildPong( + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildButton( + uint8_t click_count, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildLocalPlaybackState( + const char* group, + bool started, + char* output, + size_t capacity, + size_t* output_size) const; + // volume_percent is emitted only when >= 0 so the ServerHello status frame + // (sent before the audio engine is queried) keeps its original shape. + bool BuildStatus( + uint8_t battery_percent, + uint16_t battery_voltage_mv, + bool charging, + const char* version, + int16_t volume_percent, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildAlarmFired( + int32_t alarm_id, + int64_t fired_at_epoch, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildCallAction( + const char* state, + const char* call_id, + char* output, + size_t capacity, + size_t* output_size) const; + bool BuildOtaNotify( + const char* text, + bool optional, + char* output, + size_t capacity, + size_t* output_size) const; + + bool BuildFriendAdd( + const char* local_mac, + const char* local_name, + const char* remote_mac, + const char* remote_name, + char* output, + size_t capacity, + size_t* output_size) const; + +private: + bool Print( + void* root, + char* output, + size_t capacity, + size_t* output_size) const; +}; + +} // namespace borla diff --git a/main/protocol/realtime_binary_sink.h b/main/protocol/realtime_binary_sink.h new file mode 100644 index 0000000..5d099ab --- /dev/null +++ b/main/protocol/realtime_binary_sink.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace borla { + +class IRealtimeBinarySink { +public: + virtual ~IRealtimeBinarySink() = default; + virtual void OnRealtimeBinary( + const uint8_t* data, + size_t size, + uint32_t playback_session_id) = 0; +}; + +} // namespace borla diff --git a/main/protocol/realtime_config.cc b/main/protocol/realtime_config.cc new file mode 100644 index 0000000..a35779e --- /dev/null +++ b/main/protocol/realtime_config.cc @@ -0,0 +1,129 @@ +#include "protocol/realtime_config.h" + +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "RealtimeConfig2"; +constexpr const char* kNamespace = "websocket"; +constexpr const char* kFallbackUrl = kDefaultRealtimeUrl; + +template +void CopyLiteral(std::array* output, const char* value) +{ + output->fill('\0'); + if (value != nullptr) { + std::strncpy(output->data(), value, output->size() - 1); + } +} + +template +bool ReadString( + nvs_handle_t handle, + const char* key, + std::array* output) +{ + size_t size = output->size(); + output->fill('\0'); + return nvs_get_str(handle, key, output->data(), &size) == ESP_OK; +} + +} // namespace + +bool NvsRealtimeConfigStore::SaveEndpoint( + const char* url, + const char* token) +{ + if ((url == nullptr || url[0] == '\0') && + (token == nullptr || token[0] == '\0')) { + return true; + } + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNamespace, NVS_READWRITE, &handle); + if (result != ESP_OK) { + ESP_LOGE(kTag, "open writable namespace failed: %s", + esp_err_to_name(result)); + return false; + } + if (url != nullptr && url[0] != '\0') { + result = nvs_set_str(handle, "url", url); + } + if (result == ESP_OK && token != nullptr && token[0] != '\0') { + result = nvs_set_str(handle, "token", token); + } + if (result == ESP_OK) { + result = nvs_set_i32(handle, "version", 3); + } + if (result == ESP_OK) { + result = nvs_commit(handle); + } + nvs_close(handle); + if (result != ESP_OK) { + ESP_LOGE(kTag, "endpoint save failed: %s", + esp_err_to_name(result)); + return false; + } + ESP_LOGI(kTag, "endpoint persisted url=%s token=%s", + url != nullptr && url[0] != '\0' ? url : "(unchanged)", + token != nullptr && token[0] != '\0' + ? "present" + : "(unchanged)"); + return true; +} + +bool NvsRealtimeConfigStore::Load(RealtimeConfig* output) const +{ + if (output == nullptr) { + return false; + } + + RealtimeConfig config; + CopyLiteral(&config.transport.url, kFallbackUrl); + + nvs_handle_t handle = 0; + const esp_err_t open_result = + nvs_open(kNamespace, NVS_READONLY, &handle); + if (open_result == ESP_OK) { + std::array saved_url{}; + if (ReadString(handle, "url", &saved_url) && + saved_url[0] != '\0') { + config.transport.url = saved_url; + } + ReadString(handle, "token", &config.transport.token); + + int32_t version = 0; + if (nvs_get_i32(handle, "version", &version) == ESP_OK && + version > 0 && version <= UINT8_MAX) { + config.transport.protocol_version = + static_cast(version); + } + nvs_close(handle); + } else if (open_result != ESP_ERR_NVS_NOT_FOUND) { + ESP_LOGE(kTag, "open namespace failed: %s", + esp_err_to_name(open_result)); + return false; + } + + if (config.transport.protocol_version != 3) { + ESP_LOGW(kTag, "forcing protocol version 3 instead of %u", + static_cast( + config.transport.protocol_version)); + config.transport.protocol_version = 3; + } + *output = config; + ESP_LOGI(kTag, "loaded endpoint url=%s protocol=%u token=%s", + output->transport.url.data(), + static_cast( + output->transport.protocol_version), + output->transport.token[0] == '\0' ? "absent" : "present"); + return true; +} + +} // namespace borla diff --git a/main/protocol/realtime_config.h b/main/protocol/realtime_config.h new file mode 100644 index 0000000..6aa7436 --- /dev/null +++ b/main/protocol/realtime_config.h @@ -0,0 +1,41 @@ +#pragma once + +#include "protocol/websocket_transport.h" + +namespace borla { + +// Build default used when NVS holds nothing, and the replacement applied when +// a stored/pushed endpoint turns out to be a retired staging host. +inline constexpr const char* kDefaultRealtimeUrl = + "wss://borlaws.lkall.com/v1/ws"; + +struct RealtimeConfig { + WebsocketTransportConfig transport; + uint32_t hello_timeout_ms = 15000; + uint32_t heartbeat_interval_ms = 30000; + uint32_t heartbeat_timeout_ms = 90000; +}; + +class IRealtimeConfigStore { +public: + virtual ~IRealtimeConfigStore() = default; + virtual bool Load(RealtimeConfig* output) const = 0; + + // Persist an endpoint handed down by the OTA check response. `token` may + // be null to leave the stored token untouched. Returns false only on a + // real NVS failure; the caller treats that as non-fatal because the + // in-memory endpoint is still usable for this boot. + virtual bool SaveEndpoint( + const char* url, + const char* token) = 0; +}; + +class NvsRealtimeConfigStore final : public IRealtimeConfigStore { +public: + bool Load(RealtimeConfig* output) const override; + bool SaveEndpoint( + const char* url, + const char* token) override; +}; + +} // namespace borla diff --git a/main/protocol/realtime_protocol.cc b/main/protocol/realtime_protocol.cc new file mode 100644 index 0000000..efc3fd6 --- /dev/null +++ b/main/protocol/realtime_protocol.cc @@ -0,0 +1,1546 @@ +#include "protocol/realtime_protocol.h" + +#include "connectivity/wifi_types.h" +#include "core/psram_object.h" +#include "diagnostics/device_log_formatter.h" +#include "diagnostics/trace_context.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "RealtimeProtocol2"; +constexpr const char* kConversationTag = "ConversationText2"; + +// Conversation lines are what a human actually reads when watching a session, +// and they used to be indistinguishable from the surrounding state-machine +// chatter. These wrap them in colour and a direction marker. +// +// The escapes are emitted directly rather than through ESP_LOG's own colouring +// because CONFIG_LOG_COLORS is off in this build — IDF adds nothing, so there +// is nothing to compose with. Set the three constants to "" if the log ever has +// to be piped somewhere that cannot handle ANSI. +constexpr const char* kUserColor = "\033[1;36m"; // bright cyan +constexpr const char* kDeviceColor = "\033[1;32m"; // bright green +constexpr const char* kEmotionColor = "\033[0;35m"; // magenta +constexpr const char* kColorReset = "\033[0m"; +constexpr uint32_t kHelloBuildError = 3301; +constexpr uint32_t kHelloTimeoutError = 3302; +constexpr uint32_t kHeartbeatTimeoutError = 3303; +constexpr uint32_t kTransportSendError = 3304; +constexpr uint32_t kInvalidServerHelloError = 3305; +constexpr uint32_t kMissingCallIdError = 3390; +constexpr char kHeartbeatPingMessage[] = "{\"type\":\"ping\"}"; + +// ClientHello needs a ~2 KB memory snapshot plus a ~2.5 KB text buffer. Both +// used to be stack locals, which put a ~4.7 KB frame on the WebSocket task +// right underneath the TLS write. Keep the pair in PSRAM instead. +struct HelloScratch { + MemorySnapshot memory{}; + std::array message{}; +}; + +const char* ProtocolPromptGroup(LocalPrompt prompt) +{ + if (prompt == LocalPrompt::kActivationDevice) { + return "activation_prompt"; + } + if (prompt == LocalPrompt::kProvisioning) { + return "wifi_config"; + } + return ToString(prompt); +} + +class MutexGuard final { +public: + explicit MutexGuard(SemaphoreHandle_t mutex) + : mutex_(mutex) + { + if (mutex_ != nullptr) { + xSemaphoreTake(mutex_, portMAX_DELAY); + } + } + + ~MutexGuard() + { + if (mutex_ != nullptr) { + xSemaphoreGive(mutex_); + } + } + +private: + SemaphoreHandle_t mutex_; +}; + +} // namespace + +RealtimeProtocol::RealtimeProtocol( + IWebsocketTransport& transport, + IRealtimeConfigStore& config_store) + : transport_(transport), + config_store_(config_store), + reconnect_backoff_(ReconnectBackoffConfig{ + 1000, + kProtocolRetryMaximumMs, + 2, + 20, + }) +{ +} + +RealtimeProtocol::~RealtimeProtocol() +{ + if (incoming_command_ != nullptr) { + incoming_command_->~ServerCommand(); + heap_caps_free(incoming_command_); + incoming_command_ = nullptr; + } +} + +bool RealtimeProtocol::Initialize(const DeviceIdentity& identity) +{ + if (initialized_) { + return true; + } + mutex_ = xSemaphoreCreateMutexStatic(&mutex_storage_); + if (mutex_ == nullptr || !config_store_.Load(&config_)) { + ESP_LOGE(kTag, "configuration initialization failed"); + return false; + } + if (incoming_command_ == nullptr) { + incoming_command_ = static_cast(heap_caps_malloc( + sizeof(ServerCommand), + MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); + if (incoming_command_ == nullptr) { + ESP_LOGE(kTag, "incoming command PSRAM allocation failed"); + return false; + } + new (incoming_command_) ServerCommand(); + } + + std::snprintf( + config_.transport.device_id.data(), + config_.transport.device_id.size(), + "%s", + identity.mac); + std::snprintf( + config_.transport.firmware_version.data(), + config_.transport.firmware_version.size(), + "%s", + identity.app_version); + + if (!transport_.Initialize()) { + ESP_LOGE(kTag, "transport initialization failed"); + return false; + } + + const esp_timer_create_args_t timer_args = { + .callback = &RealtimeProtocol::TimerCallback, + .arg = this, + .dispatch_method = ESP_TIMER_TASK, + .name = "realtime_tick2", + .skip_unhandled_events = true, + }; + if (esp_timer_create(&timer_args, &timer_) != ESP_OK) { + timer_ = nullptr; + ESP_LOGE(kTag, "lifecycle timer creation failed"); + return false; + } + if (esp_timer_start_periodic(timer_, 1000ULL * 1000ULL) != ESP_OK) { + esp_timer_delete(timer_); + timer_ = nullptr; + ESP_LOGE(kTag, "lifecycle timer start failed"); + return false; + } + initialized_ = true; + ESP_LOGI(kTag, "initialized hello_timeout=%lu heartbeat=%lu/%lu ms", + static_cast(config_.hello_timeout_ms), + static_cast(config_.heartbeat_interval_ms), + static_cast(config_.heartbeat_timeout_ms)); + return true; +} + +void RealtimeProtocol::Open() +{ + if (!initialized_) { + ESP_LOGE(kTag, "open ignored before initialization"); + return; + } + + bool open_now = false; + { + MutexGuard lock(mutex_); + intentional_close_ = false; + disconnect_reported_ = false; + if (phase_ == RealtimeConnectionPhase::kConnecting || + phase_ == RealtimeConnectionPhase::kAwaitingHello || + phase_ == RealtimeConnectionPhase::kOpen || + phase_ == RealtimeConnectionPhase::kClosingAfterError) { + return; + } + + const uint64_t now = NowMs(); + if (reconnect_at_ms_ != 0 && now < reconnect_at_ms_) { + pending_open_ = true; + ESP_LOGI(kTag, "open deferred for %llu ms", + static_cast( + reconnect_at_ms_ - now)); + return; + } + phase_ = RealtimeConnectionPhase::kConnecting; + diagnostics_.phase = phase_; + pending_open_ = false; + open_now = true; + } + + if (open_now && !transport_.Open(config_.transport, *this)) { + OnWebsocketDisconnected(kTransportSendError); + } +} + +void RealtimeProtocol::Close() +{ + if (!initialized_) { + return; + } + { + MutexGuard lock(mutex_); + intentional_close_ = true; + pending_open_ = false; + disconnect_reported_ = true; + phase_ = RealtimeConnectionPhase::kClosed; + active_tts_session_ = 0; + playback_text_[0] = '\0'; + ClearCallLocked(); + listening_uplink_enabled_ = false; + barge_in_enabled_ = false; + tts_tail_uplink_enabled_ = false; + call_uplink_enabled_ = false; + audio_batch_.Reset(); + diagnostics_.phase = phase_; + diagnostics_.active_tts_session = 0; + reconnect_at_ms_ = 0; + reconnect_backoff_.Reset(); + } + transport_.Close(); +} + +void RealtimeProtocol::SendStartListening() +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildStartListening( + diagnostics_.session_id.data(), + message.data(), + message.size(), + &size)) { + return; + } + listening_uplink_enabled_ = true; + // A new turn begins here; the id ties the uplink audio, the ASR text + // and the reply back together across device/server logs. + TraceContext::RefreshTrace("turn"); + // tts:stop only closes the producer. Reaching listen:start means the + // local playback queue has physically drained, so normal batched + // listening can replace the single-frame TTS-tail uplink. + tts_tail_uplink_enabled_ = false; + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendStopListening() +{ + std::array message{}; + size_t size = 0; + size_t audio_size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildStopListening( + diagnostics_.session_id.data(), + message.data(), + message.size(), + &size)) { + return; + } + listening_uplink_enabled_ = false; + TakeAudioBatchLocked(&audio_size); + } + if (audio_size != 0 && + !transport_.SendBinary(audio_packet_.data(), audio_size)) { + RequestErrorClose(kTransportSendError); + return; + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendAbortSpeaking( + ConversationInterruptSource source) +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildAbort( + diagnostics_.session_id.data(), + source, + playback_text_.data(), + message.data(), + message.size(), + &size)) { + return; + } + playback_text_[0] = '\0'; + active_tts_session_ = 0; + tts_tail_uplink_enabled_ = false; + diagnostics_.active_tts_session = 0; + if (!UplinkEnabledLocked()) { + audio_batch_.Reset(); + } + } + ESP_LOGI(kTag, "abort requested source=%s", ToString(source)); + SendBuiltMessage(message.data(), size); +} + +bool RealtimeProtocol::SubmitEncodedAudio( + const uint8_t* data, + size_t size) +{ + size_t packet_size = 0; + bool low_latency_barge_in = false; + size_t batch_frames = 0; + uint64_t trace_sequence = 0; + uint64_t trace_send_ms = 0; + bool trace_due = false; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !UplinkEnabledLocked()) { + return false; + } + low_latency_barge_in = + barge_in_enabled_ && + (active_tts_session_ != 0 || tts_tail_uplink_enabled_) && + !listening_uplink_enabled_ && !call_uplink_enabled_; + if (low_latency_barge_in) { + // A TTS session starts only after the normal listen path has + // flushed. Do not carry a stale partial batch into the low-latency + // barge-in window. + audio_batch_.Reset(); + if (!BuildBinaryAudioSingleFrame( + data, + size, + audio_packet_.data(), + audio_packet_.size(), + &packet_size)) { + return false; + } + } else if (!audio_batch_.Push(data, size)) { + return false; + } + if (low_latency_barge_in) { + // Send below without waiting for the normal five-frame batch. + batch_frames = 1; + } else if (!audio_batch_.Full()) { + return true; + } else { + // Read the count before TakeAudioBatchLocked resets the builder. + batch_frames = audio_batch_.FrameCount(); + if (!TakeAudioBatchLocked(&packet_size)) { + return false; + } + } + trace_sequence = ++trace_audio_batch_sequence_; + trace_send_ms = NowMs(); + trace_due = ShouldTraceAudioBatchLocked( + trace_sequence, batch_frames, packet_size, trace_send_ms); + } + if (!transport_.SendBinary( + audio_packet_.data(), packet_size)) { + return false; + } + if (trace_due) { + // After the audio, so the marker can never delay the frames it + // describes, and outside the lock because SendBuiltMessage takes it. + SendAudioBatchTrace( + trace_sequence, batch_frames, packet_size, trace_send_ms); + } + return true; +} + +int64_t RealtimeProtocol::EpochMs() +{ + struct timeval now {}; + if (gettimeofday(&now, nullptr) != 0) { + return 0; + } + // Before NTP lands the clock reads 1970. Reporting that as an epoch would + // make the server compute a 56-year skew, so say "unknown" instead. + if (now.tv_sec < 1700000000) { + return 0; + } + return static_cast(now.tv_sec) * 1000 + + now.tv_usec / 1000; +} + +bool RealtimeProtocol::ShouldTraceAudioBatchLocked( + uint64_t sequence, + size_t frames, + size_t bytes, + uint64_t now_ms) +{ + if (last_trace_audio_batch_ms_ == 0 || sequence == 1) { + last_trace_audio_batch_ms_ = now_ms; + last_trace_audio_batch_frames_ = frames; + last_trace_audio_batch_bytes_ = bytes; + return true; + } + + const size_t previous_bytes = + last_trace_audio_batch_bytes_ != 0 + ? last_trace_audio_batch_bytes_ + : 1; + const size_t byte_delta = + bytes > last_trace_audio_batch_bytes_ + ? bytes - last_trace_audio_batch_bytes_ + : last_trace_audio_batch_bytes_ - bytes; + const bool frames_changed = + frames != last_trace_audio_batch_frames_; + const bool bytes_changed = + byte_delta >= kAudioTraceMinimumByteDelta && + static_cast(byte_delta) / + static_cast(previous_bytes) >= + kAudioTraceRelativeChange; + const bool heartbeat = + now_ms >= last_trace_audio_batch_ms_ && + now_ms - last_trace_audio_batch_ms_ >= + kAudioTraceHeartbeatMs; + + if (!frames_changed && !bytes_changed && !heartbeat) { + return false; + } + last_trace_audio_batch_ms_ = now_ms; + last_trace_audio_batch_frames_ = frames; + last_trace_audio_batch_bytes_ = bytes; + return true; +} + +void RealtimeProtocol::SendAudioBatchTrace( + uint64_t sequence, + size_t frames, + size_t bytes, + uint64_t client_send_ms) +{ + std::array marker{}; + size_t size = 0; + if (!builder_.BuildTraceMarker( + TraceContext::TraceId(), + "ws.audio_batch.send", + sequence, + frames, + bytes, + client_send_ms, + EpochMs(), + marker.data(), + marker.size(), + &size)) { + return; + } + SendBuiltMessage(marker.data(), size); +} + +void RealtimeProtocol::FlushEncodedAudio() +{ + size_t packet_size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !TakeAudioBatchLocked(&packet_size)) { + return; + } + } + if (!transport_.SendBinary( + audio_packet_.data(), packet_size)) { + ESP_LOGW(kTag, "audio batch flush dropped by transport"); + } +} + +bool RealtimeProtocol::SendSensorMessage( + const char* data, + size_t size) +{ + if (data == nullptr || size == 0 || + size >= kMessageCapacity) { + return false; + } + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen) { + return false; + } + } + return transport_.SendTelemetryText(data, size); +} + +bool RealtimeProtocol::SendAlarmFired( + int32_t alarm_id, + int64_t fired_at_epoch) +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildAlarmFired( + alarm_id, + fired_at_epoch, + message.data(), + message.size(), + &size)) { + return false; + } + } + return SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendAcceptCall() +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildCallAction( + "accept", + active_call_id_.data(), + message.data(), + message.size(), + &size)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, + kMissingCallIdError)); + return; + } + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendHangupCall() +{ + std::array message{}; + size_t size = 0; + size_t audio_size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildCallAction( + "hangup", + active_call_id_.data(), + message.data(), + message.size(), + &size)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, + kMissingCallIdError)); + return; + } + call_uplink_enabled_ = false; + TakeAudioBatchLocked(&audio_size); + } + if (audio_size != 0 && + !transport_.SendBinary(audio_packet_.data(), audio_size)) { + RequestErrorClose(kTransportSendError); + return; + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendButtonClick(uint8_t click_count) +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildButton( + click_count, + message.data(), + message.size(), + &size)) { + return; + } + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendGoodbye() +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildGoodbye( + message.data(), message.size(), &size)) { + return; + } + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::SendLocalPlaybackState( + LocalPrompt prompt, + bool started) +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildLocalPlaybackState( + ProtocolPromptGroup(prompt), + started, + message.data(), + message.size(), + &size)) { + return; + } + } + SendBuiltMessage(message.data(), size); +} + +bool RealtimeProtocol::SendFriendAdd( + const char* local_mac, + const char* local_name, + const char* remote_mac, + const char* remote_name) +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildFriendAdd( + local_mac, + local_name, + remote_mac, + remote_name, + message.data(), + message.size(), + &size)) { + return false; + } + } + return SendBuiltMessage(message.data(), size); +} + +bool RealtimeProtocol::SendOtaNotify( + const char* text, + bool optional) +{ + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildOtaNotify( + text, + optional, + message.data(), + message.size(), + &size)) { + return false; + } + } + return SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::RequestConnectionErrorPrompt() +{ + if (remote_behavior_config_ == nullptr) { + return; + } + Publish(AppEvent::Make( + AppEventType::kLocalPromptRequested, + 0, + static_cast( + remote_behavior_config_->ServerUnreachablePrompt()), + static_cast(PlaybackPriority::kSystem))); +} + +RealtimeDiagnostics RealtimeProtocol::GetDiagnostics() const +{ + MutexGuard lock(mutex_); + return diagnostics_; +} + +uint32_t RealtimeProtocol::ActiveTtsSession() const +{ + MutexGuard lock(mutex_); + return active_tts_session_; +} + +void RealtimeProtocol::OnWebsocketConnected() +{ + auto scratch = MakePsramObject(); + if (!scratch) { + ESP_LOGE(kTag, "ClientHello scratch allocation failed"); + RequestErrorClose(kHelloBuildError); + return; + } + std::array& hello = scratch->message; + size_t hello_size = 0; + bool close_immediately = false; + MemorySnapshot& memory = scratch->memory; + if (memory_cache_ != nullptr) { + memory_cache_->CopySnapshot(&memory); + } + const bool has_memory = + memory_cache_ != nullptr && memory.HasData(); + { + MutexGuard lock(mutex_); + if (intentional_close_) { + close_immediately = true; + } else { + const uint64_t now = NowMs(); + disconnect_reported_ = false; + phase_ = RealtimeConnectionPhase::kAwaitingHello; + diagnostics_.phase = phase_; + hello_deadline_ms_ = now + config_.hello_timeout_ms; + last_incoming_ms_ = now; + last_ping_ms_ = now; + last_status_ms_ = now; + diagnostics_.last_incoming_ms = now; + bool built = builder_.BuildHello( + config_.transport.protocol_version, + has_memory ? &memory : nullptr, + hello.data(), + hello.size(), + &hello_size); + if (!built && has_memory) { + ESP_LOGW(kTag, + "memory cache omitted because hello exceeds capacity"); + built = builder_.BuildHello( + config_.transport.protocol_version, + hello.data(), + hello.size(), + &hello_size); + } + if (!built) { + phase_ = RealtimeConnectionPhase::kClosingAfterError; + diagnostics_.phase = phase_; + } + } + } + + if (close_immediately) { + transport_.Close(); + return; + } + if (hello_size == 0) { + RequestErrorClose(kHelloBuildError); + return; + } + if (!SendBuiltMessage(hello.data(), hello_size)) { + RequestErrorClose(kTransportSendError); + return; + } + ESP_LOGI(kTag, + "ClientHello queued stack_free_bytes=%u", + static_cast( + uxTaskGetStackHighWaterMark(nullptr))); +} + +void RealtimeProtocol::OnWebsocketDisconnected(int error_code) +{ + bool publish_disconnected = false; + bool server_was_reachable = false; + { + MutexGuard lock(mutex_); + if (intentional_close_) { + phase_ = RealtimeConnectionPhase::kClosed; + diagnostics_.phase = phase_; + return; + } + if (!disconnect_reported_) { + publish_disconnected = true; + disconnect_reported_ = true; + } + server_was_reachable = + phase_ == RealtimeConnectionPhase::kOpen; + phase_ = RealtimeConnectionPhase::kClosed; + active_tts_session_ = 0; + playback_text_[0] = '\0'; + ClearCallLocked(); + listening_uplink_enabled_ = false; + barge_in_enabled_ = false; + tts_tail_uplink_enabled_ = false; + call_uplink_enabled_ = false; + audio_batch_.Reset(); + diagnostics_.phase = phase_; + diagnostics_.active_tts_session = 0; + diagnostics_.transport_error_count++; + ScheduleReconnectLocked(NowMs()); + } + // Heap snapshot on the same line: every disconnect so far has been an + // internal-RAM starvation symptom (esp-aes alloc, select() ENOMEM), and + // the periodic diagnostics line is too sparse to catch the trough. + ESP_LOGW(kTag, + "transport disconnected error=%d internal_free=%u largest=%u", + error_code, + static_cast( + heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL))); + if (publish_disconnected) { + Publish(AppEvent::Make( + AppEventType::kRealtimeDisconnected, + static_cast( + error_code < 0 ? -error_code : error_code))); + if (!server_was_reachable && + remote_behavior_config_ != nullptr) { + Publish(AppEvent::Make( + AppEventType::kLocalPromptRequested, + 0, + static_cast( + remote_behavior_config_-> + ServerUnreachablePrompt()), + static_cast( + PlaybackPriority::kSystem))); + } + } +} + +void RealtimeProtocol::OnWebsocketText( + const char* data, + size_t size) +{ + if (incoming_command_ == nullptr || + !dispatcher_.ParseInto(data, size, incoming_command_)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3101)); + return; + } + const ServerCommand& command = *incoming_command_; + if (command.type == ServerCommandType::kHello) { + ESP_LOGI(kTag, + "ServerHello parsed stack_free_bytes=%u", + static_cast( + uxTaskGetStackHighWaterMark(nullptr))); + } + { + MutexGuard lock(mutex_); + last_incoming_ms_ = NowMs(); + diagnostics_.last_incoming_ms = last_incoming_ms_; + diagnostics_.received_text_count++; + if (command.type == ServerCommandType::kInvalid) { + diagnostics_.invalid_message_count++; + } else if ( + command.type == ServerCommandType::kUnsupported) { + diagnostics_.unsupported_message_count++; + } + } + HandleCommand(command); +} + +void RealtimeProtocol::OnWebsocketBinary( + const uint8_t* data, + size_t size) +{ + IRealtimeBinarySink* sink = nullptr; + uint32_t session_id = 0; + { + MutexGuard lock(mutex_); + last_incoming_ms_ = NowMs(); + diagnostics_.last_incoming_ms = last_incoming_ms_; + diagnostics_.received_binary_count++; + sink = binary_sink_; + session_id = active_call_session_ != 0 + ? active_call_session_ + : active_tts_session_; + } + if (sink == nullptr || session_id == 0) { + ESP_LOGD(kTag, + "binary frame ignored without sink/session size=%u", + static_cast(size)); + return; + } + + class PlaybackVisitor final : public IBinaryAudioFrameVisitor { + public: + PlaybackVisitor( + IRealtimeBinarySink& sink, + uint32_t session_id) + : sink_(sink), session_id_(session_id) + { + } + + bool OnOpusFrame( + const uint8_t* frame, + size_t frame_size) override + { + sink_.OnRealtimeBinary( + frame, frame_size, session_id_); + return true; + } + + private: + IRealtimeBinarySink& sink_; + uint32_t session_id_; + }; + + PlaybackVisitor visitor(*sink, session_id); + size_t frames = 0; + if (!VisitBinaryAudioPacket( + data, size, visitor, &frames)) { + { + MutexGuard lock(mutex_); + diagnostics_.invalid_message_count++; + } + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3201)); + } +} + +void RealtimeProtocol::TimerCallback(void* context) +{ + static_cast(context)->OnTimer(); +} + +void RealtimeProtocol::OnTimer() +{ + bool open_transport = false; + bool send_ping = false; + bool send_status = false; + uint32_t close_error = 0; + { + MutexGuard lock(mutex_); + const uint64_t now = NowMs(); + if (!intentional_close_ && + pending_open_ && + phase_ == RealtimeConnectionPhase::kClosed && + now >= reconnect_at_ms_) { + pending_open_ = false; + phase_ = RealtimeConnectionPhase::kConnecting; + diagnostics_.phase = phase_; + open_transport = true; + } else if ( + phase_ == RealtimeConnectionPhase::kAwaitingHello && + now >= hello_deadline_ms_) { + phase_ = RealtimeConnectionPhase::kClosingAfterError; + diagnostics_.phase = phase_; + close_error = kHelloTimeoutError; + } else if (phase_ == RealtimeConnectionPhase::kOpen) { + if (now - last_incoming_ms_ >= + config_.heartbeat_timeout_ms) { + phase_ = RealtimeConnectionPhase::kClosingAfterError; + diagnostics_.phase = phase_; + close_error = kHeartbeatTimeoutError; + } else if ( + now - last_ping_ms_ >= + config_.heartbeat_interval_ms) { + last_ping_ms_ = now; + send_ping = true; + } + if (now - last_status_ms_ >= kStatusIntervalMs) { + // Stamp here so a suppressed send (invalid battery sample) + // still paces the next attempt one interval out. + last_status_ms_ = now; + send_status = true; + } + } + } + + if (open_transport && + !transport_.Open(config_.transport, *this)) { + OnWebsocketDisconnected(kTransportSendError); + } + if (send_ping && !SendBuiltMessage( + kHeartbeatPingMessage, + sizeof(kHeartbeatPingMessage) - 1)) { + close_error = kTransportSendError; + } + if (send_status && close_error == 0) { + SendStatusSnapshot(); + } + if (close_error != 0) { + RequestErrorClose(close_error); + } +} + +void RealtimeProtocol::HandleCommand( + const ServerCommand& command) +{ + switch (command.type) { + case ServerCommandType::kInvalid: { + bool invalid_hello = false; + { + MutexGuard lock(mutex_); + invalid_hello = + phase_ == RealtimeConnectionPhase::kAwaitingHello; + } + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, + command.error_id)); + if (invalid_hello) { + RequestErrorClose(kInvalidServerHelloError); + } + return; + } + case ServerCommandType::kUnsupported: + ESP_LOGD(kTag, "unsupported server message ignored"); + return; + case ServerCommandType::kHello: + HandleHello(command); + return; + case ServerCommandType::kPing: { + std::array pong{}; + size_t size = 0; + if (builder_.BuildPong( + pong.data(), pong.size(), &size)) { + SendBuiltMessage(pong.data(), size); + } + return; + } + case ServerCommandType::kPong: + case ServerCommandType::kTtsSentenceEnd: + return; + case ServerCommandType::kSttText: + ESP_LOGI( + kConversationTag, + "%s>>> 用户 | %s%s", + kUserColor, + command.conversation_text.data(), + kColorReset); + return; + case ServerCommandType::kLlmEmotion: + ESP_LOGI( + kConversationTag, + "%s .. 情绪 | %s%s", + kEmotionColor, + command.conversation_text[0] == '\0' + ? "-" + : command.conversation_text.data(), + kColorReset); + return; + case ServerCommandType::kTtsSentenceStart: { + ESP_LOGI( + kConversationTag, + "%s<<< 播乐 | %s%s", + kDeviceColor, + command.conversation_text.data(), + kColorReset); + // Remember what the speaker is about to say, so an abort mid-sentence + // can tell the server where the child stopped listening. + MutexGuard lock(mutex_); + // std::strncpy( + // playback_text_.data(), + // command.conversation_text.data(), + // playback_text_.size() - 1); + strlcpy(playback_text_.data(),command.conversation_text.data(),playback_text_.size()); + playback_text_[playback_text_.size() - 1] = '\0'; + return; + } + case ServerCommandType::kBargeIn: + switch (command.barge_in_state) { + case BargeInDecisionState::kCandidate: + Publish(AppEvent::Make( + AppEventType::kBargeInCandidate)); + return; + case BargeInDecisionState::kRejected: + Publish(AppEvent::Make( + AppEventType::kBargeInRejected)); + return; + case BargeInDecisionState::kConfirmed: + { + MutexGuard lock(mutex_); + active_tts_session_ = 0; + playback_text_[0] = '\0'; + tts_tail_uplink_enabled_ = false; + diagnostics_.active_tts_session = 0; + audio_batch_.Reset(); + } + Publish(AppEvent::Make( + AppEventType::kBargeInConfirmed)); + return; + case BargeInDecisionState::kNone: + return; + } + return; + case ServerCommandType::kControl: { + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen) { + return; + } + if (command.control_action == + RemoteControlAction::kBargeIn) { + barge_in_enabled_ = command.control_value != 0; + if (!barge_in_enabled_) { + tts_tail_uplink_enabled_ = false; + } + if (!UplinkEnabledLocked()) { + audio_batch_.Reset(); + } + } + } + switch (command.control_action) { + case RemoteControlAction::kVolume: + Publish(AppEvent::Make( + AppEventType::kAudioVolumeRequested, + 0, + command.control_value)); + return; + case RemoteControlAction::kWakeWord: + Publish(AppEvent::Make( + AppEventType::kWakeWordControlRequested, + 0, + command.control_value)); + return; + case RemoteControlAction::kBargeIn: + Publish(AppEvent::Make( + AppEventType::kBargeInControlRequested, + 0, + command.control_value)); + return; + case RemoteControlAction::kLightSleep: + Publish(AppEvent::Make( + AppEventType::kRemoteIdleSleepRequested)); + return; + case RemoteControlAction::kLedAlert: + Publish(AppEvent::Make( + AppEventType::kLedAlertRequested, + 0, + command.control_value)); + return; + case RemoteControlAction::kNone: + return; + } + return; + } + case ServerCommandType::kTtsStart: { + uint32_t session_id = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen) { + return; + } + session_id = AllocateTtsSessionLocked(); + active_tts_session_ = session_id; + tts_tail_uplink_enabled_ = false; + diagnostics_.active_tts_session = session_id; + } + Publish(AppEvent::Make( + AppEventType::kTtsStarted, session_id)); + return; + } + case ServerCommandType::kTtsStop: { + uint32_t session_id = 0; + bool tail_uplink = false; + { + MutexGuard lock(mutex_); + session_id = active_tts_session_; + active_tts_session_ = 0; + // The sentence finished on its own — a later abort must not report + // it as still playing. + playback_text_[0] = '\0'; + // Keep the microphone/AEC path open while queued speaker frames + // are still draining. SendStartListening() closes this tail lane + // when playback is physically empty. + tts_tail_uplink_enabled_ = + session_id != 0 && barge_in_enabled_; + tail_uplink = tts_tail_uplink_enabled_; + diagnostics_.active_tts_session = 0; + if (!UplinkEnabledLocked()) { + audio_batch_.Reset(); + } + } + if (session_id != 0) { + ESP_LOGI( + kTag, + "tts producer stopped session=%lu tail_uplink=%d", + static_cast(session_id), + tail_uplink ? 1 : 0); + Publish(AppEvent::Make( + AppEventType::kTtsStreamEnded, session_id)); + } + return; + } + case ServerCommandType::kPlayLocal: + if (command.soft_off_after_playback) { + Publish(AppEvent::Make( + AppEventType::kShutdownPromptRequested)); + } else { + Publish(AppEvent::Make( + AppEventType::kLocalPromptRequested, + command.prompt_index < 0 + ? 0 + : static_cast( + command.prompt_index) + 1U, + static_cast(command.local_prompt), + static_cast( + command.playback_priority))); + } + return; + case ServerCommandType::kPlayLocalSequence: + if (local_sequence_handler_ == nullptr || + !local_sequence_handler_->StartLocalSequence( + command.local_sequence)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3113)); + } + return; + case ServerCommandType::kMemorySync: + if (memory_cache_ == nullptr || + !memory_cache_->Update(command.memory)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3114)); + } + return; + case ServerCommandType::kSetTimer: + if (schedule_handler_ == nullptr || + !schedule_handler_->AddReminder( + command.duration_seconds)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3110)); + } + return; + case ServerCommandType::kCancelTimer: + if (schedule_handler_ != nullptr) { + schedule_handler_->CancelReminder( + command.timer_cancel_scope); + } + return; + case ServerCommandType::kSetAlarm: + if (schedule_handler_ == nullptr || + !schedule_handler_->SetAlarm(command.alarm)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3111)); + } + return; + case ServerCommandType::kDeleteAlarm: + if (schedule_handler_ != nullptr) { + schedule_handler_->DeleteAlarm(command.alarm_id); + } + return; + case ServerCommandType::kSyncAlarms: + if (schedule_handler_ == nullptr || + !schedule_handler_->SyncAlarms(command.alarms)) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3112)); + } + return; + case ServerCommandType::kAlarmConfig: + if (schedule_handler_ != nullptr) { + schedule_handler_->SetAlarmToneIndices( + command.set_tone_index, + command.wake_tone_index); + } + return; + case ServerCommandType::kCall: { + uint32_t session_id = 0; + AppEventType event_type = AppEventType::kCallEnded; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen) { + return; + } + const bool same_call = + active_call_id_[0] != '\0' && + std::strcmp( + active_call_id_.data(), + command.call_id.data()) == 0; + if (command.call_state == CallSignalState::kRing || + command.call_state == CallSignalState::kInvite) { + active_call_id_ = command.call_id; + active_call_session_ = AllocateCallSessionLocked(); + diagnostics_.active_call_session = + active_call_session_; + active_tts_session_ = 0; + playback_text_[0] = '\0'; + tts_tail_uplink_enabled_ = false; + diagnostics_.active_tts_session = 0; + listening_uplink_enabled_ = false; + call_uplink_enabled_ = false; + audio_batch_.Reset(); + session_id = active_call_session_; + event_type = + command.call_state == CallSignalState::kInvite + ? AppEventType::kIncomingCall + : AppEventType::kOutgoingCall; + } else if ( + command.call_state == CallSignalState::kConnected && + same_call) { + session_id = active_call_session_; + call_uplink_enabled_ = true; + event_type = AppEventType::kCallConnected; + } else if ( + (command.call_state == CallSignalState::kEnded || + command.call_state == CallSignalState::kMissed) && + same_call) { + session_id = active_call_session_; + ClearCallLocked(); + audio_batch_.Reset(); + event_type = AppEventType::kCallEnded; + } else { + return; + } + } + Publish(AppEvent::Make(event_type, session_id)); + return; + } + case ServerCommandType::kEnterProvisioning: + Publish(AppEvent::Make( + AppEventType::kProvisioningRequested)); + return; + case ServerCommandType::kError: + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, + command.error_id)); + return; + } +} + +void RealtimeProtocol::HandleHello(const ServerCommand& command) +{ + bool accepted = false; + { + MutexGuard lock(mutex_); + if (phase_ == RealtimeConnectionPhase::kAwaitingHello) { + diagnostics_.session_id = command.session_id; + phase_ = RealtimeConnectionPhase::kOpen; + diagnostics_.phase = phase_; + reconnect_backoff_.Reset(); + reconnect_at_ms_ = 0; + pending_open_ = false; + accepted = true; + } + } + if (!accepted) { + ESP_LOGW(kTag, "unexpected duplicate ServerHello ignored"); + return; + } + + // Correlation scopes: the server owns the session id, the device opens a + // new turn scope for everything that follows this hello. + TraceContext::SetSession(command.session_id.data()); + TraceContext::RefreshTrace("ws"); + SyncClock(command); + if (device_profile_sink_ != nullptr && + command.device_name[0] != '\0') { + device_profile_sink_->SetDeviceName( + command.device_name.data()); + } + if (remote_behavior_config_ != nullptr) { + const bool button_saved = + remote_behavior_config_->UpdateButtonActions( + command.triple_click_action, + command.quadruple_click_action); + const bool prompts_saved = + remote_behavior_config_->UpdateConnectionPrompts( + command.has_server_unreachable_prompt, + command.server_unreachable_prompt, + command.has_no_network_prompt, + command.no_network_prompt); + if (!button_saved || !prompts_saved) { + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, 3115)); + } + } + ESP_LOGI(kTag, + "ServerHello accepted session=%s output=%luHz frame=%ums", + command.session_id.data(), + static_cast(command.output_sample_rate), + static_cast(command.frame_duration_ms)); + Publish(AppEvent::Make(AppEventType::kRealtimeConnected)); + SendStatusSnapshot(); +} + +void RealtimeProtocol::SendStatusSnapshot() +{ + if (battery_ == nullptr) { + return; + } + const BatteryStatus status = battery_->GetBatteryStatus(); + if (!status.valid) { + // Suppress rather than report a bogus 0%: the battery task may not + // have produced its first plausible sample yet. + return; + } + const int16_t volume_percent = + volume_ != nullptr + ? static_cast(volume_->OutputVolumePercent()) + : static_cast(-1); + std::array message{}; + size_t size = 0; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kOpen || + !builder_.BuildStatus( + status.percent, + status.millivolts, + status.charging, + config_.transport.firmware_version.data(), + volume_percent, + message.data(), + message.size(), + &size)) { + return; + } + last_status_ms_ = NowMs(); + } + SendBuiltMessage(message.data(), size); +} + +void RealtimeProtocol::RequestErrorClose(uint32_t error_id) +{ + bool should_close = false; + { + MutexGuard lock(mutex_); + if (phase_ != RealtimeConnectionPhase::kClosed && + phase_ != RealtimeConnectionPhase::kClosingAfterError) { + phase_ = RealtimeConnectionPhase::kClosingAfterError; + diagnostics_.phase = phase_; + should_close = true; + } else if ( + phase_ == RealtimeConnectionPhase::kClosingAfterError) { + should_close = true; + } + } + if (!should_close) { + return; + } + Publish(AppEvent::Make( + AppEventType::kRealtimeProtocolError, error_id)); + transport_.Close(); +} + +void RealtimeProtocol::ScheduleReconnectLocked(uint64_t now_ms) +{ + const uint32_t delay = + reconnect_backoff_.NextDelayMs(esp_random()); + reconnect_at_ms_ = now_ms + delay; + pending_open_ = true; + diagnostics_.reconnect_attempt_count = + reconnect_backoff_.attempt_count(); + ESP_LOGI(kTag, "reconnect gate delay=%lu ms attempt=%lu", + static_cast(delay), + static_cast( + diagnostics_.reconnect_attempt_count)); +} + +void RealtimeProtocol::Publish(const AppEvent& event) +{ + if (publisher_ == nullptr || !publisher_->Publish(event)) { + ESP_LOGE(kTag, "failed to publish event=%s", + ToString(event.type)); + } +} + +bool RealtimeProtocol::SendBuiltMessage( + const char* data, + size_t size) +{ + if (!transport_.SendText(data, size)) { + return false; + } + MutexGuard lock(mutex_); + diagnostics_.sent_text_count++; + return true; +} + +bool RealtimeProtocol::TakeAudioBatchLocked(size_t* packet_size) +{ + if (packet_size == nullptr || audio_batch_.Empty()) { + return false; + } + const bool built = audio_batch_.Build( + audio_packet_.data(), + audio_packet_.size(), + packet_size); + audio_batch_.Reset(); + return built; +} + +bool RealtimeProtocol::UplinkEnabledLocked() const +{ + return listening_uplink_enabled_ || + call_uplink_enabled_ || + (barge_in_enabled_ && + (active_tts_session_ != 0 || tts_tail_uplink_enabled_)); +} + +uint32_t RealtimeProtocol::AllocateTtsSessionLocked() +{ + uint32_t result = next_tts_session_++; + if (result == 0 || result >= 0x80000000U) { + next_tts_session_ = 2; + result = 1; + } + return result; +} + +uint32_t RealtimeProtocol::AllocateCallSessionLocked() +{ + uint32_t result = next_call_session_++; + if (result < 0x80000000U || result == 0xFFFFFFFFU) { + next_call_session_ = 0x80000002U; + result = 0x80000001U; + } + return result; +} + +void RealtimeProtocol::ClearCallLocked() +{ + active_call_id_.fill('\0'); + active_call_session_ = 0; + call_uplink_enabled_ = false; + diagnostics_.active_call_session = 0; +} + +void RealtimeProtocol::SyncClock(const ServerCommand& command) +{ + if (command.server_time_seconds < 1700000000LL) { + return; + } + timeval time_value{}; + time_value.tv_sec = + static_cast(command.server_time_seconds); + settimeofday(&time_value, nullptr); + + if (command.timezone_offset_seconds >= -43200 && + command.timezone_offset_seconds <= 50400) { + const int offset_hours = + command.timezone_offset_seconds / 3600; + char timezone[20]{}; + std::snprintf( + timezone, sizeof(timezone), "UTC%+d", -offset_hours); + setenv("TZ", timezone, 1); + tzset(); + } + DeviceLogFormatter::MarkClockSynchronized(); +} + +uint64_t RealtimeProtocol::NowMs() const +{ + return static_cast( + esp_timer_get_time() / 1000ULL); +} + +} // namespace borla diff --git a/main/protocol/realtime_protocol.h b/main/protocol/realtime_protocol.h new file mode 100644 index 0000000..a66cc16 --- /dev/null +++ b/main/protocol/realtime_protocol.h @@ -0,0 +1,253 @@ +#pragma once + +#include "connectivity/reconnect_backoff.h" +#include "audio/encoded_audio_sink.h" +#include "ports/battery_status_provider.h" +#include "ports/device_platform.h" +#include "ports/device_profile_sink.h" +#include "ports/event_publisher.h" +#include "ports/local_sequence_handler.h" +#include "ports/memory_cache.h" +#include "ports/remote_behavior_config.h" +#include "ports/realtime_protocol.h" +#include "ports/sensor_message_sink.h" +#include "ports/volume_status_provider.h" +#include "protocol/protocol_message_builder.h" +#include "protocol/binary_audio_protocol.h" +#include "protocol/realtime_config.h" +#include "protocol/server_message_dispatcher.h" +#include "protocol/realtime_binary_sink.h" +#include "protocol/websocket_transport.h" +#include "schedule/schedule_types.h" + +#include +#include +#include + +#include +#include +#include + +namespace borla { + +enum class RealtimeConnectionPhase : uint8_t { + kClosed, + kConnecting, + kAwaitingHello, + kOpen, + kClosingAfterError, +}; + +struct RealtimeDiagnostics { + RealtimeConnectionPhase phase = RealtimeConnectionPhase::kClosed; + uint32_t reconnect_attempt_count = 0; + uint32_t invalid_message_count = 0; + uint32_t unsupported_message_count = 0; + uint32_t received_text_count = 0; + uint32_t received_binary_count = 0; + uint32_t sent_text_count = 0; + uint32_t transport_error_count = 0; + uint32_t active_tts_session = 0; + uint32_t active_call_session = 0; + uint64_t last_incoming_ms = 0; + std::array session_id{}; +}; + +class RealtimeProtocol final + : public IRealtimeProtocol, + public IEncodedAudioSink, + public ISensorMessageSink, + public IScheduleEventSink, + public IWebsocketTransportObserver { +public: + RealtimeProtocol( + IWebsocketTransport& transport, + IRealtimeConfigStore& config_store); + ~RealtimeProtocol(); + + bool Initialize(const DeviceIdentity& identity); + void SetEventPublisher(IEventPublisher* publisher) + { + publisher_ = publisher; + } + void SetBinarySink(IRealtimeBinarySink* sink) { binary_sink_ = sink; } + void SetScheduleCommandHandler(IScheduleCommandHandler* handler) + { + schedule_handler_ = handler; + } + void SetBatteryStatusProvider(IBatteryStatusProvider* provider) + { + battery_ = provider; + } + void SetVolumeStatusProvider(IVolumeStatusProvider* provider) + { + volume_ = provider; + } + void SetDeviceProfileSink(IDeviceProfileSink* sink) + { + device_profile_sink_ = sink; + } + void SetLocalSequenceHandler(ILocalSequenceHandler* handler) + { + local_sequence_handler_ = handler; + } + void SetMemoryCache(IMemoryCache* cache) + { + memory_cache_ = cache; + } + void SetRemoteBehaviorConfig(IRemoteBehaviorConfig* config) + { + remote_behavior_config_ = config; + } + + void Open() override; + void Close() override; + void SendStartListening() override; + void SendStopListening() override; + void SendAbortSpeaking( + ConversationInterruptSource source) override; + void SendGoodbye() override; + void SendAcceptCall() override; + void SendHangupCall() override; + void SendButtonClick(uint8_t click_count) override; + void SendLocalPlaybackState( + LocalPrompt prompt, + bool started) override; + bool SendFriendAdd( + const char* local_mac, + const char* local_name, + const char* remote_mac, + const char* remote_name) override; + bool SendOtaNotify( + const char* text, + bool optional) override; + void RequestConnectionErrorPrompt() override; + bool SubmitEncodedAudio( + const uint8_t* data, + size_t size) override; + void FlushEncodedAudio() override; + bool SendSensorMessage( + const char* data, + size_t size) override; + bool SendAlarmFired( + int32_t alarm_id, + int64_t fired_at_epoch) override; + + RealtimeDiagnostics GetDiagnostics() const; + uint32_t ActiveTtsSession() const; + + void OnWebsocketConnected() override; + void OnWebsocketDisconnected(int error_code) override; + void OnWebsocketText(const char* data, size_t size) override; + void OnWebsocketBinary( + const uint8_t* data, + size_t size) override; + +private: + static constexpr size_t kMessageCapacity = + kBinaryAudioMaximumPacketBytes; + static constexpr size_t kHeartbeatMessageCapacity = 128; + // Status is built on the esp_timer task, whose stack is a few KB. Size the + // buffer for the message (~150 bytes) instead of reusing the 2.5 KB + // audio-packet capacity the other builders share. + static constexpr size_t kStatusMessageCapacity = 256; + static constexpr uint32_t kProtocolRetryMaximumMs = 30000; + static constexpr uint32_t kStatusIntervalMs = 60000; + static constexpr size_t kTraceMarkerCapacity = 256; + static constexpr uint64_t kAudioTraceHeartbeatMs = 5000; + static constexpr float kAudioTraceRelativeChange = 0.20F; + static constexpr size_t kAudioTraceMinimumByteDelta = 160; + + static void TimerCallback(void* context); + void OnTimer(); + void HandleCommand(const ServerCommand& command); + void HandleHello(const ServerCommand& command); + void RequestErrorClose(uint32_t error_id); + void ScheduleReconnectLocked(uint64_t now_ms); + void Publish(const AppEvent& event); + bool SendBuiltMessage(const char* data, size_t size); + bool TakeAudioBatchLocked(size_t* packet_size); + // One uplink batch leaves every 300 ms, and a marker per batch would be + // pure noise. Emit one when the batch shape actually changes — first batch, + // a different frame count, or a byte size that moved by both an absolute + // and a relative margin — plus a slow heartbeat so a steady stream still + // reports a clock sample. Same policy as the previous firmware. + bool ShouldTraceAudioBatchLocked( + uint64_t sequence, + size_t frames, + size_t bytes, + uint64_t now_ms); + void SendAudioBatchTrace( + uint64_t sequence, + size_t frames, + size_t bytes, + uint64_t client_send_ms); + static int64_t EpochMs(); + bool UplinkEnabledLocked() const; + uint32_t AllocateTtsSessionLocked(); + uint32_t AllocateCallSessionLocked(); + void ClearCallLocked(); + void SyncClock(const ServerCommand& command); + void SendStatusSnapshot(); + uint64_t NowMs() const; + + IWebsocketTransport& transport_; + IRealtimeConfigStore& config_store_; + IEventPublisher* publisher_ = nullptr; + IRealtimeBinarySink* binary_sink_ = nullptr; + IScheduleCommandHandler* schedule_handler_ = nullptr; + IBatteryStatusProvider* battery_ = nullptr; + IVolumeStatusProvider* volume_ = nullptr; + IDeviceProfileSink* device_profile_sink_ = nullptr; + ILocalSequenceHandler* local_sequence_handler_ = nullptr; + IMemoryCache* memory_cache_ = nullptr; + IRemoteBehaviorConfig* remote_behavior_config_ = nullptr; + RealtimeConfig config_{}; + ServerMessageDispatcher dispatcher_; + ServerCommand* incoming_command_ = nullptr; + ProtocolMessageBuilder builder_; + ReconnectBackoff reconnect_backoff_; + + mutable StaticSemaphore_t mutex_storage_{}; + SemaphoreHandle_t mutex_ = nullptr; + esp_timer_handle_t timer_ = nullptr; + bool initialized_ = false; + bool intentional_close_ = true; + bool pending_open_ = false; + bool disconnect_reported_ = false; + RealtimeConnectionPhase phase_ = RealtimeConnectionPhase::kClosed; + uint64_t hello_deadline_ms_ = 0; + uint64_t reconnect_at_ms_ = 0; + uint64_t last_incoming_ms_ = 0; + uint64_t last_ping_ms_ = 0; + uint64_t last_status_ms_ = 0; + uint32_t next_tts_session_ = 1; + uint32_t active_tts_session_ = 0; + uint32_t next_call_session_ = 0x80000001U; + uint32_t active_call_session_ = 0; + std::array active_call_id_{}; + // The sentence currently coming out of the speaker, reported to the server + // on abort so it knows how much of its reply the child actually heard. + // Only the leading bytes are kept — the abort builder caps the field anyway, + // and holding a full sentence per connection is not worth the RAM. + std::array< + char, + ProtocolMessageBuilder::kPlaybackTextBytes + 1> + playback_text_{}; + uint64_t trace_audio_batch_sequence_ = 0; + uint64_t last_trace_audio_batch_ms_ = 0; + size_t last_trace_audio_batch_frames_ = 0; + size_t last_trace_audio_batch_bytes_ = 0; + bool listening_uplink_enabled_ = false; + bool barge_in_enabled_ = false; + bool tts_tail_uplink_enabled_ = false; + bool call_uplink_enabled_ = false; + BinaryAudioBatchBuilder audio_batch_; + std::array< + uint8_t, + kBinaryAudioMaximumPacketBytes> + audio_packet_{}; + RealtimeDiagnostics diagnostics_{}; +}; + +} // namespace borla diff --git a/main/protocol/server_message_dispatcher.cc b/main/protocol/server_message_dispatcher.cc new file mode 100644 index 0000000..22f0515 --- /dev/null +++ b/main/protocol/server_message_dispatcher.cc @@ -0,0 +1,944 @@ +#include "protocol/server_message_dispatcher.h" + +#include "connectivity/wifi_types.h" + +#include +#include +#include +#include +#include + +#include + +namespace borla { +namespace { + +constexpr uint32_t kMalformedJsonError = 3101; +constexpr uint32_t kInvalidMessageError = 3102; +constexpr uint32_t kInvalidHelloError = 3103; +constexpr uint32_t kServerReportedError = 3104; + +void ResetCommand( + ServerCommand* output, + ServerCommandType type) +{ + output->~ServerCommand(); + new (output) ServerCommand(); + output->type = type; +} + +void SetInvalid(ServerCommand* output, uint32_t error_id) +{ + ResetCommand(output, ServerCommandType::kInvalid); + output->error_id = error_id; +} + +const char* StringField(const cJSON* root, const char* name) +{ + const cJSON* item = + cJSON_GetObjectItemCaseSensitive(root, name); + return cJSON_IsString(item) ? item->valuestring : nullptr; +} + +bool IntegerField( + const cJSON* root, + const char* name, + int64_t minimum, + int64_t maximum, + int64_t* value) +{ + const cJSON* item = + cJSON_GetObjectItemCaseSensitive(root, name); + if (!cJSON_IsNumber(item) || !std::isfinite(item->valuedouble) || + std::floor(item->valuedouble) != item->valuedouble || + item->valuedouble < static_cast(minimum) || + item->valuedouble > static_cast(maximum)) { + return false; + } + *value = static_cast(item->valuedouble); + return true; +} + +template +bool CopyOptionalString( + const cJSON* root, + const char* name, + std::array* output) +{ + if (output == nullptr) { + return false; + } + const char* value = StringField(root, name); + if (value == nullptr) { + output->fill('\0'); + return true; + } + const size_t size = BoundedStringLength(value, Capacity); + if (size >= Capacity) { + return false; + } + output->fill('\0'); + std::memcpy(output->data(), value, size); + return true; +} + +template +bool CopyRequiredString( + const cJSON* root, + const char* name, + std::array* output) +{ + if (output == nullptr) { + return false; + } + const char* value = StringField(root, name); + const size_t size = BoundedStringLength(value, Capacity); + if (size == 0 || size >= Capacity) { + return false; + } + output->fill('\0'); + std::memcpy(output->data(), value, size); + return true; +} + +bool ParseAlarmObject(const cJSON* object, AlarmEntry* alarm) +{ + if (!cJSON_IsObject(object) || alarm == nullptr) { + return false; + } + int64_t id = 0; + int64_t hour = 0; + int64_t minute = 0; + int64_t repeat_mask = 0; + if (!IntegerField(object, "id", INT32_MIN, INT32_MAX, &id) || + id == 0 || id == kBuiltInFirstDayAlarmId || + !IntegerField(object, "hour", 0, 23, &hour) || + !IntegerField(object, "minute", 0, 59, &minute) || + !IntegerField(object, "repeat_mask", 0, 0x7F, &repeat_mask)) { + return false; + } + int64_t fire_epoch = 0; + const cJSON* fire = + cJSON_GetObjectItemCaseSensitive(object, "fire_epoch"); + if (fire != nullptr && + !IntegerField(object, "fire_epoch", 0, INT64_MAX, &fire_epoch)) { + return false; + } + const cJSON* enabled = + cJSON_GetObjectItemCaseSensitive(object, "enabled"); + if (enabled != nullptr && !cJSON_IsBool(enabled)) { + return false; + } + const char* label = StringField(object, "label"); + if (label != nullptr && + std::strlen(label) >= kAlarmLabelCapacity) { + return false; + } + AlarmEntry parsed; + parsed.id = static_cast(id); + parsed.hour = static_cast(hour); + parsed.minute = static_cast(minute); + parsed.repeat_mask = static_cast(repeat_mask); + parsed.fire_epoch = fire_epoch; + parsed.enabled = enabled == nullptr || cJSON_IsTrue(enabled); + if (label != nullptr) { + std::memcpy(parsed.label.data(), label, std::strlen(label)); + } + *alarm = parsed; + return true; +} + +bool LookupPrompt( + const char* group, + LocalPrompt* prompt, + PlaybackPriority* priority) +{ + if (group == nullptr || prompt == nullptr || priority == nullptr) { + return false; + } + + struct PromptMapping { + const char* group; + LocalPrompt prompt; + PlaybackPriority priority; + }; + static constexpr PromptMapping kMappings[] = { + {"activation_device", LocalPrompt::kActivationDevice, + PlaybackPriority::kLocalPrompt}, + {"activation_prompt", LocalPrompt::kActivationDevice, + PlaybackPriority::kLocalPrompt}, + {"device_already_bound", LocalPrompt::kDeviceAlreadyBound, + PlaybackPriority::kLocalPrompt}, + {"server_error", LocalPrompt::kServerError, + PlaybackPriority::kSystem}, + {"alarm_wake", LocalPrompt::kAlarmWake, + PlaybackPriority::kAlarm}, + {"alarm_set", LocalPrompt::kAlarmSet, + PlaybackPriority::kSystem}, + {"no_network", LocalPrompt::kNoNetwork, + PlaybackPriority::kSystem}, + {"wifi_config", LocalPrompt::kProvisioning, + PlaybackPriority::kSystem}, + {"wake_response", LocalPrompt::kWakeResponse, + PlaybackPriority::kLocalPrompt}, + {"story_expired", LocalPrompt::kStoryExpired, + PlaybackPriority::kLocalPrompt}, + {"idle_check", LocalPrompt::kIdleCheck, + PlaybackPriority::kLocalPrompt}, + {"idle_goodbye", LocalPrompt::kIdleGoodbye, + PlaybackPriority::kLocalPrompt}, + {"snore_light", LocalPrompt::kSnoreLight, + PlaybackPriority::kLocalPrompt}, + {"wifi_success", LocalPrompt::kWifiSuccess, + PlaybackPriority::kSystem}, + {"welcome", LocalPrompt::kWelcome, + PlaybackPriority::kLocalPrompt}, + {"shutdown", LocalPrompt::kShutdown, + PlaybackPriority::kSystem}, + {"boot", LocalPrompt::kBoot, + PlaybackPriority::kSystem}, + {"error", LocalPrompt::kError, + PlaybackPriority::kSystem}, + {"low_battery_20", LocalPrompt::kLowBattery20, + PlaybackPriority::kSystem}, + {"low_battery_10", LocalPrompt::kLowBattery10, + PlaybackPriority::kSystem}, + {"net4g_boot_on", LocalPrompt::kNet4gBootOn, + PlaybackPriority::kSystem}, + {"net4g_off", LocalPrompt::kNet4gOff, + PlaybackPriority::kSystem}, + {"net4g_on", LocalPrompt::kNet4gOn, + PlaybackPriority::kSystem}, + {"net4g_no_wifi", LocalPrompt::kNet4gNoWifi, + PlaybackPriority::kSystem}, + {"digit_0", LocalPrompt::kDigit0, + PlaybackPriority::kLocalPrompt}, + {"digit_1", LocalPrompt::kDigit1, + PlaybackPriority::kLocalPrompt}, + {"digit_2", LocalPrompt::kDigit2, + PlaybackPriority::kLocalPrompt}, + {"digit_3", LocalPrompt::kDigit3, + PlaybackPriority::kLocalPrompt}, + {"digit_4", LocalPrompt::kDigit4, + PlaybackPriority::kLocalPrompt}, + {"digit_5", LocalPrompt::kDigit5, + PlaybackPriority::kLocalPrompt}, + {"digit_6", LocalPrompt::kDigit6, + PlaybackPriority::kLocalPrompt}, + {"digit_7", LocalPrompt::kDigit7, + PlaybackPriority::kLocalPrompt}, + {"digit_8", LocalPrompt::kDigit8, + PlaybackPriority::kLocalPrompt}, + {"digit_9", LocalPrompt::kDigit9, + PlaybackPriority::kLocalPrompt}, + }; + + for (const PromptMapping& mapping : kMappings) { + if (std::strcmp(group, mapping.group) == 0) { + *prompt = mapping.prompt; + *priority = mapping.priority; + return true; + } + } + return false; +} + +} // namespace + +bool ServerMessageDispatcher::ParseInto( + const char* json, + size_t size, + ServerCommand* output) const +{ + if (output == nullptr) { + return false; + } + if (json == nullptr || size == 0) { + SetInvalid(output, kMalformedJsonError); + return true; + } + cJSON* root = cJSON_ParseWithLength(json, size); + if (!cJSON_IsObject(root)) { + cJSON_Delete(root); + SetInvalid(output, kMalformedJsonError); + return true; + } + + const char* type = StringField(root, "type"); + if (type == nullptr) { + SetInvalid(output, kInvalidMessageError); + } else if (std::strcmp(type, "hello") == 0) { + ParseHello(root, output); + } else if (std::strcmp(type, "ping") == 0) { + ResetCommand(output, ServerCommandType::kPing); + } else if (std::strcmp(type, "pong") == 0) { + ResetCommand(output, ServerCommandType::kPong); + } else if (std::strcmp(type, "stt") == 0) { + ParseStt(root, output); + } else if (std::strcmp(type, "llm") == 0) { + ParseLlm(root, output); + } else if (std::strcmp(type, "tts") == 0) { + ParseTts(root, output); + } else if (std::strcmp(type, "barge_in") == 0) { + ParseBargeIn(root, output); + } else if (std::strcmp(type, "control") == 0) { + ParseControl(root, output); + } else if (std::strcmp(type, "play_local") == 0) { + ParsePlayLocal(root, output); + } else if (std::strcmp(type, "play_local_sequence") == 0) { + ParsePlayLocalSequence(root, output); + } else if (std::strcmp(type, "memory_sync") == 0) { + ParseMemorySync(root, output); + } else if (std::strcmp(type, "set_timer") == 0) { + ParseSetTimer(root, output); + } else if (std::strcmp(type, "cancel_timer") == 0) { + ParseCancelTimer(root, output); + } else if (std::strcmp(type, "set_alarm") == 0) { + ParseSetAlarm(root, output); + } else if (std::strcmp(type, "delete_alarm") == 0) { + ParseDeleteAlarm(root, output); + } else if (std::strcmp(type, "sync_alarms") == 0) { + ParseSyncAlarms(root, output); + } else if (std::strcmp(type, "alarm_config") == 0) { + ParseAlarmConfig(root, output); + } else if (std::strcmp(type, "call") == 0) { + ParseCall(root, output); + } else if (std::strcmp(type, "wifi_config") == 0) { + ResetCommand(output, ServerCommandType::kEnterProvisioning); + } else if (std::strcmp(type, "error") == 0) { + ResetCommand(output, ServerCommandType::kError); + output->error_id = kServerReportedError; + const cJSON* code = + cJSON_GetObjectItemCaseSensitive(root, "code"); + if (cJSON_IsNumber(code) && code->valuedouble > 0) { + output->error_id = + static_cast(code->valuedouble); + } + } else { + ResetCommand(output, ServerCommandType::kUnsupported); + } + + cJSON_Delete(root); + return true; +} + +void ServerMessageDispatcher::ParseBargeIn( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* state = StringField(root, "state"); + if (state == nullptr) { + SetInvalid(output, kInvalidMessageError); + return; + } + ResetCommand(output, ServerCommandType::kBargeIn); + if (std::strcmp(state, "candidate") == 0) { + output->barge_in_state = BargeInDecisionState::kCandidate; + } else if (std::strcmp(state, "rejected") == 0) { + output->barge_in_state = BargeInDecisionState::kRejected; + } else if (std::strcmp(state, "confirmed") == 0) { + output->barge_in_state = BargeInDecisionState::kConfirmed; + } else { + SetInvalid(output, kInvalidMessageError); + } +} + +void ServerMessageDispatcher::ParseControl( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* action = StringField(root, "action"); + if (action == nullptr) { + SetInvalid(output, kInvalidMessageError); + return; + } + ResetCommand(output, ServerCommandType::kControl); + ServerCommand& command = *output; + if (std::strcmp(action, "volume") == 0) { + int64_t volume = 0; + if (!IntegerField(root, "volume", INT_MIN, INT_MAX, &volume)) { + SetInvalid(output, kInvalidMessageError); + return; + } + command.control_action = RemoteControlAction::kVolume; + command.control_value = static_cast( + std::clamp(volume, 0, 100)); + return; + } + if (std::strcmp(action, "wake_word") == 0 || + std::strcmp(action, "barge_in") == 0) { + const cJSON* enabled = + cJSON_GetObjectItemCaseSensitive(root, "enabled"); + if (!cJSON_IsBool(enabled)) { + SetInvalid(output, kInvalidMessageError); + return; + } + command.control_action = + std::strcmp(action, "wake_word") == 0 + ? RemoteControlAction::kWakeWord + : RemoteControlAction::kBargeIn; + command.control_value = cJSON_IsTrue(enabled) ? 1 : 0; + return; + } + if (std::strcmp(action, "light_sleep") == 0) { + const char* mode = StringField(root, "mode"); + if (mode != nullptr && std::strcmp(mode, "idle_sleep") != 0) { + SetInvalid(output, kInvalidMessageError); + return; + } + command.control_action = RemoteControlAction::kLightSleep; + return; + } + if (std::strcmp(action, "led") == 0) { + const char* state = StringField(root, "state"); + const char* color = StringField(root, "color"); + int64_t duration_ms = 0; + if (state == nullptr || color == nullptr || + std::strcmp(state, "alert") != 0 || + std::strcmp(color, "red") != 0 || + !IntegerField( + root, + "duration_ms", + INT_MIN, + INT_MAX, + &duration_ms)) { + SetInvalid(output, kInvalidMessageError); + return; + } + command.control_action = RemoteControlAction::kLedAlert; + command.control_value = static_cast( + std::clamp(duration_ms, 100, 60000)); + return; + } + ResetCommand(output, ServerCommandType::kUnsupported); +} + +void ServerMessageDispatcher::ParseCall( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* state = StringField(root, "state"); + const char* call_id = StringField(root, "call_id"); + const size_t call_id_size = + BoundedStringLength(call_id, kCallIdCapacity); + if (state == nullptr || call_id_size == 0 || + call_id_size >= kCallIdCapacity) { + SetInvalid(output, kInvalidMessageError); + return; + } + + ResetCommand(output, ServerCommandType::kCall); + ServerCommand& command = *output; + if (std::strcmp(state, "ring") == 0) { + command.call_state = CallSignalState::kRing; + } else if (std::strcmp(state, "invite") == 0) { + command.call_state = CallSignalState::kInvite; + } else if (std::strcmp(state, "connected") == 0) { + command.call_state = CallSignalState::kConnected; + } else if (std::strcmp(state, "ended") == 0) { + command.call_state = CallSignalState::kEnded; + } else if (std::strcmp(state, "missed") == 0) { + command.call_state = CallSignalState::kMissed; + } else { + SetInvalid(output, kInvalidMessageError); + return; + } + + std::memcpy(command.call_id.data(), call_id, call_id_size); + const char* peer_field = "peer_name"; + if (command.call_state == CallSignalState::kRing) { + peer_field = "target_name"; + } else if (command.call_state == CallSignalState::kInvite) { + peer_field = "caller_name"; + } + if (!CopyOptionalString(root, peer_field, &command.peer_name)) { + SetInvalid(output, kInvalidMessageError); + return; + } +} + +void ServerMessageDispatcher::ParseSetTimer( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + int64_t duration = 0; + if (!IntegerField(root, "duration", 1, 604800, &duration)) { + SetInvalid(output, kInvalidMessageError); + return; + } + ResetCommand(output, ServerCommandType::kSetTimer); + output->duration_seconds = static_cast(duration); +} + +void ServerMessageDispatcher::ParseCancelTimer( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* scope = StringField(root, "scope"); + ResetCommand(output, ServerCommandType::kCancelTimer); + if (scope == nullptr || std::strcmp(scope, "recent") == 0) { + output->timer_cancel_scope = TimerCancelScope::kNext; + } else if (std::strcmp(scope, "all") == 0) { + output->timer_cancel_scope = TimerCancelScope::kAll; + } else { + SetInvalid(output, kInvalidMessageError); + } +} + +void ServerMessageDispatcher::ParseSetAlarm( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const cJSON* item = + cJSON_GetObjectItemCaseSensitive(root, "alarm"); + ResetCommand(output, ServerCommandType::kSetAlarm); + if (!ParseAlarmObject(item, &output->alarm)) { + SetInvalid(output, kInvalidMessageError); + } +} + +void ServerMessageDispatcher::ParseDeleteAlarm( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + int64_t id = 0; + if (!IntegerField(root, "id", INT32_MIN, INT32_MAX, &id) || + (id <= 0 && id != kBuiltInFirstDayAlarmId)) { + SetInvalid(output, kInvalidMessageError); + return; + } + ResetCommand(output, ServerCommandType::kDeleteAlarm); + output->alarm_id = static_cast(id); +} + +void ServerMessageDispatcher::ParseSyncAlarms( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const cJSON* alarms = + cJSON_GetObjectItemCaseSensitive(root, "alarms"); + if (!cJSON_IsArray(alarms) || + cJSON_GetArraySize(alarms) > + static_cast(kMaximumAlarmCount)) { + SetInvalid(output, kInvalidMessageError); + return; + } + ResetCommand(output, ServerCommandType::kSyncAlarms); + cJSON* item = nullptr; + cJSON_ArrayForEach(item, alarms) { + if (!ParseAlarmObject( + item, + &output->alarms.entries[output->alarms.count])) { + SetInvalid(output, kInvalidMessageError); + return; + } + output->alarms.count++; + } +} + +void ServerMessageDispatcher::ParseAlarmConfig( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + int64_t set_index = 0; + int64_t wake_index = 0; + if (!IntegerField(root, "set_tone_index", -1, 15, &set_index) || + !IntegerField(root, "wake_tone_index", -1, 15, &wake_index)) { + SetInvalid(output, kInvalidMessageError); + return; + } + ResetCommand(output, ServerCommandType::kAlarmConfig); + output->set_tone_index = static_cast(set_index); + output->wake_tone_index = static_cast(wake_index); +} + +void ServerMessageDispatcher::ParseHello( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* session_id = StringField(root, "session_id"); + const char* transport = StringField(root, "transport"); + const cJSON* version = + cJSON_GetObjectItemCaseSensitive(root, "version"); + const cJSON* audio = + cJSON_GetObjectItemCaseSensitive(root, "audio_params"); + const cJSON* sample_rate = + cJSON_GetObjectItemCaseSensitive(audio, "sample_rate"); + const cJSON* channels = + cJSON_GetObjectItemCaseSensitive(audio, "channels"); + const cJSON* frame_duration = + cJSON_GetObjectItemCaseSensitive(audio, "frame_duration"); + const char* format = StringField(audio, "format"); + + const size_t session_length = + BoundedStringLength(session_id, kRealtimeSessionIdCapacity); + const bool valid_version = + !cJSON_IsNumber(version) || version->valueint == 3; + const bool valid_transport = + transport == nullptr || std::strcmp(transport, "websocket") == 0; + const bool valid_audio = + cJSON_IsObject(audio) && + cJSON_IsNumber(sample_rate) && + sample_rate->valueint == 24000 && + (!cJSON_IsNumber(channels) || channels->valueint == 1) && + cJSON_IsNumber(frame_duration) && + frame_duration->valueint == 60 && + (format == nullptr || std::strcmp(format, "opus") == 0); + + if (session_length == 0 || + session_length >= kRealtimeSessionIdCapacity || + !valid_version || !valid_transport || !valid_audio) { + SetInvalid(output, kInvalidHelloError); + return; + } + + ResetCommand(output, ServerCommandType::kHello); + ServerCommand& command = *output; + std::memcpy( + command.session_id.data(), session_id, session_length); + command.output_sample_rate = + static_cast(sample_rate->valueint); + command.frame_duration_ms = + static_cast(frame_duration->valueint); + + const cJSON* server_time = + cJSON_GetObjectItemCaseSensitive(root, "server_time"); + const cJSON* timezone = + cJSON_GetObjectItemCaseSensitive(root, "tz_offset"); + if (cJSON_IsNumber(server_time)) { + command.server_time_seconds = + static_cast(server_time->valuedouble); + } + if (cJSON_IsNumber(timezone)) { + command.timezone_offset_seconds = timezone->valueint; + } + if (!CopyOptionalString(root, "device_name", &command.device_name)) { + SetInvalid(output, kInvalidHelloError); + return; + } + + const cJSON* button_map = + cJSON_GetObjectItemCaseSensitive(root, "button_map"); + if (cJSON_IsObject(button_map)) { + const cJSON* triple = + cJSON_GetObjectItemCaseSensitive(button_map, "3"); + const cJSON* quadruple = + cJSON_GetObjectItemCaseSensitive(button_map, "4"); + if (cJSON_IsString(triple)) { + ParseButtonAction( + triple->valuestring, + &command.triple_click_action); + } + if (cJSON_IsString(quadruple)) { + ParseButtonAction( + quadruple->valuestring, + &command.quadruple_click_action); + } + } + + const cJSON* prompts = cJSON_GetObjectItemCaseSensitive( + root, "connection_error_prompts"); + if (cJSON_IsObject(prompts)) { + const cJSON* server = cJSON_GetObjectItemCaseSensitive( + prompts, "server_unreachable"); + const cJSON* network = cJSON_GetObjectItemCaseSensitive( + prompts, "no_network"); + if (cJSON_IsString(server)) { + command.has_server_unreachable_prompt = + ParseConnectionPrompt( + server->valuestring, + &command.server_unreachable_prompt); + } + if (cJSON_IsString(network)) { + command.has_no_network_prompt = + ParseConnectionPrompt( + network->valuestring, + &command.no_network_prompt); + } + } +} + +void ServerMessageDispatcher::ParseTts( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* state = StringField(root, "state"); + if (state == nullptr) { + SetInvalid(output, kInvalidMessageError); + return; + } + if (std::strcmp(state, "start") == 0) { + ResetCommand(output, ServerCommandType::kTtsStart); + return; + } + if (std::strcmp(state, "stop") == 0) { + ResetCommand(output, ServerCommandType::kTtsStop); + return; + } + if (std::strcmp(state, "sentence_start") == 0) { + ResetCommand(output, ServerCommandType::kTtsSentenceStart); + if (!CopyRequiredString( + root, + "text", + &output->conversation_text)) { + SetInvalid(output, kInvalidMessageError); + } + return; + } + if (std::strcmp(state, "sentence_end") == 0) { + ResetCommand(output, ServerCommandType::kTtsSentenceEnd); + return; + } + ResetCommand(output, ServerCommandType::kUnsupported); +} + +void ServerMessageDispatcher::ParseStt( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + ResetCommand(output, ServerCommandType::kSttText); + if (!CopyRequiredString( + root, + "text", + &output->conversation_text)) { + SetInvalid(output, kInvalidMessageError); + } +} + +void ServerMessageDispatcher::ParseLlm( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + ResetCommand(output, ServerCommandType::kLlmEmotion); + // The emotion string is advisory only: firmware logs it so the device-side + // trace lines up with the server dialogue log. An llm frame without a + // usable emotion is still a well-formed frame, not an error. + if (!CopyOptionalString( + root, "emotion", &output->conversation_text)) { + output->conversation_text.fill('\0'); + } +} + +void ServerMessageDispatcher::ParsePlayLocal( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const char* group = StringField(root, "group"); + ResetCommand(output, ServerCommandType::kPlayLocal); + ServerCommand& command = *output; + if (!LookupPrompt( + group, + &command.local_prompt, + &command.playback_priority)) { + ResetCommand(output, ServerCommandType::kUnsupported); + return; + } + + const cJSON* index = + cJSON_GetObjectItemCaseSensitive(root, "index"); + if (cJSON_IsNumber(index) && + index->valueint >= 0 && + index->valueint <= INT16_MAX) { + command.prompt_index = + static_cast(index->valueint); + } + + const char* post_action = StringField(root, "post_action"); + const cJSON* block_reconnect = + cJSON_GetObjectItemCaseSensitive(root, "block_reconnect"); + const bool has_new_fields = + post_action != nullptr || cJSON_IsBool(block_reconnect); + command.soft_off_after_playback = + (post_action != nullptr && + std::strcmp(post_action, "enter_soft_off") == 0) || + (!has_new_fields && + command.local_prompt == LocalPrompt::kShutdown) || + (command.local_prompt == LocalPrompt::kShutdown && + cJSON_IsTrue(block_reconnect)); +} + +void ServerMessageDispatcher::ParsePlayLocalSequence( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + const cJSON* sequence = + cJSON_GetObjectItemCaseSensitive(root, "sequence"); + if (!cJSON_IsArray(sequence) || + cJSON_GetArraySize(sequence) > + static_cast(kMaxLocalPromptSequenceItems)) { + SetInvalid(output, kInvalidMessageError); + return; + } + + ResetCommand(output, ServerCommandType::kPlayLocalSequence); + ServerCommand& command = *output; + const cJSON* item = nullptr; + cJSON_ArrayForEach(item, sequence) { + if (!cJSON_IsObject(item)) { + continue; + } + LocalPrompt prompt = LocalPrompt::kError; + PlaybackPriority priority = PlaybackPriority::kLocalPrompt; + if (!LookupPrompt( + StringField(item, "group"), + &prompt, + &priority)) { + continue; + } + int16_t selector = -1; + const cJSON* index = + cJSON_GetObjectItemCaseSensitive(item, "index"); + if (index != nullptr) { + int64_t parsed_index = 0; + if (!IntegerField( + item, + "index", + 0, + INT16_MAX, + &parsed_index)) { + continue; + } + selector = static_cast(parsed_index); + } + command.local_sequence.items[ + command.local_sequence.count++] = { + prompt, + selector, + }; + } + if (command.local_sequence.Empty()) { + ResetCommand(output, ServerCommandType::kUnsupported); + } +} + +void ServerMessageDispatcher::ParseMemorySync( + const void* opaque_root, + ServerCommand* output) const +{ + const auto* root = static_cast(opaque_root); + ResetCommand(output, ServerCommandType::kMemorySync); + ServerCommand& command = *output; + const cJSON* name = + cJSON_GetObjectItemCaseSensitive(root, "child_name"); + const cJSON* brain = + cJSON_GetObjectItemCaseSensitive(root, "brain_text"); + const cJSON* count = + cJSON_GetObjectItemCaseSensitive(root, "interaction_count"); + if ((name != nullptr && !cJSON_IsString(name)) || + (brain != nullptr && !cJSON_IsString(brain)) || + (count != nullptr && !cJSON_IsNumber(count)) || + !CopyOptionalString( + root, "child_name", &command.memory.child_name) || + !CopyOptionalString( + root, "brain_text", &command.memory.brain_text)) { + SetInvalid(output, kInvalidMessageError); + return; + } + if (count != nullptr) { + int64_t parsed_count = 0; + if (!IntegerField( + root, + "interaction_count", + 0, + INT32_MAX, + &parsed_count)) { + SetInvalid(output, kInvalidMessageError); + return; + } + command.memory.interaction_count = + static_cast(parsed_count); + } +} + +const char* ToString(ServerCommandType type) +{ + switch (type) { + case ServerCommandType::kInvalid: + return "invalid"; + case ServerCommandType::kUnsupported: + return "unsupported"; + case ServerCommandType::kHello: + return "hello"; + case ServerCommandType::kPing: + return "ping"; + case ServerCommandType::kPong: + return "pong"; + case ServerCommandType::kSttText: + return "stt_text"; + case ServerCommandType::kLlmEmotion: + return "llm_emotion"; + case ServerCommandType::kTtsStart: + return "tts_start"; + case ServerCommandType::kTtsStop: + return "tts_stop"; + case ServerCommandType::kTtsSentenceStart: + return "tts_sentence_start"; + case ServerCommandType::kTtsSentenceEnd: + return "tts_sentence_end"; + case ServerCommandType::kBargeIn: + return "barge_in"; + case ServerCommandType::kControl: + return "control"; + case ServerCommandType::kPlayLocal: + return "play_local"; + case ServerCommandType::kPlayLocalSequence: + return "play_local_sequence"; + case ServerCommandType::kMemorySync: + return "memory_sync"; + case ServerCommandType::kSetTimer: + return "set_timer"; + case ServerCommandType::kCancelTimer: + return "cancel_timer"; + case ServerCommandType::kSetAlarm: + return "set_alarm"; + case ServerCommandType::kDeleteAlarm: + return "delete_alarm"; + case ServerCommandType::kSyncAlarms: + return "sync_alarms"; + case ServerCommandType::kAlarmConfig: + return "alarm_config"; + case ServerCommandType::kCall: + return "call"; + case ServerCommandType::kEnterProvisioning: + return "enter_provisioning"; + case ServerCommandType::kError: + return "error"; + } + return "unknown"; +} + +const char* ToString(CallSignalState state) +{ + switch (state) { + case CallSignalState::kNone: + return "none"; + case CallSignalState::kRing: + return "ring"; + case CallSignalState::kInvite: + return "invite"; + case CallSignalState::kConnected: + return "connected"; + case CallSignalState::kEnded: + return "ended"; + case CallSignalState::kMissed: + return "missed"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/protocol/server_message_dispatcher.h b/main/protocol/server_message_dispatcher.h new file mode 100644 index 0000000..81de362 --- /dev/null +++ b/main/protocol/server_message_dispatcher.h @@ -0,0 +1,153 @@ +#pragma once + +#include "core/playback_types.h" +#include "core/remote_behavior.h" +#include "memory/memory_types.h" +#include "schedule/schedule_types.h" + +#include +#include +#include + +namespace borla { + +inline constexpr size_t kRealtimeSessionIdCapacity = 64; +inline constexpr size_t kCallIdCapacity = 96; +inline constexpr size_t kPeerNameCapacity = 64; +inline constexpr size_t kDeviceNameCapacity = 64; +inline constexpr size_t kConversationTextCapacity = 1024; + +enum class CallSignalState : uint8_t { + kNone, + kRing, + kInvite, + kConnected, + kEnded, + kMissed, +}; + +enum class RemoteControlAction : uint8_t { + kNone, + kVolume, + kWakeWord, + kBargeIn, + kLightSleep, + kLedAlert, +}; + +enum class BargeInDecisionState : uint8_t { + kNone, + kCandidate, + kRejected, + kConfirmed, +}; + +enum class ServerCommandType : uint8_t { + kInvalid, + kUnsupported, + kHello, + kPing, + kPong, + kSttText, + kLlmEmotion, + kTtsStart, + kTtsStop, + kTtsSentenceStart, + kTtsSentenceEnd, + kBargeIn, + kControl, + kPlayLocal, + kPlayLocalSequence, + kMemorySync, + kSetTimer, + kCancelTimer, + kSetAlarm, + kDeleteAlarm, + kSyncAlarms, + kAlarmConfig, + kCall, + kEnterProvisioning, + kError, +}; + +struct ServerCommand { + ServerCommandType type = ServerCommandType::kInvalid; + uint32_t error_id = 0; + std::array session_id{}; + std::array device_name{}; + std::array call_id{}; + std::array peer_name{}; + std::array conversation_text{}; + ButtonAction triple_click_action = ButtonAction::kUnspecified; + ButtonAction quadruple_click_action = ButtonAction::kUnspecified; + LocalPrompt server_unreachable_prompt = LocalPrompt::kServerError; + LocalPrompt no_network_prompt = LocalPrompt::kNoNetwork; + bool has_server_unreachable_prompt = false; + bool has_no_network_prompt = false; + CallSignalState call_state = CallSignalState::kNone; + RemoteControlAction control_action = RemoteControlAction::kNone; + BargeInDecisionState barge_in_state = BargeInDecisionState::kNone; + int32_t control_value = 0; + uint32_t output_sample_rate = 0; + uint16_t frame_duration_ms = 0; + int64_t server_time_seconds = 0; + int32_t timezone_offset_seconds = 0; + LocalPrompt local_prompt = LocalPrompt::kError; + PlaybackPriority playback_priority = PlaybackPriority::kLocalPrompt; + int16_t prompt_index = -1; + bool soft_off_after_playback = false; + LocalPromptSequence local_sequence{}; + MemorySnapshot memory{}; + uint32_t duration_seconds = 0; + TimerCancelScope timer_cancel_scope = TimerCancelScope::kNext; + AlarmEntry alarm{}; + AlarmList alarms{}; + int32_t alarm_id = 0; + int8_t set_tone_index = -1; + int8_t wake_tone_index = -1; +}; + +class ServerMessageDispatcher final { +public: + bool ParseInto( + const char* json, + size_t size, + ServerCommand* output) const; + +private: + void ParseHello(const void* root, ServerCommand* output) const; + void ParseStt(const void* root, ServerCommand* output) const; + void ParseLlm(const void* root, ServerCommand* output) const; + void ParseTts(const void* root, ServerCommand* output) const; + void ParseBargeIn(const void* root, ServerCommand* output) const; + void ParseControl(const void* root, ServerCommand* output) const; + void ParsePlayLocal( + const void* root, + ServerCommand* output) const; + void ParsePlayLocalSequence( + const void* root, + ServerCommand* output) const; + void ParseMemorySync( + const void* root, + ServerCommand* output) const; + void ParseSetTimer(const void* root, ServerCommand* output) const; + void ParseCancelTimer( + const void* root, + ServerCommand* output) const; + void ParseSetAlarm(const void* root, ServerCommand* output) const; + void ParseDeleteAlarm( + const void* root, + ServerCommand* output) const; + void ParseSyncAlarms( + const void* root, + ServerCommand* output) const; + void ParseAlarmConfig( + const void* root, + ServerCommand* output) const; + void ParseCall(const void* root, ServerCommand* output) const; +}; + +const char* ToString(ServerCommandType type); +const char* ToString(CallSignalState state); + +} // namespace borla diff --git a/main/protocol/utf8_text.h b/main/protocol/utf8_text.h new file mode 100644 index 0000000..fe8d6d7 --- /dev/null +++ b/main/protocol/utf8_text.h @@ -0,0 +1,48 @@ +#pragma once + +#include + +namespace borla { +namespace utf8_text { + +// Continuation bytes are 0b10xxxxxx — every byte of a multi-byte sequence +// except the first. +inline bool IsContinuationByte(char value) +{ + return (static_cast(value) & 0xC0) == 0x80; +} + +// Longest prefix of `text` that is at most `max_bytes` long AND ends on a UTF-8 +// character boundary. Returns the length in bytes; the caller copies that many. +// +// Truncating on a raw byte boundary is not a cosmetic problem. The previous +// firmware capped the same field with substr(0, 100), which splits a 3-byte +// Chinese character straddling byte 100 into an incomplete sequence. The +// server's websockets library validates text frames as UTF-8 and force-closes +// with code 1007 (invalid frame payload data) — seen in production as "invalid +// continuation byte at position 214", killing the session mid-story. JSON +// escaping does not help: half a character is still invalid UTF-8, and cJSON +// escapes control characters without validating encoding. +inline size_t SafeTruncatedLength( + const char* text, + size_t length, + size_t max_bytes) +{ + if (text == nullptr) { + return 0; + } + if (length <= max_bytes) { + return length; + } + // Walk left from the cap until the byte at the cut is a lead byte, i.e. + // the start of the character that is being dropped. Everything before it + // is then a run of complete characters. + size_t end = max_bytes; + while (end > 0 && IsContinuationByte(text[end])) { + --end; + } + return end; +} + +} // namespace utf8_text +} // namespace borla diff --git a/main/protocol/websocket_transport.h b/main/protocol/websocket_transport.h new file mode 100644 index 0000000..f3b735b --- /dev/null +++ b/main/protocol/websocket_transport.h @@ -0,0 +1,53 @@ +#pragma once + +#include +#include +#include +#include + +namespace borla { + +inline constexpr size_t kWebsocketUrlCapacity = 512; +inline constexpr size_t kWebsocketTokenCapacity = 320; +inline constexpr size_t kWebsocketDeviceIdCapacity = 24; +inline constexpr size_t kWebsocketFirmwareVersionCapacity = 48; + +struct WebsocketTransportConfig { + std::array url{}; + std::array token{}; + std::array device_id{}; + std::array firmware_version{}; + uint8_t protocol_version = 3; + uint32_t connect_timeout_ms = 15000; +}; + +class IWebsocketTransportObserver { +public: + virtual ~IWebsocketTransportObserver() = default; + virtual void OnWebsocketConnected() = 0; + virtual void OnWebsocketDisconnected(int error_code) = 0; + virtual void OnWebsocketText(const char* data, size_t size) = 0; + virtual void OnWebsocketBinary( + const uint8_t* data, + size_t size) = 0; +}; + +class IWebsocketTransport { +public: + virtual ~IWebsocketTransport() = default; + + virtual bool Initialize() = 0; + virtual bool Open( + const WebsocketTransportConfig& config, + IWebsocketTransportObserver& observer) = 0; + virtual void Close() = 0; + virtual bool SendText(const char* data, size_t size) = 0; + virtual bool SendTelemetryText(const char* data, size_t size) + { + return SendText(data, size); + } + virtual bool SendBinary(const uint8_t* data, size_t size) = 0; + virtual bool IsConnected() const = 0; +}; + +} // namespace borla diff --git a/main/protocol/websocket_uri.cc b/main/protocol/websocket_uri.cc new file mode 100644 index 0000000..a9eac67 --- /dev/null +++ b/main/protocol/websocket_uri.cc @@ -0,0 +1,143 @@ +#include "protocol/websocket_uri.h" + +#include "connectivity/wifi_types.h" + +#include +#include + +namespace borla { +namespace { + +bool CopyRange( + const char* begin, + const char* end, + char* output, + size_t capacity) +{ + if (begin == nullptr || end == nullptr || output == nullptr || + end <= begin || static_cast(end - begin) >= capacity) { + return false; + } + const size_t size = static_cast(end - begin); + std::memcpy(output, begin, size); + output[size] = '\0'; + return true; +} + +bool ParsePort(const char* begin, const char* end, uint16_t* output) +{ + if (begin == nullptr || end == nullptr || output == nullptr || + begin >= end) { + return false; + } + uint32_t value = 0; + for (const char* cursor = begin; cursor < end; ++cursor) { + if (!std::isdigit(static_cast(*cursor))) { + return false; + } + value = value * 10U + + static_cast(*cursor - '0'); + if (value > 65535U) { + return false; + } + } + if (value == 0) { + return false; + } + *output = static_cast(value); + return true; +} + +} // namespace + +bool ParseWebsocketUri(const char* uri, WebsocketUri* output) +{ + if (uri == nullptr || output == nullptr) { + return false; + } + const size_t uri_size = BoundedStringLength(uri, 1024); + if (uri_size == 0 || uri_size >= 1024) { + return false; + } + + WebsocketUri parsed; + const char* authority = nullptr; + if (std::strncmp(uri, "ws://", 5) == 0) { + parsed.secure = false; + parsed.port = 80; + authority = uri + 5; + } else if (std::strncmp(uri, "wss://", 6) == 0) { + parsed.secure = true; + parsed.port = 443; + authority = uri + 6; + } else { + return false; + } + + const char* const uri_end = uri + uri_size; + const char* path = std::strchr(authority, '/'); + const char* authority_end = path == nullptr ? uri_end : path; + if (authority >= authority_end) { + return false; + } + + const char* port_separator = nullptr; + if (*authority == '[') { + const char* bracket = std::strchr(authority, ']'); + if (bracket == nullptr || bracket >= authority_end || + !CopyRange( + authority + 1, + bracket, + parsed.host.data(), + parsed.host.size())) { + return false; + } + if (bracket + 1 < authority_end) { + if (*(bracket + 1) != ':') { + return false; + } + port_separator = bracket + 1; + } + } else { + for (const char* cursor = authority; + cursor < authority_end; + ++cursor) { + if (*cursor == ':') { + if (port_separator != nullptr) { + return false; + } + port_separator = cursor; + } + } + const char* host_end = + port_separator == nullptr ? authority_end : port_separator; + if (!CopyRange( + authority, + host_end, + parsed.host.data(), + parsed.host.size())) { + return false; + } + } + + if (port_separator != nullptr && + !ParsePort(port_separator + 1, authority_end, &parsed.port)) { + return false; + } + + if (path == nullptr) { + parsed.path[0] = '/'; + parsed.path[1] = '\0'; + } else if (!CopyRange( + path, + uri_end, + parsed.path.data(), + parsed.path.size())) { + return false; + } + + *output = parsed; + return true; +} + +} // namespace borla diff --git a/main/protocol/websocket_uri.h b/main/protocol/websocket_uri.h new file mode 100644 index 0000000..84fc832 --- /dev/null +++ b/main/protocol/websocket_uri.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +inline constexpr size_t kWebsocketHostCapacity = 128; +inline constexpr size_t kWebsocketPathCapacity = 384; + +struct WebsocketUri { + bool secure = false; + uint16_t port = 0; + std::array host{}; + std::array path{}; +}; + +bool ParseWebsocketUri(const char* uri, WebsocketUri* output); + +} // namespace borla diff --git a/main/provisioning/ble_provisioning_codec.cc b/main/provisioning/ble_provisioning_codec.cc new file mode 100644 index 0000000..57c4eb1 --- /dev/null +++ b/main/provisioning/ble_provisioning_codec.cc @@ -0,0 +1,269 @@ +#include "provisioning/ble_provisioning_codec.h" + +#include +#include + +#include + +namespace borla { +namespace { + +bool PrintJson( + cJSON* root, + char* output, + size_t capacity, + size_t* output_size) +{ + if (root == nullptr || output == nullptr || + capacity < 2 || output_size == nullptr) { + cJSON_Delete(root); + return false; + } + const bool printed = + cJSON_PrintPreallocated( + root, + output, + static_cast(capacity), + false) != 0; + cJSON_Delete(root); + if (!printed) { + output[0] = '\0'; + *output_size = 0; + return false; + } + *output_size = std::strlen(output); + return true; +} + +bool AddString(cJSON* object, const char* name, const char* value) +{ + return cJSON_AddStringToObject(object, name, value) != nullptr; +} + +} // namespace + +BleChunkAssemblyResult BleChunkAssembler::Push( + const uint8_t* packet, + size_t size) +{ + if (packet == nullptr || size < 3) { + Reset(); + return BleChunkAssemblyResult::kInvalid; + } + const uint8_t sequence = packet[0]; + const uint8_t flag = packet[1]; + if (flag > 1 || (!receiving_ && sequence != 0) || + (receiving_ && sequence != next_sequence_)) { + Reset(); + return BleChunkAssemblyResult::kInvalid; + } + + if (sequence == 0) { + Reset(); + receiving_ = true; + } + const size_t payload_size = size - 2; + if (payload_size == 0 || + size_ + payload_size >= buffer_.size()) { + Reset(); + return BleChunkAssemblyResult::kInvalid; + } + std::memcpy(buffer_.data() + size_, packet + 2, payload_size); + size_ += payload_size; + buffer_[size_] = '\0'; + next_sequence_ = static_cast(sequence + 1U); + + if (flag == 0) { + return BleChunkAssemblyResult::kAccepted; + } + receiving_ = false; + return BleChunkAssemblyResult::kComplete; +} + +void BleChunkAssembler::Reset() +{ + buffer_.fill('\0'); + size_ = 0; + next_sequence_ = 0; + receiving_ = false; +} + +bool VisitBleNotificationChunks( + const char* json, + size_t size, + uint16_t negotiated_mtu, + IBleChunkVisitor& visitor) +{ + if (json == nullptr || size == 0) { + return false; + } + const size_t att_payload = + negotiated_mtu > 3 + ? static_cast( + std::min(negotiated_mtu, 517) - 3) + : 20; + const size_t chunk_payload = + std::max( + 1, + att_payload > 2 ? att_payload - 2 : 18); + if ((size + chunk_payload - 1) / chunk_payload > 256) { + return false; + } + + std::array packet{}; + size_t offset = 0; + uint8_t sequence = 0; + while (offset < size) { + const size_t bytes = + std::min(chunk_payload, size - offset); + const bool last = offset + bytes == size; + packet[0] = sequence; + packet[1] = last ? 1 : 0; + std::memcpy(packet.data() + 2, json + offset, bytes); + if (!visitor.OnBleChunk(packet.data(), bytes + 2)) { + return false; + } + offset += bytes; + sequence++; + } + return true; +} + +bool ParseProvisioningCredential( + const char* json, + size_t size, + WifiCredential* credential) +{ + if (json == nullptr || credential == nullptr || + size == 0 || size >= kBleCredentialJsonCapacity || + std::memchr(json, '\0', size) != nullptr) { + return false; + } + std::array copy{}; + std::memcpy(copy.data(), json, size); + + cJSON* root = cJSON_Parse(copy.data()); + if (!cJSON_IsObject(root)) { + cJSON_Delete(root); + return false; + } + const cJSON* ssid = + cJSON_GetObjectItemCaseSensitive(root, "ssid"); + const cJSON* password = + cJSON_GetObjectItemCaseSensitive(root, "password"); + const bool valid = + cJSON_IsString(ssid) && + ssid->valuestring != nullptr && + (password == nullptr || cJSON_IsString(password)); + const bool set = + valid && credential->Set( + ssid->valuestring, + password == nullptr ? "" : password->valuestring); + cJSON_Delete(root); + return set; +} + +bool BuildProvisioningDeviceInfoJson( + const DeviceIdentity& identity, + char* output, + size_t capacity, + size_t* output_size) +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || + !AddString(root, "mac", identity.mac) || + !AddString(root, "version", identity.app_version) || + !AddString(root, "board", identity.board)) { + cJSON_Delete(root); + return false; + } + return PrintJson(root, output, capacity, output_size); +} + +bool BuildProvisioningScanJson( + const WifiNetwork* networks, + size_t count, + char* output, + size_t capacity, + size_t* output_size) +{ + if ((networks == nullptr && count != 0) || + count > kMaxProvisioningScanResults) { + return false; + } + cJSON* root = cJSON_CreateObject(); + cJSON* array = + root == nullptr ? nullptr : cJSON_AddArrayToObject(root, "networks"); + if (array == nullptr) { + cJSON_Delete(root); + return false; + } + for (size_t index = 0; index < count; ++index) { + cJSON* item = cJSON_CreateObject(); + if (item == nullptr || + !AddString(item, "ssid", networks[index].ssid.data()) || + cJSON_AddNumberToObject( + item, "rssi", networks[index].rssi_dbm) == nullptr || + cJSON_AddNumberToObject( + item, "auth", networks[index].auth_mode) == nullptr) { + cJSON_Delete(item); + cJSON_Delete(root); + return false; + } + cJSON_AddItemToArray(array, item); + } + return PrintJson(root, output, capacity, output_size); +} + +bool BuildProvisioningSavedWifiJson( + const WifiCredential* credentials, + size_t count, + char* output, + size_t capacity, + size_t* output_size) +{ + if ((credentials == nullptr && count != 0) || + count > kMaxSavedWifiCredentials) { + return false; + } + cJSON* root = cJSON_CreateObject(); + cJSON* array = + root == nullptr ? nullptr : cJSON_AddArrayToObject(root, "saved"); + if (array == nullptr) { + cJSON_Delete(root); + return false; + } + for (size_t index = 0; index < count; ++index) { + cJSON* item = cJSON_CreateObject(); + if (item == nullptr || + cJSON_AddNumberToObject(item, "index", index) == nullptr || + !AddString(item, "ssid", credentials[index].ssid.data())) { + cJSON_Delete(item); + cJSON_Delete(root); + return false; + } + cJSON_AddItemToArray(array, item); + } + return PrintJson(root, output, capacity, output_size); +} + +bool BuildProvisioningResultJson( + bool success, + const char* error, + char* output, + size_t capacity, + size_t* output_size) +{ + cJSON* root = cJSON_CreateObject(); + if (root == nullptr || + cJSON_AddBoolToObject(root, "success", success) == nullptr || + (!success && error != nullptr && + error[0] != '\0' && + !AddString(root, "error", error))) { + cJSON_Delete(root); + return false; + } + return PrintJson(root, output, capacity, output_size); +} + +} // namespace borla diff --git a/main/provisioning/ble_provisioning_codec.h b/main/provisioning/ble_provisioning_codec.h new file mode 100644 index 0000000..643f353 --- /dev/null +++ b/main/provisioning/ble_provisioning_codec.h @@ -0,0 +1,84 @@ +#pragma once + +#include "connectivity/wifi_types.h" +#include "ports/device_platform.h" + +#include +#include +#include + +namespace borla { + +inline constexpr size_t kBleProvisioningJsonCapacity = 4096; +inline constexpr size_t kBleCredentialJsonCapacity = 256; + +enum class BleChunkAssemblyResult : uint8_t { + kAccepted, + kComplete, + kInvalid, +}; + +class BleChunkAssembler final { +public: + BleChunkAssemblyResult Push( + const uint8_t* packet, + size_t size); + void Reset(); + + const char* data() const { return buffer_.data(); } + size_t size() const { return size_; } + +private: + std::array buffer_{}; + size_t size_ = 0; + uint8_t next_sequence_ = 0; + bool receiving_ = false; +}; + +class IBleChunkVisitor { +public: + virtual ~IBleChunkVisitor() = default; + virtual bool OnBleChunk( + const uint8_t* data, + size_t size) = 0; +}; + +bool VisitBleNotificationChunks( + const char* json, + size_t size, + uint16_t negotiated_mtu, + IBleChunkVisitor& visitor); + +bool ParseProvisioningCredential( + const char* json, + size_t size, + WifiCredential* credential); + +bool BuildProvisioningDeviceInfoJson( + const DeviceIdentity& identity, + char* output, + size_t capacity, + size_t* output_size); + +bool BuildProvisioningScanJson( + const WifiNetwork* networks, + size_t count, + char* output, + size_t capacity, + size_t* output_size); + +bool BuildProvisioningSavedWifiJson( + const WifiCredential* credentials, + size_t count, + char* output, + size_t capacity, + size_t* output_size); + +bool BuildProvisioningResultJson( + bool success, + const char* error, + char* output, + size_t capacity, + size_t* output_size); + +} // namespace borla diff --git a/main/provisioning/ble_provisioning_service.cc b/main/provisioning/ble_provisioning_service.cc new file mode 100644 index 0000000..23ecb3a --- /dev/null +++ b/main/provisioning/ble_provisioning_service.cc @@ -0,0 +1,486 @@ +#include "provisioning/ble_provisioning_service.h" + +#include + +#include +#include +#include +#include + +// Self-verifying build stamp: sdkconfig is gitignored, so a fix that only +// lives in sdkconfig.defaults silently misses any build whose sdkconfig was +// not regenerated. Logging the compiled mode makes a stale build obvious in +// the device log instead of reproducing "hci inits failed" mysteries. +#if CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL +#define BORLA_NIMBLE_POOLS "PSRAM" +#elif CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_INTERNAL +#define BORLA_NIMBLE_POOLS "internal (STALE sdkconfig — regenerate!)" +#else +#define BORLA_NIMBLE_POOLS "default" +#endif + +namespace borla { +namespace { + +constexpr const char* kTag = "BleProvService2"; +constexpr uint32_t kWifiStartTimeoutMs = 1500; +constexpr uint32_t kWifiConnectTimeoutMs = 10000; +constexpr uint32_t kNotifySubscriptionDelayMs = 120; +constexpr uint32_t kRebootDispatchDelayMs = 150; +// wifi_success.ogg runs about 1.2 s; 5 s leaves room for it to be queued +// behind another prompt without letting a stalled producer wedge the reboot. +constexpr uint32_t kRebootPlaybackDrainMs = 5000; +// 进配网时先让「请用小程序帮我连接网络」播完,再释放音频引擎给 BT 控制器腾内存。 +constexpr uint32_t kProvisioningPromptDrainMs = 3000; +constexpr uint32_t kProvisioningStartError = 7001; + +} // namespace + +BleProvisioningService::BleProvisioningService( + IWifiTransport& wifi, + IWifiCredentialStore& credentials, + IDevicePlatform& platform, + IAudioEngine& audio) + : wifi_(wifi), + credentials_(credentials), + platform_(platform), + audio_(audio) +{ +} + +bool BleProvisioningService::Initialize() +{ + if (initialized_.load()) { + return true; + } + queue_ = xQueueCreateStatic( + kQueueDepth, + sizeof(Command), + queue_storage_.data(), + &queue_control_); + wifi_events_ = + xEventGroupCreateStatic(&wifi_events_control_); + if (queue_ == nullptr || wifi_events_ == nullptr) { + ESP_LOGE(kTag, "queue/event group initialization failed"); + return false; + } + task_ = xTaskCreateStatic( + &BleProvisioningService::TaskEntry, + "ble_provision2", + task_stack_.size(), + this, + kTaskPriority, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + ESP_LOGE(kTag, "worker task creation failed"); + return false; + } + initialized_.store(true); + return true; +} + +void BleProvisioningService::SetEventPublisher( + IEventPublisher* publisher) +{ + publisher_.store(publisher); +} + +void BleProvisioningService::Start() +{ + if (!Post({CommandType::kStart, {}, 0})) { + ESP_LOGE(kTag, "failed to enqueue provisioning start"); + } +} + +void BleProvisioningService::Stop() +{ + if (!Post({CommandType::kStop, {}, 0})) { + ESP_LOGE(kTag, "failed to enqueue provisioning stop"); + } +} + +void BleProvisioningService::OnBleWifiScanRequested() +{ + Post({CommandType::kSendScan, {}, 0}); +} + +void BleProvisioningService::OnBleWifiCredential( + const WifiCredential& credential) +{ + Command command; + command.type = CommandType::kConnectCredential; + command.credential = credential; + Post(command); +} + +void BleProvisioningService::OnBleSavedWifiListRequested() +{ + Post({CommandType::kListSavedWifi, {}, 0}); +} + +void BleProvisioningService::OnBleSavedWifiDeleteRequested( + uint8_t index) +{ + Post({CommandType::kDeleteSavedWifi, {}, index}); +} + +void BleProvisioningService::OnBleRebootRequested() +{ + Post({CommandType::kReboot, {}, 0}); +} + +void BleProvisioningService::OnWifiTransportEvent( + const WifiTransportEvent& event) +{ + if (wifi_events_ == nullptr) { + return; + } + switch (event.type) { + case WifiTransportEventType::kStarted: + xEventGroupSetBits(wifi_events_, kWifiStartedBit); + break; + case WifiTransportEventType::kGotIp: + xEventGroupSetBits(wifi_events_, kWifiConnectedBit); + break; + case WifiTransportEventType::kDisconnected: + disconnect_reason_.store(event.disconnect_reason); + xEventGroupSetBits(wifi_events_, kWifiDisconnectedBit); + break; + case WifiTransportEventType::kReconnectRequested: + case WifiTransportEventType::kCellularOn: + case WifiTransportEventType::kCellularOff: + case WifiTransportEventType::kCellularUnavailable: + case WifiTransportEventType::kCellularBootOn: + break; + } +} + +void BleProvisioningService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void BleProvisioningService::Run() +{ + ESP_LOGI(kTag, "BLE provisioning worker started"); + while (true) { + Command command; + if (xQueueReceive(queue_, &command, portMAX_DELAY) == pdTRUE) { + Handle(command); + } + } +} + +bool BleProvisioningService::Post(const Command& command) +{ + return initialized_.load() && queue_ != nullptr && + xQueueSend(queue_, &command, 0) == pdTRUE; +} + +void BleProvisioningService::Handle(const Command& command) +{ + switch (command.type) { + case CommandType::kStart: + HandleStart(); + return; + case CommandType::kStop: + gatt_.Stop(); + wifi_.Stop(); + // Leaving provisioning without a reboot: the next full driver init + // has no BT controller to share with, so give the buffers back. + wifi_.UseLowMemoryProfile(false); + // A failed credential test leaves the codec released on purpose; the + // device is staying alive here rather than rebooting, so restore it or + // it would be silent from now on. + if (!audio_.Start()) { + ESP_LOGW(kTag, "audio restart on provisioning stop failed"); + } + active_ = false; + connection_attempt_active_ = false; + return; + case CommandType::kSendScan: + if (active_) { + vTaskDelay(pdMS_TO_TICKS(kNotifySubscriptionDelayMs)); + if (!gatt_.NotifyScanResults( + scan_results_.data(), scan_count_)) { + ESP_LOGW(kTag, "scan result notification failed"); + } + } + return; + case CommandType::kConnectCredential: + HandleConnect(command.credential); + return; + case CommandType::kListSavedWifi: + HandleListSavedWifi(); + return; + case CommandType::kDeleteSavedWifi: + HandleDeleteSavedWifi(command.index); + return; + case CommandType::kReboot: + // The phone sends this the moment it sees the success notification, so + // "配网成功啦" has only just been queued. Rebooting on a fixed short + // delay tore the decode queue and the I2S DMA down mid-sentence — the + // child heard half a word and then silence until the device came back. + // The previous firmware waited for playback to drain here too + // (wifi_board.cc SetRebootCallback, 3 s cap); the cap matters because a + // stuck producer must not be able to block the reboot forever. + vTaskDelay(pdMS_TO_TICKS(kRebootDispatchDelayMs)); + if (!audio_.WaitForPlaybackIdle(kRebootPlaybackDrainMs)) { + ESP_LOGW(kTag, "rebooting with playback still active"); + } + platform_.Reboot(); + return; + } +} + +void BleProvisioningService::HandleStart() +{ + if (active_) { + return; + } + + scan_results_.fill(WifiNetwork{}); + scan_count_ = 0; + xEventGroupClearBits(wifi_events_, kWifiBits); + if (wifi_.Start(*this)) { + xEventGroupWaitBits( + wifi_events_, + kWifiStartedBit, + pdTRUE, + pdFALSE, + pdMS_TO_TICKS(kWifiStartTimeoutMs)); + if (!wifi_.Scan( + scan_results_.data(), + scan_results_.size(), + &scan_count_)) { + ESP_LOGW(kTag, "pre-scan failed; BLE will expose empty list"); + scan_count_ = 0; + } + } else { + ESP_LOGW(kTag, "WiFi transport unavailable for pre-scan"); + } + // Tear the WiFi driver all the way down, not just stop it. The BT + // controller plus NimBLE host need ~65 KB of internal RAM at init and an + // idle-but-initialised WiFi driver holds tens of KB of packet buffers, so + // leaving it up makes nimble_port_init fail with "hci inits failed" and + // the device never advertises. Scan results are already cached above, and + // HandleConnect brings the driver back up when credentials arrive. + wifi_.ReleaseDriver(); + // Every later Start() in this provisioning session runs alongside the BT + // controller, so it must ask the driver for the small buffer profile. The + // pre-scan above deliberately ran on the default one: BLE was not up yet + // and scanning benefits from the full RX pool. + wifi_.UseLowMemoryProfile(true); + ESP_LOGI(kTag, + "internal RAM before BLE: free=%u largest=%u dma_free=%u " + "dma_largest=%u host_pools=%s", + static_cast( + heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)), + static_cast(heap_caps_get_free_size( + MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)), + static_cast(heap_caps_get_largest_free_block( + MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)), + BORLA_NIMBLE_POOLS); + // 分区域明细:BT 控制器要的是一个 30KB 连续内部块,只有看到每个 region 的 + // free/largest 才能判断失败是"总量不够"还是"碎片化"(见 sdkconfig.defaults + // 里 SPIRAM_MALLOC_RESERVE_INTERNAL 的说明)。 + heap_caps_print_heap_info(MALLOC_CAP_INTERNAL); + + // Free the audio engine so the BT controller has the internal RAM it needs + // (~30KB contiguous block for the controller plus the NimBLE host share). + // EnterProvisioning only applies AudioPolicy::kOff, which idles the capture + // task but keeps its 16KB internal stack and the I2S DMA descriptors alive; + // they are the two biggest consumers that would otherwise starve BLE init. + // Let the provisioning prompt finish first — it is the user's only + // confirmation that the double-click was heard. HandleConnect restarts the + // codec when there is something to say. + if (!audio_.WaitForPlaybackIdle(kProvisioningPromptDrainMs)) { + ESP_LOGW(kTag, "provisioning prompt still playing; releasing audio anyway"); + } + audio_.Stop(); + + if (!gatt_.Start(platform_.Identity(), *this)) { + ESP_LOGE(kTag, "BLE GATT server start failed"); + platform_.ReportError(kProvisioningStartError); + // Restore the codec so a retry (another double-click) can play the + // provisioning prompt again before re-entering this path. + if (!audio_.Start()) { + ESP_LOGW(kTag, "audio restart after BLE init failure"); + } + return; + } + active_ = true; + ESP_LOGI(kTag, "provisioning active cached_networks=%u", + static_cast(scan_count_)); +} + +void BleProvisioningService::HandleConnect( + WifiCredential credential) +{ + if (!active_ || connection_attempt_active_) { + gatt_.NotifyWifiResult(false, "unknown"); + return; + } + connection_attempt_active_ = true; + + if (credential.password[0] == '\0') { + RestoreSavedPassword(&credential); + } + xEventGroupClearBits(wifi_events_, kWifiBits); + disconnect_reason_.store(0); + + // Bringing the WiFi driver back up while the BT controller holds its own + // allocations is the tightest internal-RAM moment in the whole firmware, + // and the binding constraint is not plain internal RAM but the DMA-capable + // subset: the driver's static RX buffers are 1600-byte DMA allocations and + // that is exactly where it fails ("wifi:malloc buffer fail" with tens of KB + // still free overall). + // + // I2S is the other big consumer of that pool — 6 descriptors x 240 frames + // on both directions, roughly 11 KB — and nothing needs the speaker or the + // microphone while a credential is being tested. Release the codec for the + // duration and bring it back afterwards so the success prompt can still + // play. + audio_.Stop(); + ESP_LOGI(kTag, + "internal RAM before WiFi retry (audio released): " + "free=%u largest=%u dma_free=%u dma_largest=%u", + static_cast( + heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), + static_cast( + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)), + static_cast(heap_caps_get_free_size( + MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA)), + static_cast(heap_caps_get_largest_free_block( + MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA))); + + bool success = false; + const char* error = "unknown"; + if (!wifi_.Start(*this)) { + // Almost always internal-RAM exhaustion at esp_wifi_init(); the log + // line above carries the number that proves it. + ESP_LOGE(kTag, "WiFi driver restart failed; cannot test credential"); + } else if (wifi_.Connect(credential)) { + const EventBits_t result = xEventGroupWaitBits( + wifi_events_, + kWifiConnectedBit | kWifiDisconnectedBit, + pdTRUE, + pdFALSE, + pdMS_TO_TICKS(kWifiConnectTimeoutMs)); + if ((result & kWifiConnectedBit) != 0) { + if (credentials_.SaveAndPromote(credential)) { + success = true; + error = ""; + } else { + ESP_LOGE(kTag, "connected credential NVS save failed"); + } + } else if ((result & kWifiDisconnectedBit) != 0) { + error = MapDisconnectError(disconnect_reason_.load()); + } else { + error = "timeout"; + } + } + + // Stop WiFi before notifying: this gives the BLE connection exclusive + // radio time and makes the result notification reliable on ESP32-S3. + wifi_.Stop(); + // Only bring the codec back when there is something to say. After a failed + // attempt the phone will almost certainly send another credential, and that + // retry starts from a worse position than this one did: esp_wifi_init() + // leaks a few KB on the failure path (IDF's own cleanup reports "Failed to + // deinit Wi-Fi driver (0x3001)"). Leaving the codec released keeps its + // ~7 KB — and the contiguous block it occupies — available for that retry. + if (!success) { + ESP_LOGI(kTag, "codec left released for the next attempt"); + } else if (!audio_.Start()) { + ESP_LOGW(kTag, "audio restart after WiFi retry failed"); + } else { + // "配网成功啦" — published after the codec is alive again, and routed + // through the reducer so the control plane stays the single writer of + // playback decisions. + Publish(AppEvent::Make( + AppEventType::kProvisioningWifiSaved)); + } + if (!gatt_.NotifyWifiResult(success, error)) { + ESP_LOGW(kTag, "WiFi result notification failed success=%d", + success ? 1 : 0); + } + connection_attempt_active_ = false; +} + +void BleProvisioningService::HandleListSavedWifi() +{ + std::array saved{}; + const size_t count = + credentials_.Load(saved.data(), saved.size()); + if (!gatt_.NotifySavedWifi(saved.data(), count)) { + ESP_LOGW(kTag, "saved WiFi list notification failed"); + } +} + +void BleProvisioningService::HandleDeleteSavedWifi(uint8_t index) +{ + std::array saved{}; + const size_t count = + credentials_.Load(saved.data(), saved.size()); + const bool valid = index < count; + const bool success = + valid && credentials_.Remove(saved[index].ssid.data()); + if (!gatt_.NotifySavedWifiResult( + success, success ? "" : "invalid_index")) { + ESP_LOGW(kTag, "saved WiFi delete notification failed"); + } +} + +bool BleProvisioningService::RestoreSavedPassword( + WifiCredential* credential) +{ + if (credential == nullptr) { + return false; + } + std::array saved{}; + const size_t count = + credentials_.Load(saved.data(), saved.size()); + for (size_t index = 0; index < count; ++index) { + if (std::strncmp( + saved[index].ssid.data(), + credential->ssid.data(), + kWifiSsidCapacity) == 0) { + credential->password = saved[index].password; + return true; + } + } + return false; +} + +void BleProvisioningService::Publish(const AppEvent& event) +{ + IEventPublisher* publisher = publisher_.load(); + if (publisher == nullptr || !publisher->Publish(event)) { + ESP_LOGE(kTag, "event publish failed type=%s", + ToString(event.type)); + } +} + +const char* BleProvisioningService::MapDisconnectError( + uint16_t reason) const +{ + switch (reason) { + case WIFI_REASON_NO_AP_FOUND: + case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD: + case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD: + return "not_found"; + case WIFI_REASON_AUTH_EXPIRE: + case WIFI_REASON_AUTH_FAIL: + case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: + case WIFI_REASON_HANDSHAKE_TIMEOUT: + return "password_wrong"; + default: + return "unknown"; + } +} + +} // namespace borla diff --git a/main/provisioning/ble_provisioning_service.h b/main/provisioning/ble_provisioning_service.h new file mode 100644 index 0000000..a4346e8 --- /dev/null +++ b/main/provisioning/ble_provisioning_service.h @@ -0,0 +1,116 @@ +#pragma once + +#include "connectivity/wifi_credential_store.h" +#include "connectivity/wifi_transport.h" +#include "core/task_stack_budget.h" +#include "platform/borla_s3/ble_provisioning_gatt.h" +#include "ports/audio_engine.h" +#include "ports/device_platform.h" +#include "ports/event_publisher.h" +#include "ports/provisioning_service.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace borla { + +class BleProvisioningService final + : public IProvisioningService, + public IBleProvisioningGattObserver, + public IWifiTransportObserver { +public: + BleProvisioningService( + IWifiTransport& wifi, + IWifiCredentialStore& credentials, + IDevicePlatform& platform, + IAudioEngine& audio); + + bool Initialize(); + void SetEventPublisher(IEventPublisher* publisher); + void Start() override; + void Stop() override; + + void OnBleWifiScanRequested() override; + void OnBleWifiCredential( + const WifiCredential& credential) override; + void OnBleSavedWifiListRequested() override; + void OnBleSavedWifiDeleteRequested(uint8_t index) override; + void OnBleRebootRequested() override; + void OnWifiTransportEvent( + const WifiTransportEvent& event) override; + +private: + enum class CommandType : uint8_t { + kStart, + kStop, + kSendScan, + kConnectCredential, + kListSavedWifi, + kDeleteSavedWifi, + kReboot, + }; + + struct Command { + CommandType type = CommandType::kStart; + WifiCredential credential{}; + uint8_t index = 0; + }; + + static constexpr size_t kQueueDepth = 12; + static constexpr UBaseType_t kTaskPriority = 5; + static constexpr EventBits_t kWifiStartedBit = BIT0; + static constexpr EventBits_t kWifiConnectedBit = BIT1; + static constexpr EventBits_t kWifiDisconnectedBit = BIT2; + static constexpr EventBits_t kWifiBits = + kWifiStartedBit | kWifiConnectedBit | kWifiDisconnectedBit; + + static void TaskEntry(void* context); + [[noreturn]] void Run(); + bool Post(const Command& command); + void Handle(const Command& command); + void HandleStart(); + void HandleConnect(WifiCredential credential); + void HandleListSavedWifi(); + void HandleDeleteSavedWifi(uint8_t index); + bool RestoreSavedPassword(WifiCredential* credential); + const char* MapDisconnectError(uint16_t reason) const; + void Publish(const AppEvent& event); + + IWifiTransport& wifi_; + IWifiCredentialStore& credentials_; + IDevicePlatform& platform_; + IAudioEngine& audio_; + BleProvisioningGattServer gatt_; + std::array + scan_results_{}; + size_t scan_count_ = 0; + + QueueHandle_t queue_ = nullptr; + StaticQueue_t queue_control_{}; + alignas(Command) + std::array + queue_storage_{}; + EventGroupHandle_t wifi_events_ = nullptr; + StaticEventGroup_t wifi_events_control_{}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array< + StackType_t, + task_stack_budget::kBleProvisioningBytes> + task_stack_{}; + + std::atomic publisher_{nullptr}; + std::atomic disconnect_reason_{0}; + std::atomic initialized_{false}; + bool active_ = false; + bool connection_attempt_active_ = false; +}; + +} // namespace borla diff --git a/main/schedule/alarm_schedule.cc b/main/schedule/alarm_schedule.cc new file mode 100644 index 0000000..db1ff06 --- /dev/null +++ b/main/schedule/alarm_schedule.cc @@ -0,0 +1,173 @@ +#include "schedule/alarm_schedule.h" + +#include +#include + +namespace borla { +namespace { + +bool IsBuiltIn(const AlarmEntry& alarm) +{ + return alarm.id == kBuiltInFirstDayAlarmId; +} + +AlarmEntry BuiltInAlarm() +{ + AlarmEntry alarm; + alarm.id = kBuiltInFirstDayAlarmId; + alarm.hour = 20; + alarm.minute = 30; + alarm.repeat_mask = 0x7F; + alarm.enabled = true; + std::strncpy( + alarm.label.data(), + "first_day_sleep_prompt", + alarm.label.size() - 1); + return alarm; +} + +} // namespace + +bool AlarmSchedule::Validate(const AlarmEntry& alarm) +{ + return alarm.id != 0 && + alarm.hour < 24 && + alarm.minute < 60 && + alarm.repeat_mask <= 0x7F && + alarm.label.back() == '\0' && + (alarm.repeat_mask != 0 || alarm.fire_epoch >= 0); +} + +bool AlarmSchedule::Upsert(const AlarmEntry& alarm) +{ + if (!Validate(alarm)) { + return false; + } + for (size_t i = 0; i < alarms_.count; ++i) { + if (alarms_.entries[i].id == alarm.id) { + alarms_.entries[i] = alarm; + return true; + } + } + if (alarms_.count >= alarms_.entries.size()) { + return false; + } + alarms_.entries[alarms_.count++] = alarm; + return true; +} + +bool AlarmSchedule::Delete(int32_t id) +{ + for (size_t i = 0; i < alarms_.count; ++i) { + if (alarms_.entries[i].id != id) { + continue; + } + std::move( + alarms_.entries.begin() + i + 1, + alarms_.entries.begin() + alarms_.count, + alarms_.entries.begin() + i); + alarms_.entries[--alarms_.count] = {}; + if (id == kBuiltInFirstDayAlarmId) { + first_day_consumed_ = true; + } + return true; + } + return false; +} + +bool AlarmSchedule::Replace(const AlarmList& alarms) +{ + if (alarms.count > alarms.entries.size()) { + return false; + } + AlarmList replacement; + for (size_t i = 0; i < alarms.count; ++i) { + if (!Validate(alarms.entries[i]) || + replacement.count >= replacement.entries.size()) { + return false; + } + bool duplicate = false; + for (size_t j = 0; j < replacement.count; ++j) { + duplicate |= + replacement.entries[j].id == alarms.entries[i].id; + } + if (duplicate) { + return false; + } + replacement.entries[replacement.count++] = alarms.entries[i]; + } + alarms_ = replacement; + return true; +} + +bool AlarmSchedule::EnsureBuiltInFirstDay(bool consumed) +{ + first_day_consumed_ = consumed; + if (consumed) { + Delete(kBuiltInFirstDayAlarmId); + first_day_consumed_ = true; + return true; + } + // The built-in first-day prompt is optional. When the user list already + // fills every slot there is no room for it, but that must not fail the + // whole sync or boot; first_day_consumed_ stays false so a later sync with + // free capacity can still install it. + Upsert(BuiltInAlarm()); + return true; +} + +bool AlarmSchedule::Matches( + const AlarmEntry& alarm, + const CalendarMinute& local_time, + int64_t epoch_seconds) +{ + if (!Validate(alarm) || !alarm.enabled || + alarm.hour != local_time.hour || + alarm.minute != local_time.minute) { + return false; + } + if (alarm.repeat_mask != 0) { + return (alarm.repeat_mask & + (1U << local_time.week_day)) != 0; + } + if (alarm.fire_epoch == 0) { + return true; + } + const int64_t difference = + epoch_seconds - alarm.fire_epoch; + return difference >= 0 && difference < 60; +} + +AlarmFireBatch AlarmSchedule::TakeDue( + const CalendarMinute& local_time, + int64_t epoch_seconds) +{ + AlarmFireBatch result; + const int64_t minute_key = epoch_seconds / 60; + if (minute_key == last_fired_minute_key_) { + return result; + } + for (size_t i = 0; i < alarms_.count; ++i) { + AlarmEntry& alarm = alarms_.entries[i]; + if (!Matches(alarm, local_time, epoch_seconds)) { + continue; + } + result.ids[result.count++] = alarm.id; + if (IsBuiltIn(alarm)) { + result.built_in_first_day = true; + first_day_consumed_ = true; + alarm.enabled = false; + } else { + result.play_audio = true; + } + if (alarm.repeat_mask == 0) { + alarm.enabled = false; + } + } + if (result.count > 0) { + last_fired_minute_key_ = minute_key; + } + return result; +} + +} // namespace borla diff --git a/main/schedule/alarm_schedule.h b/main/schedule/alarm_schedule.h new file mode 100644 index 0000000..e42e08c --- /dev/null +++ b/main/schedule/alarm_schedule.h @@ -0,0 +1,35 @@ +#pragma once + +#include "schedule/schedule_types.h" + +#include +#include + +namespace borla { + +class AlarmSchedule final { +public: + bool Upsert(const AlarmEntry& alarm); + bool Delete(int32_t id); + bool Replace(const AlarmList& alarms); + bool EnsureBuiltInFirstDay(bool consumed); + AlarmFireBatch TakeDue( + const CalendarMinute& local_time, + int64_t epoch_seconds); + + const AlarmList& list() const { return alarms_; } + bool first_day_consumed() const { return first_day_consumed_; } + + static bool Validate(const AlarmEntry& alarm); + static bool Matches( + const AlarmEntry& alarm, + const CalendarMinute& local_time, + int64_t epoch_seconds); + +private: + AlarmList alarms_{}; + bool first_day_consumed_ = false; + int64_t last_fired_minute_key_ = -1; +}; + +} // namespace borla diff --git a/main/schedule/alarm_service.cc b/main/schedule/alarm_service.cc new file mode 100644 index 0000000..76898e8 --- /dev/null +++ b/main/schedule/alarm_service.cc @@ -0,0 +1,236 @@ +#include "schedule/alarm_service.h" + +#include "core/psram_object.h" + +#include +#include + +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "AlarmService2"; +constexpr int64_t kMinimumValidEpoch = 1700000000; +constexpr int64_t kMaximumWakeSearchSeconds = + 8LL * 24LL * 60LL * 60LL; + +class Lock final { +public: + explicit Lock(SemaphoreHandle_t mutex) : mutex_(mutex) + { + xSemaphoreTake(mutex_, portMAX_DELAY); + } + ~Lock() { xSemaphoreGive(mutex_); } + +private: + SemaphoreHandle_t mutex_; +}; + +bool ToneValid(int8_t index) +{ + return index >= -1 && index <= 15; +} + +} // namespace + +bool AlarmService::Initialize( + IEventPublisher& publisher, + IScheduleEventSink& event_sink) +{ + if (running_.load()) { + return true; + } + publisher_ = &publisher; + event_sink_ = &event_sink; + mutex_ = xSemaphoreCreateMutexStatic(&mutex_control_); + if (mutex_ == nullptr) { + return false; + } + AlarmStoreSnapshot stored; + if (!store_.Load(&stored) || + !schedule_.Replace(stored.alarms) || + !schedule_.EnsureBuiltInFirstDay( + stored.first_day_consumed)) { + ESP_LOGE(kTag, "persisted alarm initialization failed"); + return false; + } + set_tone_index_.store(stored.set_tone_index); + wake_tone_index_.store(stored.wake_tone_index); + if (!SaveLocked()) { + return false; + } + + running_.store(true); + task_ = xTaskCreateStatic( + &AlarmService::TaskEntry, + "alarm2", + task_stack_.size(), + this, + 4, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + running_.store(false); + return false; + } + return true; +} + +void AlarmService::Stop() +{ + running_.store(false); +} + +bool AlarmService::Set(const AlarmEntry& alarm) +{ + if (mutex_ == nullptr) { + return false; + } + Lock lock(mutex_); + return schedule_.Upsert(alarm) && SaveLocked(); +} + +void AlarmService::Delete(int32_t id) +{ + if (mutex_ == nullptr) { + return; + } + Lock lock(mutex_); + if (schedule_.Delete(id)) { + SaveLocked(); + } +} + +bool AlarmService::Sync(const AlarmList& alarms) +{ + if (mutex_ == nullptr) { + return false; + } + Lock lock(mutex_); + const bool consumed = schedule_.first_day_consumed(); + return schedule_.Replace(alarms) && + schedule_.EnsureBuiltInFirstDay(consumed) && + SaveLocked(); +} + +void AlarmService::SetToneIndices( + int8_t set_tone_index, + int8_t wake_tone_index) +{ + if (mutex_ == nullptr || + !ToneValid(set_tone_index) || + !ToneValid(wake_tone_index)) { + return; + } + Lock lock(mutex_); + set_tone_index_.store(set_tone_index); + wake_tone_index_.store(wake_tone_index); + SaveLocked(); +} + +uint64_t AlarmService::NextWakeupDelayUs() const +{ + const int64_t now = static_cast(std::time(nullptr)); + if (mutex_ == nullptr || now < kMinimumValidEpoch) { + return 0; + } + Lock lock(mutex_); + const AlarmList alarms = schedule_.list(); + int64_t candidate = now - now % 60 + 60; + const int64_t end = now + kMaximumWakeSearchSeconds; + for (; candidate <= end; candidate += 60) { + CalendarMinute calendar; + if (!MakeCalendar(candidate, &calendar)) { + return 0; + } + for (size_t i = 0; i < alarms.count; ++i) { + if (AlarmSchedule::Matches( + alarms.entries[i], calendar, candidate)) { + return static_cast( + std::max(1, candidate - now)) * + 1000000ULL; + } + } + } + return 0; +} + +void AlarmService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void AlarmService::Run() +{ + while (running_.load()) { + const int64_t now = + static_cast(std::time(nullptr)); + if (now >= kMinimumValidEpoch) { + CalendarMinute calendar; + AlarmFireBatch due; + if (MakeCalendar(now, &calendar)) { + Lock lock(mutex_); + due = schedule_.TakeDue(calendar, now); + if (due.count > 0) { + SaveLocked(); + } + } + for (size_t i = 0; i < due.count; ++i) { + if (due.ids[i] > 0 && event_sink_ != nullptr) { + event_sink_->SendAlarmFired(due.ids[i], now); + } + } + if (due.play_audio && publisher_ != nullptr) { + publisher_->Publish( + AppEvent::Make(AppEventType::kAlarmDue)); + } else if (due.built_in_first_day && + publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kFirstDayAlarmDue)); + } + } + vTaskDelay(pdMS_TO_TICKS(500)); + } + task_ = nullptr; + vTaskDelete(nullptr); +} + +bool AlarmService::SaveLocked() +{ + auto snapshot = MakePsramObject(); + if (!snapshot) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + return false; + } + snapshot->alarms = schedule_.list(); + snapshot->first_day_consumed = + schedule_.first_day_consumed(); + snapshot->set_tone_index = set_tone_index_.load(); + snapshot->wake_tone_index = wake_tone_index_.load(); + return store_.Save(*snapshot); +} + +bool AlarmService::MakeCalendar( + int64_t epoch_seconds, + CalendarMinute* calendar) +{ + if (calendar == nullptr) { + return false; + } + const time_t value = static_cast(epoch_seconds); + tm local{}; + if (localtime_r(&value, &local) == nullptr) { + return false; + } + *calendar = { + .year = local.tm_year, + .year_day = local.tm_yday, + .week_day = local.tm_wday, + .hour = local.tm_hour, + .minute = local.tm_min, + }; + return true; +} + +} // namespace borla diff --git a/main/schedule/alarm_service.h b/main/schedule/alarm_service.h new file mode 100644 index 0000000..4032687 --- /dev/null +++ b/main/schedule/alarm_service.h @@ -0,0 +1,64 @@ +#pragma once + +#include "core/task_stack_budget.h" +#include "ports/event_publisher.h" +#include "schedule/alarm_schedule.h" +#include "schedule/alarm_store.h" +#include "schedule/schedule_types.h" + +#include +#include +#include + +#include +#include +#include + +namespace borla { + +class AlarmService final { +public: + explicit AlarmService(IAlarmStore& store) : store_(store) {} + + bool Initialize( + IEventPublisher& publisher, + IScheduleEventSink& event_sink); + void Stop(); + + bool Set(const AlarmEntry& alarm); + void Delete(int32_t id); + bool Sync(const AlarmList& alarms); + void SetToneIndices( + int8_t set_tone_index, + int8_t wake_tone_index); + int8_t wake_tone_index() const + { + return wake_tone_index_.load(); + } + uint64_t NextWakeupDelayUs() const; + +private: + static void TaskEntry(void* context); + void Run(); + bool SaveLocked(); + static bool MakeCalendar( + int64_t epoch_seconds, + CalendarMinute* calendar); + + IAlarmStore& store_; + IEventPublisher* publisher_ = nullptr; + IScheduleEventSink* event_sink_ = nullptr; + mutable SemaphoreHandle_t mutex_ = nullptr; + mutable StaticSemaphore_t mutex_control_{}; + AlarmSchedule schedule_; + std::atomic set_tone_index_{-1}; + std::atomic wake_tone_index_{-1}; + std::atomic running_{false}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array< + StackType_t, + task_stack_budget::kAlarmServiceBytes> task_stack_{}; +}; + +} // namespace borla diff --git a/main/schedule/alarm_store.cc b/main/schedule/alarm_store.cc new file mode 100644 index 0000000..9dcab65 --- /dev/null +++ b/main/schedule/alarm_store.cc @@ -0,0 +1,157 @@ +#include "schedule/alarm_store.h" + +#include "core/psram_object.h" +#include "schedule/alarm_schedule.h" + +#include +#include + +#include +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "AlarmStore2"; +constexpr const char* kNamespace = "alarm_v2"; +constexpr const char* kSnapshotKey = "snapshot"; +constexpr uint32_t kMagic = 0x324D5241; +constexpr uint16_t kVersion = 1; + +struct PersistedAlarmSnapshot { + uint32_t magic = kMagic; + uint16_t version = kVersion; + uint16_t count = 0; + uint8_t first_day_consumed = 0; + int8_t set_tone_index = -1; + int8_t wake_tone_index = -1; + uint8_t reserved = 0; + AlarmEntry entries[kMaximumAlarmCount]{}; + uint32_t checksum = 0; +}; + +uint32_t Checksum( + const void* data, + size_t size) +{ + const auto* bytes = static_cast(data); + uint32_t value = 2166136261U; + for (size_t i = 0; i < size; ++i) { + value ^= bytes[i]; + value *= 16777619U; + } + return value; +} + +bool ToneIndexValid(int8_t index) +{ + return index >= -1 && index <= 15; +} + +} // namespace + +bool NvsAlarmStore::Load(AlarmStoreSnapshot* snapshot) const +{ + if (snapshot == nullptr) { + return false; + } + *snapshot = {}; + snapshot->set_tone_index = -1; + snapshot->wake_tone_index = -1; + + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNamespace, NVS_READONLY, &handle); + if (result == ESP_ERR_NVS_NOT_FOUND) { + return true; + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "open failed: %s", esp_err_to_name(result)); + return false; + } + auto stored = MakePsramObject(); + if (!stored) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + nvs_close(handle); + return false; + } + size_t size = sizeof(*stored); + result = nvs_get_blob( + handle, kSnapshotKey, stored.get(), &size); + nvs_close(handle); + if (result == ESP_ERR_NVS_NOT_FOUND) { + return true; + } + const uint32_t expected = Checksum( + stored.get(), offsetof(PersistedAlarmSnapshot, checksum)); + if (result != ESP_OK || size != sizeof(*stored) || + stored->magic != kMagic || + stored->version != kVersion || + stored->count > kMaximumAlarmCount || + stored->checksum != expected || + !ToneIndexValid(stored->set_tone_index) || + !ToneIndexValid(stored->wake_tone_index)) { + ESP_LOGE(kTag, "invalid persisted alarm snapshot"); + return false; + } + snapshot->alarms.count = stored->count; + for (size_t i = 0; i < stored->count; ++i) { + if (!AlarmSchedule::Validate(stored->entries[i])) { + ESP_LOGE(kTag, "invalid persisted alarm index=%u", + static_cast(i)); + return false; + } + snapshot->alarms.entries[i] = stored->entries[i]; + } + snapshot->first_day_consumed = + stored->first_day_consumed != 0; + snapshot->set_tone_index = stored->set_tone_index; + snapshot->wake_tone_index = stored->wake_tone_index; + return true; +} + +bool NvsAlarmStore::Save(const AlarmStoreSnapshot& snapshot) +{ + if (snapshot.alarms.count > kMaximumAlarmCount || + !ToneIndexValid(snapshot.set_tone_index) || + !ToneIndexValid(snapshot.wake_tone_index)) { + return false; + } + auto stored = MakePsramObject(); + if (!stored) { + ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); + return false; + } + stored->count = static_cast(snapshot.alarms.count); + stored->first_day_consumed = + snapshot.first_day_consumed ? 1 : 0; + stored->set_tone_index = snapshot.set_tone_index; + stored->wake_tone_index = snapshot.wake_tone_index; + for (size_t i = 0; i < snapshot.alarms.count; ++i) { + stored->entries[i] = snapshot.alarms.entries[i]; + } + stored->checksum = Checksum( + stored.get(), offsetof(PersistedAlarmSnapshot, checksum)); + + nvs_handle_t handle = 0; + esp_err_t result = + nvs_open(kNamespace, NVS_READWRITE, &handle); + if (result == ESP_OK) { + result = nvs_set_blob( + handle, kSnapshotKey, stored.get(), sizeof(*stored)); + } + if (result == ESP_OK) { + result = nvs_commit(handle); + } + if (handle != 0) { + nvs_close(handle); + } + if (result != ESP_OK) { + ESP_LOGE(kTag, "save failed: %s", esp_err_to_name(result)); + return false; + } + return true; +} + +} // namespace borla diff --git a/main/schedule/alarm_store.h b/main/schedule/alarm_store.h new file mode 100644 index 0000000..f1f9d31 --- /dev/null +++ b/main/schedule/alarm_store.h @@ -0,0 +1,29 @@ +#pragma once + +#include "schedule/schedule_types.h" + +#include + +namespace borla { + +struct AlarmStoreSnapshot { + AlarmList alarms{}; + bool first_day_consumed = false; + int8_t set_tone_index = -1; + int8_t wake_tone_index = -1; +}; + +class IAlarmStore { +public: + virtual ~IAlarmStore() = default; + virtual bool Load(AlarmStoreSnapshot* snapshot) const = 0; + virtual bool Save(const AlarmStoreSnapshot& snapshot) = 0; +}; + +class NvsAlarmStore final : public IAlarmStore { +public: + bool Load(AlarmStoreSnapshot* snapshot) const override; + bool Save(const AlarmStoreSnapshot& snapshot) override; +}; + +} // namespace borla diff --git a/main/schedule/alert_ringer.cc b/main/schedule/alert_ringer.cc new file mode 100644 index 0000000..fff036a --- /dev/null +++ b/main/schedule/alert_ringer.cc @@ -0,0 +1,117 @@ +#include "schedule/alert_ringer.h" + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "AlertRinger2"; +constexpr uint32_t kMaximumRingMs = 60000; +constexpr uint32_t kRingPeriodMs = 2500; + +uint64_t NowMs() +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace + +void AlertRinger::Start(AlertKind kind) +{ + kind_.store(kind); + if (!EnsureWorker()) { + if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kAlertFinished)); + } + return; + } + if (running_.exchange(true)) { + return; + } + generation_.fetch_add(1); + xSemaphoreGive(request_); +} + +void AlertRinger::Stop() +{ + running_.store(false); + audio_.CancelPlayback(0); +} + +bool AlertRinger::EnsureWorker() +{ + if (task_ != nullptr) { + return true; + } + if (request_ == nullptr) { + request_ = xSemaphoreCreateBinaryStatic(&request_storage_); + if (request_ == nullptr) { + ESP_LOGE(kTag, "alert request semaphore creation failed"); + return false; + } + } + task_ = xTaskCreateStatic( + &AlertRinger::TaskEntry, + "alert_ringer2", + task_stack_.size(), + this, + 4, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + ESP_LOGE(kTag, "alert ringer worker creation failed"); + return false; + } + return true; +} + +void AlertRinger::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +[[noreturn]] void AlertRinger::Run() +{ + for (;;) { + if (xSemaphoreTake(request_, portMAX_DELAY) != pdTRUE) { + continue; + } + RunOneAlert(generation_.load()); + } +} + +void AlertRinger::RunOneAlert(uint32_t generation) +{ + const uint64_t deadline = NowMs() + kMaximumRingMs; + while (running_.load() && + generation_.load() == generation && + NowMs() < deadline) { + audio_.PlayLocalPrompt( + LocalPrompt::kAlarmWake, + PlaybackPriority::kAlarm, + alarms_.wake_tone_index()); + for (uint32_t waited = 0; + running_.load() && + generation_.load() == generation && + waited < kRingPeriodMs; + waited += 50) { + vTaskDelay(pdMS_TO_TICKS(50)); + } + } + if (generation_.load() != generation) { + // A newer Start() already owns the ringing state. Its pending request + // token drives the next cycle, so this one must not finish it. + return; + } + if (running_.exchange(false)) { + ESP_LOGI(kTag, "alert ringing timed out"); + } + if (publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kAlertFinished)); + } +} + +} // namespace borla diff --git a/main/schedule/alert_ringer.h b/main/schedule/alert_ringer.h new file mode 100644 index 0000000..56a7e3e --- /dev/null +++ b/main/schedule/alert_ringer.h @@ -0,0 +1,57 @@ +#pragma once + +#include "ports/alert_ringer.h" +#include "ports/audio_engine.h" +#include "ports/event_publisher.h" +#include "schedule/alarm_service.h" + +#include +#include +#include + +#include +#include +#include + +namespace borla { + +class AlertRinger final : public IAlertRinger { +public: + AlertRinger( + IAudioEngine& audio, + AlarmService& alarms) + : audio_(audio), alarms_(alarms) + { + } + + void SetEventPublisher(IEventPublisher& publisher) + { + publisher_ = &publisher; + } + void Start(AlertKind kind) override; + void Stop() override; + +private: + static constexpr uint32_t kTaskStackDepth = 3072; + static void TaskEntry(void* context); + // The worker is created once and then parks on request_. A static task + // control block and stack must not be recycled while the previous task is + // still being torn down, so this worker is never deleted. + bool EnsureWorker(); + [[noreturn]] void Run(); + void RunOneAlert(uint32_t generation); + + IAudioEngine& audio_; + AlarmService& alarms_; + IEventPublisher* publisher_ = nullptr; + std::atomic running_{false}; + std::atomic generation_{0}; + std::atomic kind_{AlertKind::kReminder}; + SemaphoreHandle_t request_ = nullptr; + StaticSemaphore_t request_storage_{}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array task_stack_{}; +}; + +} // namespace borla diff --git a/main/schedule/reminder_schedule.cc b/main/schedule/reminder_schedule.cc new file mode 100644 index 0000000..93d9b8e --- /dev/null +++ b/main/schedule/reminder_schedule.cc @@ -0,0 +1,62 @@ +#include "schedule/reminder_schedule.h" + +#include + +namespace borla { + +bool ReminderSchedule::Add(uint64_t deadline_ms) +{ + if (deadline_ms == 0 || count_ >= deadlines_.size()) { + return false; + } + const auto begin = deadlines_.begin(); + const auto position = std::lower_bound( + begin, begin + count_, deadline_ms); + std::move_backward( + position, begin + count_, begin + count_ + 1); + *position = deadline_ms; + count_++; + return true; +} + +void ReminderSchedule::CancelAll() +{ + count_ = 0; + deadlines_.fill(0); +} + +bool ReminderSchedule::CancelNext() +{ + if (count_ == 0) { + return false; + } + std::move( + deadlines_.begin() + 1, + deadlines_.begin() + count_, + deadlines_.begin()); + deadlines_[--count_] = 0; + return true; +} + +size_t ReminderSchedule::PopDue(uint64_t now_ms) +{ + size_t due = 0; + while (due < count_ && deadlines_[due] <= now_ms) { + due++; + } + if (due == 0) { + return 0; + } + std::move( + deadlines_.begin() + due, + deadlines_.begin() + count_, + deadlines_.begin()); + count_ -= due; + std::fill( + deadlines_.begin() + count_, + deadlines_.end(), + 0); + return due; +} + +} // namespace borla diff --git a/main/schedule/reminder_schedule.h b/main/schedule/reminder_schedule.h new file mode 100644 index 0000000..a964604 --- /dev/null +++ b/main/schedule/reminder_schedule.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +class ReminderSchedule final { +public: + static constexpr size_t kCapacity = 16; + + bool Add(uint64_t deadline_ms); + void CancelAll(); + bool CancelNext(); + size_t PopDue(uint64_t now_ms); + size_t count() const { return count_; } + uint64_t next_deadline_ms() const + { + return count_ == 0 ? 0 : deadlines_[0]; + } + +private: + size_t count_ = 0; + std::array deadlines_{}; +}; + +} // namespace borla diff --git a/main/schedule/reminder_service.cc b/main/schedule/reminder_service.cc new file mode 100644 index 0000000..81d7523 --- /dev/null +++ b/main/schedule/reminder_service.cc @@ -0,0 +1,139 @@ +#include "schedule/reminder_service.h" + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "ReminderService2"; +constexpr uint32_t kMaximumDurationSeconds = 7U * 24U * 60U * 60U; + +class Lock final { +public: + explicit Lock(SemaphoreHandle_t mutex) : mutex_(mutex) + { + xSemaphoreTake(mutex_, portMAX_DELAY); + } + ~Lock() { xSemaphoreGive(mutex_); } + +private: + SemaphoreHandle_t mutex_; +}; + +} // namespace + +bool ReminderService::Initialize(IEventPublisher& publisher) +{ + if (running_.load()) { + return true; + } + publisher_ = &publisher; + mutex_ = xSemaphoreCreateMutexStatic(&mutex_control_); + if (mutex_ == nullptr) { + return false; + } + running_.store(true); + task_ = xTaskCreateStatic( + &ReminderService::TaskEntry, + "reminder2", + task_stack_.size(), + this, + 4, + task_stack_.data(), + &task_control_); + if (task_ == nullptr) { + running_.store(false); + return false; + } + return true; +} + +void ReminderService::Stop() +{ + running_.store(false); +} + +bool ReminderService::Add(uint32_t duration_seconds) +{ + if (duration_seconds == 0 || + duration_seconds > kMaximumDurationSeconds || + mutex_ == nullptr) { + return false; + } + Lock lock(mutex_); + return schedule_.Add( + NowMs() + + static_cast(duration_seconds) * 1000); +} + +void ReminderService::Cancel(TimerCancelScope scope) +{ + if (mutex_ == nullptr) { + return; + } + Lock lock(mutex_); + if (scope == TimerCancelScope::kAll) { + schedule_.CancelAll(); + } else { + schedule_.CancelNext(); + } +} + +size_t ReminderService::count() const +{ + if (mutex_ == nullptr) { + return 0; + } + Lock lock(mutex_); + return schedule_.count(); +} + +uint64_t ReminderService::NextWakeupDelayUs() const +{ + if (mutex_ == nullptr) { + return 0; + } + Lock lock(mutex_); + const uint64_t deadline = schedule_.next_deadline_ms(); + const uint64_t now = NowMs(); + if (deadline == 0) { + return 0; + } + const uint64_t delay_ms = deadline > now ? deadline - now : 1; + return delay_ms * 1000ULL; +} + +void ReminderService::TaskEntry(void* context) +{ + static_cast(context)->Run(); +} + +void ReminderService::Run() +{ + while (running_.load()) { + size_t due = 0; + { + Lock lock(mutex_); + due = schedule_.PopDue(NowMs()); + } + if (due > 0 && publisher_ != nullptr) { + ESP_LOGI(kTag, "%u reminder(s) due", + static_cast(due)); + publisher_->Publish(AppEvent::Make( + AppEventType::kReminderDue, + 0, + static_cast(due))); + } + vTaskDelay(pdMS_TO_TICKS(100)); + } + task_ = nullptr; + vTaskDelete(nullptr); +} + +uint64_t ReminderService::NowMs() +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace borla diff --git a/main/schedule/reminder_service.h b/main/schedule/reminder_service.h new file mode 100644 index 0000000..b0776ed --- /dev/null +++ b/main/schedule/reminder_service.h @@ -0,0 +1,42 @@ +#pragma once + +#include "ports/event_publisher.h" +#include "schedule/reminder_schedule.h" +#include "schedule/schedule_types.h" + +#include +#include +#include + +#include +#include +#include + +namespace borla { + +class ReminderService final { +public: + bool Initialize(IEventPublisher& publisher); + void Stop(); + bool Add(uint32_t duration_seconds); + void Cancel(TimerCancelScope scope); + size_t count() const; + uint64_t NextWakeupDelayUs() const; + +private: + static constexpr uint32_t kTaskStackDepth = 2048; + static void TaskEntry(void* context); + void Run(); + static uint64_t NowMs(); + + IEventPublisher* publisher_ = nullptr; + mutable SemaphoreHandle_t mutex_ = nullptr; + mutable StaticSemaphore_t mutex_control_{}; + ReminderSchedule schedule_; + std::atomic running_{false}; + TaskHandle_t task_ = nullptr; + StaticTask_t task_control_{}; + std::array task_stack_{}; +}; + +} // namespace borla diff --git a/main/schedule/schedule_coordinator.cc b/main/schedule/schedule_coordinator.cc new file mode 100644 index 0000000..dc9b624 --- /dev/null +++ b/main/schedule/schedule_coordinator.cc @@ -0,0 +1,37 @@ +#include "schedule/schedule_coordinator.h" + +namespace borla { + +bool ScheduleCoordinator::AddReminder(uint32_t duration_seconds) +{ + return reminders_.Add(duration_seconds); +} + +void ScheduleCoordinator::CancelReminder(TimerCancelScope scope) +{ + reminders_.Cancel(scope); +} + +bool ScheduleCoordinator::SetAlarm(const AlarmEntry& alarm) +{ + return alarms_.Set(alarm); +} + +void ScheduleCoordinator::DeleteAlarm(int32_t id) +{ + alarms_.Delete(id); +} + +bool ScheduleCoordinator::SyncAlarms(const AlarmList& alarms) +{ + return alarms_.Sync(alarms); +} + +void ScheduleCoordinator::SetAlarmToneIndices( + int8_t set_tone_index, + int8_t wake_tone_index) +{ + alarms_.SetToneIndices(set_tone_index, wake_tone_index); +} + +} // namespace borla diff --git a/main/schedule/schedule_coordinator.h b/main/schedule/schedule_coordinator.h new file mode 100644 index 0000000..fee03fc --- /dev/null +++ b/main/schedule/schedule_coordinator.h @@ -0,0 +1,32 @@ +#pragma once + +#include "schedule/alarm_service.h" +#include "schedule/reminder_service.h" +#include "schedule/schedule_types.h" + +namespace borla { + +class ScheduleCoordinator final : public IScheduleCommandHandler { +public: + ScheduleCoordinator( + ReminderService& reminders, + AlarmService& alarms) + : reminders_(reminders), alarms_(alarms) + { + } + + bool AddReminder(uint32_t duration_seconds) override; + void CancelReminder(TimerCancelScope scope) override; + bool SetAlarm(const AlarmEntry& alarm) override; + void DeleteAlarm(int32_t id) override; + bool SyncAlarms(const AlarmList& alarms) override; + void SetAlarmToneIndices( + int8_t set_tone_index, + int8_t wake_tone_index) override; + +private: + ReminderService& reminders_; + AlarmService& alarms_; +}; + +} // namespace borla diff --git a/main/schedule/schedule_types.h b/main/schedule/schedule_types.h new file mode 100644 index 0000000..f4de4bc --- /dev/null +++ b/main/schedule/schedule_types.h @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include +#include + +namespace borla { + +inline constexpr size_t kMaximumAlarmCount = 16; +inline constexpr size_t kAlarmLabelCapacity = 48; +inline constexpr int32_t kBuiltInFirstDayAlarmId = -203000; + +struct AlarmEntry { + int32_t id = 0; + uint8_t hour = 0; + uint8_t minute = 0; + uint8_t repeat_mask = 0; + bool enabled = true; + int64_t fire_epoch = 0; + std::array label{}; +}; + +static_assert( + std::is_trivially_copyable::value, + "AlarmEntry is persisted and must stay trivially copyable"); + +struct AlarmList { + size_t count = 0; + std::array entries{}; +}; + +struct CalendarMinute { + int year = 0; + int year_day = 0; + int week_day = 0; + int hour = 0; + int minute = 0; +}; + +struct AlarmFireBatch { + size_t count = 0; + std::array ids{}; + bool play_audio = false; + bool built_in_first_day = false; +}; + +enum class TimerCancelScope : uint8_t { + kAll, + kNext, +}; + +class IScheduleCommandHandler { +public: + virtual ~IScheduleCommandHandler() = default; + virtual bool AddReminder(uint32_t duration_seconds) = 0; + virtual void CancelReminder(TimerCancelScope scope) = 0; + virtual bool SetAlarm(const AlarmEntry& alarm) = 0; + virtual void DeleteAlarm(int32_t id) = 0; + virtual bool SyncAlarms(const AlarmList& alarms) = 0; + virtual void SetAlarmToneIndices( + int8_t set_tone_index, + int8_t wake_tone_index) = 0; +}; + +class IScheduleEventSink { +public: + virtual ~IScheduleEventSink() = default; + virtual bool SendAlarmFired( + int32_t alarm_id, + int64_t fired_at_epoch) = 0; +}; + +} // namespace borla diff --git a/main/sensor/battery_estimator.cc b/main/sensor/battery_estimator.cc new file mode 100644 index 0000000..397cf77 --- /dev/null +++ b/main/sensor/battery_estimator.cc @@ -0,0 +1,130 @@ +#include "sensor/battery_estimator.h" + +#include +#include + +namespace borla { +namespace { + +struct CurvePoint { + uint16_t millivolts; + uint8_t percent; +}; + +constexpr std::array kDischargeCurve{{ + {4090, 100}, + {4040, 95}, + {3990, 90}, + {3920, 80}, + {3850, 65}, + {3770, 50}, + {3670, 35}, + {3570, 20}, + {3470, 10}, + {3370, 5}, + {3270, 2}, + {3000, 0}, +}}; + +constexpr uint16_t kMinimumPlausibleMillivolts = 2500; +constexpr uint16_t kMaximumPlausibleMillivolts = 4500; + +} // namespace + +void BatteryEstimator::Reset() +{ + initialized_ = false; + charging_ = false; + last_millivolts_ = 0; + smoothed_millivolts_ = 0; + rising_samples_ = 0; + falling_samples_ = 0; +} + +bool BatteryEstimator::IsPlausibleVoltage(uint16_t millivolts) +{ + return millivolts >= kMinimumPlausibleMillivolts && + millivolts <= kMaximumPlausibleMillivolts; +} + +void BatteryEstimator::Update(uint16_t battery_millivolts) +{ + if (!initialized_) { + initialized_ = true; + last_millivolts_ = battery_millivolts; + smoothed_millivolts_ = battery_millivolts; + // Voltage alone cannot prove USB presence. Only use the high CV + // region as a conservative boot-time hint. + charging_ = battery_millivolts >= 4150; + return; + } + + const int delta = + static_cast(battery_millivolts) - + static_cast(last_millivolts_); + last_millivolts_ = battery_millivolts; + if (delta >= 12) { + rising_samples_ = std::min(rising_samples_ + 1, 3); + falling_samples_ = 0; + } else if (delta <= -20) { + falling_samples_ = + std::min(falling_samples_ + 1, 3); + rising_samples_ = 0; + } else { + if (rising_samples_ > 0) { + rising_samples_--; + } + if (falling_samples_ > 0) { + falling_samples_--; + } + } + + if (rising_samples_ >= 2 || battery_millivolts >= 4150) { + charging_ = true; + } else if (falling_samples_ >= 2 || + battery_millivolts < 3950) { + charging_ = false; + } + + const uint32_t incoming_weight = charging_ ? 3U : 1U; + const uint32_t previous_weight = charging_ ? 7U : 4U; + smoothed_millivolts_ = static_cast( + (battery_millivolts * incoming_weight + + smoothed_millivolts_ * previous_weight) / + (incoming_weight + previous_weight)); +} + +uint8_t BatteryEstimator::percent() const +{ + return initialized_ + ? VoltageToPercent(smoothed_millivolts_) + : 0; +} + +uint8_t BatteryEstimator::VoltageToPercent(uint16_t millivolts) +{ + if (millivolts >= kDischargeCurve.front().millivolts) { + return 100; + } + if (millivolts <= kDischargeCurve.back().millivolts) { + return 0; + } + for (size_t i = 0; i + 1 < kDischargeCurve.size(); ++i) { + const CurvePoint high = kDischargeCurve[i]; + const CurvePoint low = kDischargeCurve[i + 1]; + if (millivolts <= high.millivolts && + millivolts > low.millivolts) { + const uint32_t voltage_span = + high.millivolts - low.millivolts; + const uint32_t percent_span = + high.percent - low.percent; + return static_cast( + low.percent + + (millivolts - low.millivolts) * + percent_span / voltage_span); + } + } + return 0; +} + +} // namespace borla diff --git a/main/sensor/battery_estimator.h b/main/sensor/battery_estimator.h new file mode 100644 index 0000000..e8687cd --- /dev/null +++ b/main/sensor/battery_estimator.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +namespace borla { + +class BatteryEstimator final { +public: + void Reset(); + void Update(uint16_t battery_millivolts); + + uint16_t smoothed_millivolts() const + { + return smoothed_millivolts_; + } + uint8_t percent() const; + bool charging() const { return charging_; } + bool initialized() const { return initialized_; } + + static bool IsPlausibleVoltage(uint16_t millivolts); + static uint8_t VoltageToPercent(uint16_t millivolts); + +private: + bool initialized_ = false; + bool charging_ = false; + uint16_t last_millivolts_ = 0; + uint16_t smoothed_millivolts_ = 0; + uint8_t rising_samples_ = 0; + uint8_t falling_samples_ = 0; +}; + +} // namespace borla diff --git a/main/sensor/imu_processor.cc b/main/sensor/imu_processor.cc new file mode 100644 index 0000000..4530fc8 --- /dev/null +++ b/main/sensor/imu_processor.cc @@ -0,0 +1,248 @@ +#include "sensor/imu_processor.h" + +#include +#include + +namespace borla { +namespace { + +float Magnitude(const ImuSample& sample) +{ + return std::sqrt( + sample.ax * sample.ax + + sample.ay * sample.ay + + sample.az * sample.az); +} + +} // namespace + +ImuProcessor::ImuProcessor() +{ + Reset(); +} + +void ImuProcessor::Reset() +{ + filter_initialized_ = false; + filtered_ = {}; + still_ = false; + still_frame_count_ = 0; + pending_batch_ = {}; + next_sequence_ = 0; + next_gravity_sequence_ = 0; + freefall_candidate_ = false; + freefall_confirmed_ = false; + freefall_started_ms_ = 0; + last_freefall_active_ms_ = 0; + landing_window_ = false; + landing_deadline_ms_ = 0; + landing_duration_ms_ = 0; + landing_peak_g_ = 0.0F; + last_gravity_event_ms_.fill(0); +} + +ImuProcessorOutput ImuProcessor::Process( + const ImuSample& raw, + uint64_t now_ms) +{ + ImuProcessorOutput output{}; + const ImuSample current = Filter(raw); + const float deviation_g = std::fabs(Magnitude(current) - 1.0F); + + if (still_) { + if (deviation_g >= kResumeDeviationG) { + still_ = false; + still_frame_count_ = 0; + } + } else if (deviation_g < kStillDeviationG) { + still_frame_count_++; + if (still_frame_count_ >= kStillFrameCount) { + still_ = true; + still_frame_count_ = 0; + FlushPartialBatch(&output); + } + } else { + still_frame_count_ = 0; + } + + if (!still_) { + UpdateBatch(current, now_ms, &output); + } + UpdateGravity(raw, now_ms, &output); + return output; +} + +ImuSample ImuProcessor::Filter(const ImuSample& raw) +{ + if (!filter_initialized_) { + filtered_ = raw; + filter_initialized_ = true; + return filtered_; + } + const float incoming = 1.0F - kFilterAlpha; + filtered_.ax = kFilterAlpha * filtered_.ax + incoming * raw.ax; + filtered_.ay = kFilterAlpha * filtered_.ay + incoming * raw.ay; + filtered_.az = kFilterAlpha * filtered_.az + incoming * raw.az; + filtered_.gx = kFilterAlpha * filtered_.gx + incoming * raw.gx; + filtered_.gy = kFilterAlpha * filtered_.gy + incoming * raw.gy; + filtered_.gz = kFilterAlpha * filtered_.gz + incoming * raw.gz; + return filtered_; +} + +void ImuProcessor::UpdateBatch( + const ImuSample& filtered, + uint64_t now_ms, + ImuProcessorOutput* output) +{ + if (pending_batch_.count == 0) { + pending_batch_.sequence = next_sequence_++; + pending_batch_.timestamp_ms_base = now_ms; + pending_batch_.sample_rate_hz = 50; + } + pending_batch_.samples[pending_batch_.count++] = filtered; + if (pending_batch_.count == pending_batch_.samples.size()) { + output->has_batch = true; + output->batch = pending_batch_; + pending_batch_ = {}; + } +} + +void ImuProcessor::FlushPartialBatch(ImuProcessorOutput* output) +{ + if (pending_batch_.count == 0 || output->has_batch) { + return; + } + output->has_batch = true; + output->batch = pending_batch_; + pending_batch_ = {}; +} + +void ImuProcessor::UpdateGravity( + const ImuSample& raw, + uint64_t now_ms, + ImuProcessorOutput* output) +{ + const float magnitude_g = Magnitude(raw); + + if (magnitude_g < kFreefallThresholdG) { + if (!freefall_candidate_) { + freefall_candidate_ = true; + freefall_started_ms_ = now_ms; + } + const uint64_t duration = now_ms - freefall_started_ms_; + if (!freefall_confirmed_ && duration >= kFreefallConfirmMs) { + freefall_confirmed_ = true; + last_freefall_active_ms_ = now_ms; + TryEmitGravity( + GravityAction::kFreefall, + now_ms, + static_cast(duration), + magnitude_g, + output); + } else if (freefall_confirmed_ && + now_ms - last_freefall_active_ms_ >= + kFreefallActivePeriodMs) { + last_freefall_active_ms_ = now_ms; + TryEmitGravity( + GravityAction::kFreefallActive, + now_ms, + static_cast(duration), + magnitude_g, + output); + } + return; + } + + if (freefall_candidate_) { + const uint64_t duration = now_ms - freefall_started_ms_; + if (freefall_confirmed_) { + landing_window_ = true; + landing_deadline_ms_ = now_ms + kLandingWindowMs; + landing_duration_ms_ = static_cast(duration); + landing_peak_g_ = magnitude_g; + } + freefall_candidate_ = false; + freefall_confirmed_ = false; + } + + if (landing_window_) { + landing_peak_g_ = std::max(landing_peak_g_, magnitude_g); + if (landing_peak_g_ >= kSevereThresholdG) { + landing_window_ = false; + TryEmitGravity( + GravityAction::kSevereImpact, + now_ms, + landing_duration_ms_, + landing_peak_g_, + output); + return; + } + if (landing_peak_g_ >= kDroppedThresholdG) { + landing_window_ = false; + TryEmitGravity( + GravityAction::kDropped, + now_ms, + landing_duration_ms_, + landing_peak_g_, + output); + return; + } + if (now_ms >= landing_deadline_ms_) { + landing_window_ = false; + if (landing_peak_g_ >= kCaughtThresholdG) { + TryEmitGravity( + GravityAction::kCaught, + now_ms, + landing_duration_ms_, + landing_peak_g_, + output); + } + } + return; + } + + if (magnitude_g >= kSevereThresholdG) { + TryEmitGravity( + GravityAction::kSevereImpact, + now_ms, + 0, + magnitude_g, + output); + } else if (magnitude_g >= kDroppedThresholdG) { + TryEmitGravity( + GravityAction::kImpact, + now_ms, + 0, + magnitude_g, + output); + } +} + +void ImuProcessor::TryEmitGravity( + GravityAction action, + uint64_t now_ms, + uint32_t duration_ms, + float peak_g, + ImuProcessorOutput* output) +{ + if (output->has_gravity_event) { + return; + } + const size_t index = static_cast(action); + const uint64_t previous = last_gravity_event_ms_[index]; + if (previous != 0 && now_ms - previous < kActionCooldownMs) { + return; + } + last_gravity_event_ms_[index] = now_ms; + output->has_gravity_event = true; + output->gravity_event = { + .action = action, + .sequence = next_gravity_sequence_++, + .timestamp_ms = now_ms, + .duration_ms = duration_ms, + .magnitude_g = peak_g, + .peak_g = peak_g, + }; +} + +} // namespace borla diff --git a/main/sensor/imu_processor.h b/main/sensor/imu_processor.h new file mode 100644 index 0000000..63f7e79 --- /dev/null +++ b/main/sensor/imu_processor.h @@ -0,0 +1,81 @@ +#pragma once + +#include "sensor/sensor_types.h" + +#include +#include + +namespace borla { + +struct ImuProcessorOutput { + bool has_batch = false; + ImuBatch batch{}; + bool has_gravity_event = false; + GravityEvent gravity_event{}; +}; + +class ImuProcessor final { +public: + ImuProcessor(); + + void Reset(); + ImuProcessorOutput Process( + const ImuSample& raw, + uint64_t now_ms); + + bool still() const { return still_; } + +private: + static constexpr float kFilterAlpha = 0.75F; + static constexpr float kStillDeviationG = 0.010F; + static constexpr float kResumeDeviationG = 0.050F; + static constexpr uint16_t kStillFrameCount = 50; + static constexpr float kFreefallThresholdG = 0.30F; + static constexpr uint32_t kFreefallConfirmMs = 60; + static constexpr uint32_t kFreefallActivePeriodMs = 500; + static constexpr uint32_t kLandingWindowMs = 800; + static constexpr float kCaughtThresholdG = 1.40F; + static constexpr float kDroppedThresholdG = 4.50F; + static constexpr float kSevereThresholdG = 7.00F; + static constexpr uint32_t kActionCooldownMs = 1000; + + ImuSample Filter(const ImuSample& raw); + void UpdateBatch( + const ImuSample& filtered, + uint64_t now_ms, + ImuProcessorOutput* output); + void FlushPartialBatch(ImuProcessorOutput* output); + void UpdateGravity( + const ImuSample& raw, + uint64_t now_ms, + ImuProcessorOutput* output); + void TryEmitGravity( + GravityAction action, + uint64_t now_ms, + uint32_t duration_ms, + float peak_g, + ImuProcessorOutput* output); + + bool filter_initialized_ = false; + ImuSample filtered_{}; + bool still_ = false; + uint16_t still_frame_count_ = 0; + ImuBatch pending_batch_{}; + uint32_t next_sequence_ = 0; + uint32_t next_gravity_sequence_ = 0; + + bool freefall_candidate_ = false; + bool freefall_confirmed_ = false; + uint64_t freefall_started_ms_ = 0; + uint64_t last_freefall_active_ms_ = 0; + bool landing_window_ = false; + uint64_t landing_deadline_ms_ = 0; + uint32_t landing_duration_ms_ = 0; + float landing_peak_g_ = 0.0F; + std::array< + uint64_t, + static_cast(GravityAction::kCount)> + last_gravity_event_ms_{}; +}; + +} // namespace borla diff --git a/main/sensor/sensor_message_codec.cc b/main/sensor/sensor_message_codec.cc new file mode 100644 index 0000000..e6fa39b --- /dev/null +++ b/main/sensor/sensor_message_codec.cc @@ -0,0 +1,131 @@ +#include "sensor/sensor_message_codec.h" + +#include + +namespace borla { +namespace { + +bool Finish(int written, size_t capacity, size_t* output_size) +{ + if (written < 0 || + static_cast(written) >= capacity || + output_size == nullptr) { + return false; + } + *output_size = static_cast(written); + return true; +} + +} // namespace + +bool SensorMessageCodec::BuildTouch( + const TouchEvent& event, + char* output, + size_t capacity, + size_t* output_size) +{ + if (output == nullptr || capacity == 0 || output_size == nullptr) { + return false; + } + const int written = + event.action == TouchAction::kDown + ? std::snprintf( + output, + capacity, + "{\"type\":\"sensor\",\"event\":\"touch\"," + "\"touch_zone\":\"%s\",\"touch_action\":\"down\"," + "\"timestamp\":%llu}", + ToString(event.zone), + static_cast( + event.timestamp_ms)) + : std::snprintf( + output, + capacity, + "{\"type\":\"sensor\",\"event\":\"touch\"," + "\"touch_zone\":\"%s\",\"touch_action\":\"up\"," + "\"timestamp\":%llu,\"duration_ms\":%lu}", + ToString(event.zone), + static_cast( + event.timestamp_ms), + static_cast( + event.duration_ms)); + return Finish(written, capacity, output_size); +} + +bool SensorMessageCodec::BuildImu( + const ImuBatch& batch, + char* output, + size_t capacity, + size_t* output_size) +{ + if (output == nullptr || capacity == 0 || output_size == nullptr || + batch.count == 0 || batch.count > batch.samples.size()) { + return false; + } + int written = std::snprintf( + output, + capacity, + "{\"type\":\"sensor\",\"event\":\"imu\"," + "\"seq\":%lu,\"ts_ms_base\":%llu,\"hz\":%u,\"samples\":[", + static_cast(batch.sequence), + static_cast(batch.timestamp_ms_base), + static_cast(batch.sample_rate_hz)); + if (written < 0 || static_cast(written) >= capacity) { + return false; + } + size_t used = static_cast(written); + for (size_t i = 0; i < batch.count; ++i) { + const ImuSample& sample = batch.samples[i]; + written = std::snprintf( + output + used, + capacity - used, + "%s[%.4f,%.4f,%.4f,%.3f,%.3f,%.3f]", + i == 0 ? "" : ",", + static_cast(sample.ax), + static_cast(sample.ay), + static_cast(sample.az), + static_cast(sample.gx), + static_cast(sample.gy), + static_cast(sample.gz)); + if (written < 0 || + static_cast(written) >= capacity - used) { + return false; + } + used += static_cast(written); + } + written = std::snprintf(output + used, capacity - used, "]}"); + if (written < 0 || + static_cast(written) >= capacity - used) { + return false; + } + used += static_cast(written); + *output_size = used; + return true; +} + +bool SensorMessageCodec::BuildGravity( + const GravityEvent& event, + char* output, + size_t capacity, + size_t* output_size) +{ + if (output == nullptr || capacity == 0 || output_size == nullptr) { + return false; + } + const int written = std::snprintf( + output, + capacity, + "{\"type\":\"sensor\",\"event\":\"gravity\"," + "\"seq\":%lu,\"timestamp\":%llu," + "\"gravity_zone\":\"body\",\"gravity_action\":\"%s\"," + "\"duration_ms\":%lu,\"magnitude\":%.3f,\"peak_g\":%.3f}", + static_cast(event.sequence), + static_cast(event.timestamp_ms), + ToString(event.action), + static_cast(event.duration_ms), + static_cast(event.magnitude_g), + static_cast(event.peak_g)); + return Finish(written, capacity, output_size); +} + +} // namespace borla diff --git a/main/sensor/sensor_message_codec.h b/main/sensor/sensor_message_codec.h new file mode 100644 index 0000000..2a8a507 --- /dev/null +++ b/main/sensor/sensor_message_codec.h @@ -0,0 +1,28 @@ +#pragma once + +#include "sensor/sensor_types.h" + +#include + +namespace borla { + +class SensorMessageCodec final { +public: + static bool BuildTouch( + const TouchEvent& event, + char* output, + size_t capacity, + size_t* output_size); + static bool BuildImu( + const ImuBatch& batch, + char* output, + size_t capacity, + size_t* output_size); + static bool BuildGravity( + const GravityEvent& event, + char* output, + size_t capacity, + size_t* output_size); +}; + +} // namespace borla diff --git a/main/sensor/sensor_service.cc b/main/sensor/sensor_service.cc new file mode 100644 index 0000000..b045a9e --- /dev/null +++ b/main/sensor/sensor_service.cc @@ -0,0 +1,351 @@ +#include "sensor/sensor_service.h" + +#include "sensor/sensor_message_codec.h" + +#include + +#include +#include + +namespace borla { +namespace { + +constexpr const char* kTag = "SensorService2"; +constexpr uint32_t kTouchWarmupMs = 500; +constexpr uint32_t kTouchCalibrationSamples = 10; +constexpr uint32_t kTouchCalibrationIntervalMs = 20; +constexpr uint32_t kTouchPollMs = 50; +constexpr uint32_t kImuPollMs = 20; +constexpr uint32_t kBatteryPollMs = 10000; + +uint64_t NowMs() +{ + return static_cast(esp_timer_get_time() / 1000); +} + +} // namespace + +SensorService::SensorService( + CapacitiveTouchInput& touch, + Bmi270Sensor& imu, + BatteryMonitor& battery, + ISensorMessageSink& sink) + : touch_(touch), + imu_(imu), + battery_(battery), + sink_(sink) +{ +} + +bool SensorService::Initialize() +{ + if (running_.load()) { + return true; + } + stopped_events_ = + xEventGroupCreateStatic(&stopped_events_control_); + if (stopped_events_ == nullptr) { + return false; + } + + touch_enabled_ = touch_.Initialize(); + imu_enabled_ = imu_.Initialize(); + battery_enabled_ = battery_.Initialize(); + running_.store(true); + + if (touch_enabled_) { + touch_task_ = xTaskCreateStaticPinnedToCore( + &SensorService::TouchTaskEntry, + "touch_sensor2", + touch_task_stack_.size(), + this, + kTaskPriority, + touch_task_stack_.data(), + &touch_task_control_, + 0); + touch_enabled_ = touch_task_ != nullptr; + } + if (imu_enabled_) { + imu_task_ = xTaskCreateStaticPinnedToCore( + &SensorService::ImuTaskEntry, + "imu_sensor2", + imu_task_stack_.size(), + this, + kTaskPriority + 1, + imu_task_stack_.data(), + &imu_task_control_, + 1); + imu_enabled_ = imu_task_ != nullptr; + } + if (battery_enabled_) { + battery_task_ = xTaskCreateStatic( + &SensorService::BatteryTaskEntry, + "battery_sensor2", + battery_task_stack_.size(), + this, + kTaskPriority, + battery_task_stack_.data(), + &battery_task_control_); + battery_enabled_ = battery_task_ != nullptr; + } + + const bool any_enabled = + touch_enabled_ || imu_enabled_ || battery_enabled_; + if (!any_enabled) { + running_.store(false); + ESP_LOGE(kTag, "no sensor adapter available"); + return false; + } + ESP_LOGI(kTag, "started touch=%d imu=%d battery=%d", + touch_enabled_, imu_enabled_, battery_enabled_); + return true; +} + +void SensorService::Stop() +{ + if (!running_.exchange(false) || stopped_events_ == nullptr) { + return; + } + EventBits_t expected = 0; + if (touch_enabled_) { + expected |= kTouchStoppedBit; + } + if (imu_enabled_) { + expected |= kImuStoppedBit; + } + if (battery_enabled_) { + expected |= kBatteryStoppedBit; + } + if (expected != 0) { + xEventGroupWaitBits( + stopped_events_, + expected, + pdFALSE, + pdTRUE, + pdMS_TO_TICKS(12000)); + } + ESP_LOGI(kTag, "stopped"); +} + +BatteryStatus SensorService::GetBatteryStatus() const +{ + portENTER_CRITICAL(&status_lock_); + const BatteryStatus result = battery_status_; + portEXIT_CRITICAL(&status_lock_); + return result; +} + +SensorDiagnostics SensorService::GetDiagnostics() const +{ + return { + .touch_events_sent = touch_events_sent_.load(), + .imu_batches_sent = imu_batches_sent_.load(), + .gravity_events_sent = gravity_events_sent_.load(), + .messages_dropped = messages_dropped_.load(), + .touch_read_errors = touch_read_errors_.load(), + .imu_read_errors = imu_read_errors_.load(), + .battery_read_errors = battery_read_errors_.load(), + }; +} + +void SensorService::TouchTaskEntry(void* context) +{ + static_cast(context)->RunTouch(); +} + +void SensorService::ImuTaskEntry(void* context) +{ + static_cast(context)->RunImu(); +} + +void SensorService::BatteryTaskEntry(void* context) +{ + static_cast(context)->RunBattery(); +} + +void SensorService::RunTouch() +{ + vTaskDelay(pdMS_TO_TICKS(kTouchWarmupMs)); + for (TouchChannel& channel : touch_channels_) { + channel.ResetCalibration(); + } + for (uint32_t sample_index = 0; + sample_index < kTouchCalibrationSamples && running_.load(); + ++sample_index) { + for (size_t channel = 0; + channel < touch_channels_.size(); + ++channel) { + uint32_t raw = 0; + if (touch_.Read(channel, &raw)) { + touch_channels_[channel].AddCalibrationSample(raw); + } else { + touch_read_errors_.fetch_add(1); + } + } + vTaskDelay(pdMS_TO_TICKS(kTouchCalibrationIntervalMs)); + } + for (size_t channel = 0; + channel < touch_channels_.size(); + ++channel) { + if (!touch_channels_[channel].FinishCalibration()) { + ESP_LOGW(kTag, "touch calibration failed channel=%u", + static_cast(channel)); + } else { + ESP_LOGI(kTag, "touch channel=%u baseline=%.0f threshold=%.0f", + static_cast(channel), + static_cast( + touch_channels_[channel].baseline()), + static_cast( + touch_channels_[channel].threshold())); + } + } + + TickType_t next_tick = xTaskGetTickCount(); + while (running_.load()) { + const uint64_t now_ms = NowMs(); + for (size_t channel = 0; + channel < touch_channels_.size(); + ++channel) { + uint32_t raw = 0; + if (!touch_.Read(channel, &raw)) { + touch_read_errors_.fetch_add(1); + continue; + } + TouchTransition transition{}; + if (touch_channels_[channel].Process( + raw, now_ms, &transition)) { + if (transition.action == TouchAction::kDown && + publisher_ != nullptr) { + publisher_->Publish(AppEvent::Make( + AppEventType::kUserActivityDetected, + 0, + static_cast(channel))); + } + SendTouch({ + .zone = static_cast(channel), + .action = transition.action, + .timestamp_ms = transition.timestamp_ms, + .duration_ms = transition.duration_ms, + }); + } + } + vTaskDelayUntil( + &next_tick, pdMS_TO_TICKS(kTouchPollMs)); + } + xEventGroupSetBits(stopped_events_, kTouchStoppedBit); + touch_task_ = nullptr; + vTaskDelete(nullptr); +} + +void SensorService::RunImu() +{ + TickType_t next_tick = xTaskGetTickCount(); + while (running_.load()) { + ImuSample sample{}; + if (imu_.Read(&sample)) { + const ImuProcessorOutput output = + imu_processor_.Process(sample, NowMs()); + if (output.has_gravity_event) { + SendGravity(output.gravity_event); + } + if (output.has_batch) { + SendImu(output.batch); + } + } else { + imu_read_errors_.fetch_add(1); + } + vTaskDelayUntil(&next_tick, pdMS_TO_TICKS(kImuPollMs)); + } + xEventGroupSetBits(stopped_events_, kImuStoppedBit); + imu_task_ = nullptr; + vTaskDelete(nullptr); +} + +void SensorService::RunBattery() +{ + while (running_.load()) { + BatteryStatus status{}; + if (battery_.Read(NowMs(), &status)) { + portENTER_CRITICAL(&status_lock_); + battery_status_ = status; + portEXIT_CRITICAL(&status_lock_); + // One line per actual change, not one per 10-second poll — the + // steady-state repeat was pure noise in the conversation log. + // Function-local statics are fine: there is one battery task. + static int last_logged_percent = -1; + static int last_logged_charging = -1; + if (static_cast(status.percent) != last_logged_percent || + static_cast(status.charging) != last_logged_charging) { + last_logged_percent = static_cast(status.percent); + last_logged_charging = static_cast(status.charging); + ESP_LOGI(kTag, "battery=%u%% voltage=%umV charging=%d", + status.percent, + status.millivolts, + status.charging); + } + } else { + battery_read_errors_.fetch_add(1); + portENTER_CRITICAL(&status_lock_); + battery_status_ = {}; + portEXIT_CRITICAL(&status_lock_); + } + for (uint32_t waited_ms = 0; + running_.load() && waited_ms < kBatteryPollMs; + waited_ms += 100) { + vTaskDelay(pdMS_TO_TICKS(100)); + } + } + xEventGroupSetBits(stopped_events_, kBatteryStoppedBit); + battery_task_ = nullptr; + vTaskDelete(nullptr); +} + +bool SensorService::SendTouch(const TouchEvent& event) +{ + std::array message{}; + size_t size = 0; + const bool sent = + SensorMessageCodec::BuildTouch( + event, message.data(), message.size(), &size) && + sink_.SendSensorMessage(message.data(), size); + if (sent) { + touch_events_sent_.fetch_add(1); + } else { + messages_dropped_.fetch_add(1); + } + return sent; +} + +bool SensorService::SendImu(const ImuBatch& batch) +{ + std::array message{}; + size_t size = 0; + const bool sent = + SensorMessageCodec::BuildImu( + batch, message.data(), message.size(), &size) && + sink_.SendSensorMessage(message.data(), size); + if (sent) { + imu_batches_sent_.fetch_add(1); + } else { + messages_dropped_.fetch_add(1); + } + return sent; +} + +bool SensorService::SendGravity(const GravityEvent& event) +{ + std::array message{}; + size_t size = 0; + const bool sent = + SensorMessageCodec::BuildGravity( + event, message.data(), message.size(), &size) && + sink_.SendSensorMessage(message.data(), size); + if (sent) { + gravity_events_sent_.fetch_add(1); + } else { + messages_dropped_.fetch_add(1); + } + return sent; +} + +} // namespace borla diff --git a/main/sensor/sensor_service.h b/main/sensor/sensor_service.h new file mode 100644 index 0000000..aaf6bcb --- /dev/null +++ b/main/sensor/sensor_service.h @@ -0,0 +1,109 @@ +#pragma once + +#include "platform/borla_s3/battery_monitor.h" +#include "platform/borla_s3/bmi270_sensor.h" +#include "platform/borla_s3/capacitive_touch_input.h" +#include "ports/battery_status_provider.h" +#include "ports/event_publisher.h" +#include "ports/sensor_message_sink.h" +#include "sensor/imu_processor.h" +#include "sensor/touch_channel.h" + +#include +#include +#include + +#include +#include +#include + +namespace borla { + +struct SensorDiagnostics { + uint32_t touch_events_sent = 0; + uint32_t imu_batches_sent = 0; + uint32_t gravity_events_sent = 0; + uint32_t messages_dropped = 0; + uint32_t touch_read_errors = 0; + uint32_t imu_read_errors = 0; + uint32_t battery_read_errors = 0; +}; + +class SensorService final : public IBatteryStatusProvider { +public: + SensorService( + CapacitiveTouchInput& touch, + Bmi270Sensor& imu, + BatteryMonitor& battery, + ISensorMessageSink& sink); + + bool Initialize(); + void SetEventPublisher(IEventPublisher* publisher) + { + publisher_ = publisher; + } + void Stop(); + + BatteryStatus GetBatteryStatus() const override; + SensorDiagnostics GetDiagnostics() const; + +private: + static constexpr uint32_t kTouchTaskStackDepth = 3072; + static constexpr uint32_t kImuTaskStackDepth = 4096; + static constexpr uint32_t kBatteryTaskStackDepth = 3072; + static constexpr UBaseType_t kTaskPriority = 4; + static constexpr EventBits_t kTouchStoppedBit = BIT0; + static constexpr EventBits_t kImuStoppedBit = BIT1; + static constexpr EventBits_t kBatteryStoppedBit = BIT2; + + static void TouchTaskEntry(void* context); + static void ImuTaskEntry(void* context); + static void BatteryTaskEntry(void* context); + void RunTouch(); + void RunImu(); + void RunBattery(); + bool SendTouch(const TouchEvent& event); + bool SendImu(const ImuBatch& batch); + bool SendGravity(const GravityEvent& event); + + CapacitiveTouchInput& touch_; + Bmi270Sensor& imu_; + BatteryMonitor& battery_; + ISensorMessageSink& sink_; + IEventPublisher* publisher_ = nullptr; + std::array touch_channels_{}; + ImuProcessor imu_processor_; + + std::atomic running_{false}; + bool touch_enabled_ = false; + bool imu_enabled_ = false; + bool battery_enabled_ = false; + EventGroupHandle_t stopped_events_ = nullptr; + StaticEventGroup_t stopped_events_control_{}; + + TaskHandle_t touch_task_ = nullptr; + StaticTask_t touch_task_control_{}; + std::array + touch_task_stack_{}; + TaskHandle_t imu_task_ = nullptr; + StaticTask_t imu_task_control_{}; + std::array + imu_task_stack_{}; + TaskHandle_t battery_task_ = nullptr; + StaticTask_t battery_task_control_{}; + std::array + battery_task_stack_{}; + + mutable portMUX_TYPE status_lock_ = + portMUX_INITIALIZER_UNLOCKED; + BatteryStatus battery_status_{}; + std::atomic touch_events_sent_{0}; + std::atomic imu_batches_sent_{0}; + std::atomic gravity_events_sent_{0}; + std::atomic messages_dropped_{0}; + std::atomic touch_read_errors_{0}; + std::atomic imu_read_errors_{0}; + std::atomic battery_read_errors_{0}; +}; + +} // namespace borla diff --git a/main/sensor/sensor_types.cc b/main/sensor/sensor_types.cc new file mode 100644 index 0000000..8f3a485 --- /dev/null +++ b/main/sensor/sensor_types.cc @@ -0,0 +1,56 @@ +#include "sensor/sensor_types.h" + +namespace borla { + +const char* ToString(TouchZone zone) +{ + switch (zone) { + case TouchZone::kHead: + return "touch_1"; + case TouchZone::kBack: + return "touch_2"; + case TouchZone::kRightHand: + return "touch_3"; + // case TouchZone::kLeftHand: + // return "touch_4"; + // case TouchZone::kBelly: + // return "touch_5";/////2026-9-4 ckkj mod + case TouchZone::kCount: + return "unknown"; + } + return "unknown"; +} + +const char* ToString(TouchAction action) +{ + switch (action) { + case TouchAction::kDown: + return "down"; + case TouchAction::kUp: + return "up"; + } + return "unknown"; +} + +const char* ToString(GravityAction action) +{ + switch (action) { + case GravityAction::kFreefall: + return "freefall"; + case GravityAction::kFreefallActive: + return "freefall_active"; + case GravityAction::kCaught: + return "caught"; + case GravityAction::kDropped: + return "dropped"; + case GravityAction::kImpact: + return "impact"; + case GravityAction::kSevereImpact: + return "severe_impact"; + case GravityAction::kCount: + return "unknown"; + } + return "unknown"; +} + +} // namespace borla diff --git a/main/sensor/sensor_types.h b/main/sensor/sensor_types.h new file mode 100644 index 0000000..4be0517 --- /dev/null +++ b/main/sensor/sensor_types.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include + +namespace borla { + +enum class TouchZone : uint8_t { + kHead, + kBack, + kRightHand, + // kLeftHand, + // kBelly, + kCount, +}; + +inline constexpr size_t kTouchZoneCount = + static_cast(TouchZone::kCount); + +const char* ToString(TouchZone zone); + +enum class TouchAction : uint8_t { + kDown, + kUp, +}; + +const char* ToString(TouchAction action); + +struct TouchEvent { + TouchZone zone = TouchZone::kHead; + TouchAction action = TouchAction::kDown; + uint64_t timestamp_ms = 0; + uint32_t duration_ms = 0; +}; + +struct ImuSample { + float ax = 0.0F; + float ay = 0.0F; + float az = 0.0F; + float gx = 0.0F; + float gy = 0.0F; + float gz = 0.0F; +}; + +inline constexpr size_t kImuWifiBatchCapacity = 5; + +struct ImuBatch { + uint32_t sequence = 0; + uint64_t timestamp_ms_base = 0; + uint8_t sample_rate_hz = 50; + size_t count = 0; + std::array samples{}; +}; + +enum class GravityAction : uint8_t { + kFreefall, + kFreefallActive, + kCaught, + kDropped, + kImpact, + kSevereImpact, + kCount, +}; + +const char* ToString(GravityAction action); + +struct GravityEvent { + GravityAction action = GravityAction::kFreefall; + uint32_t sequence = 0; + uint64_t timestamp_ms = 0; + uint32_t duration_ms = 0; + float magnitude_g = 0.0F; + float peak_g = 0.0F; +}; + +struct BatteryStatus { + uint64_t timestamp_ms = 0; + uint16_t millivolts = 0; + uint8_t percent = 0; + bool charging = false; + bool valid = false; +}; + +} // namespace borla diff --git a/main/sensor/touch_channel.cc b/main/sensor/touch_channel.cc new file mode 100644 index 0000000..7f512a6 --- /dev/null +++ b/main/sensor/touch_channel.cc @@ -0,0 +1,154 @@ +#include "sensor/touch_channel.h" + +#include +#include +#include + +namespace borla { + +TouchChannel::TouchChannel(const TouchChannelConfig& config) + : config_(config) +{ +} + +void TouchChannel::ResetCalibration() +{ + calibration_count_ = 0; + calibration_sum_ = 0.0; + calibration_square_sum_ = 0.0; + baseline_ = 0.0F; + filtered_ = 0.0F; + noise_deviation_ = 0.0F; + threshold_ = 0.0F; + press_count_ = 0; + release_count_ = 0; + calibrated_ = false; + pressed_ = false; + stuck_lockout_ = false; + pressed_at_ms_ = 0; +} + +void TouchChannel::AddCalibrationSample(uint32_t raw) +{ + calibration_count_++; + calibration_sum_ += static_cast(raw); + calibration_square_sum_ += + static_cast(raw) * static_cast(raw); +} + +bool TouchChannel::FinishCalibration() +{ + if (calibration_count_ < 2) { + return false; + } + const double count = static_cast(calibration_count_); + const double mean = calibration_sum_ / count; + const double variance = std::max( + 0.0, calibration_square_sum_ / count - mean * mean); + baseline_ = static_cast(mean); + filtered_ = baseline_; + noise_deviation_ = std::max( + config_.minimum_noise_deviation, + static_cast(std::sqrt(variance))); + UpdateThreshold(); + calibrated_ = true; + return true; +} + +bool TouchChannel::Process( + uint32_t raw, + uint64_t now_ms, + TouchTransition* transition) +{ + if (!calibrated_ || transition == nullptr) { + return false; + } + + filtered_ = (filtered_ * 7.0F + static_cast(raw)) / 8.0F; + if (pressed_ && static_cast(raw) < threshold_) { + // A release must not inherit the long EMA tail of a touch. + filtered_ = static_cast(raw); + } + + if (!pressed_) { + const float deviation = std::fabs(filtered_ - baseline_); + const float outlier_limit = std::max( + config_.minimum_threshold_delta, + config_.outlier_multiplier * noise_deviation_); + if (deviation < outlier_limit) { + baseline_ += + (filtered_ - baseline_) / + config_.baseline_follow_divisor; + noise_deviation_ += + (deviation - noise_deviation_) / + config_.noise_follow_divisor; + noise_deviation_ = std::max( + noise_deviation_, + config_.minimum_noise_deviation); + UpdateThreshold(); + } + } + + const bool touching = filtered_ > threshold_; + if (stuck_lockout_ && static_cast(raw) < threshold_) { + stuck_lockout_ = false; + } + + if (!pressed_) { + release_count_ = 0; + if (touching && !stuck_lockout_) { + if (press_count_ < std::numeric_limits::max()) { + press_count_++; + } + if (press_count_ >= config_.press_debounce_samples) { + press_count_ = 0; + pressed_ = true; + pressed_at_ms_ = now_ms; + transition->action = TouchAction::kDown; + transition->timestamp_ms = now_ms; + transition->duration_ms = 0; + return true; + } + } else { + press_count_ = 0; + } + return false; + } + + press_count_ = 0; + if (!touching) { + if (release_count_ < std::numeric_limits::max()) { + release_count_++; + } + } else { + release_count_ = 0; + } + + const uint64_t held_ms = now_ms - pressed_at_ms_; + const bool forced_release = + held_ms >= config_.maximum_press_ms && + static_cast(raw) < threshold_; + if (release_count_ < config_.release_debounce_samples && + !forced_release) { + return false; + } + + release_count_ = 0; + pressed_ = false; + stuck_lockout_ = forced_release; + transition->action = TouchAction::kUp; + transition->timestamp_ms = now_ms; + transition->duration_ms = static_cast( + std::min( + held_ms, std::numeric_limits::max())); + return true; +} + +void TouchChannel::UpdateThreshold() +{ + threshold_ = baseline_ + std::max( + config_.minimum_threshold_delta, + config_.threshold_noise_multiplier * noise_deviation_); +} + +} // namespace borla diff --git a/main/sensor/touch_channel.h b/main/sensor/touch_channel.h new file mode 100644 index 0000000..7c83ad4 --- /dev/null +++ b/main/sensor/touch_channel.h @@ -0,0 +1,65 @@ +#pragma once + +#include "sensor/sensor_types.h" + +#include +#include + +namespace borla { + +struct TouchChannelConfig { + float threshold_noise_multiplier = 5.0F; + float minimum_threshold_delta = 300.0F; + float minimum_noise_deviation = 50.0F; + float baseline_follow_divisor = 256.0F; + float noise_follow_divisor = 64.0F; + float outlier_multiplier = 4.0F; + uint8_t press_debounce_samples = 4; + uint8_t release_debounce_samples = 1; + uint32_t maximum_press_ms = 5000; +}; + +struct TouchTransition { + TouchAction action = TouchAction::kDown; + uint64_t timestamp_ms = 0; + uint32_t duration_ms = 0; +}; + +class TouchChannel final { +public: + TouchChannel( + const TouchChannelConfig& config = TouchChannelConfig{}); + + void ResetCalibration(); + void AddCalibrationSample(uint32_t raw); + bool FinishCalibration(); + bool Process( + uint32_t raw, + uint64_t now_ms, + TouchTransition* transition); + + bool calibrated() const { return calibrated_; } + bool pressed() const { return pressed_; } + float baseline() const { return baseline_; } + float threshold() const { return threshold_; } + +private: + void UpdateThreshold(); + + TouchChannelConfig config_; + size_t calibration_count_ = 0; + double calibration_sum_ = 0.0; + double calibration_square_sum_ = 0.0; + float baseline_ = 0.0F; + float filtered_ = 0.0F; + float noise_deviation_ = 0.0F; + float threshold_ = 0.0F; + uint8_t press_count_ = 0; + uint8_t release_count_ = 0; + bool calibrated_ = false; + bool pressed_ = false; + bool stuck_lockout_ = false; + uint64_t pressed_at_ms_ = 0; +}; + +} // namespace borla diff --git a/model_data/wn9l_ni3hao3bo1le4/_MODEL_INFO_ b/model_data/wn9l_ni3hao3bo1le4/_MODEL_INFO_ new file mode 100644 index 0000000..0fb1b3e --- /dev/null +++ b/model_data/wn9l_ni3hao3bo1le4/_MODEL_INFO_ @@ -0,0 +1 @@ +wakenet9l_tts3h12_Ni3Hao3Bo1Le4_3_0.613_0.621 \ No newline at end of file diff --git a/model_data/wn9l_ni3hao3bo1le4/wn9_data b/model_data/wn9l_ni3hao3bo1le4/wn9_data new file mode 100644 index 0000000..a334880 Binary files /dev/null and b/model_data/wn9l_ni3hao3bo1le4/wn9_data differ diff --git a/model_data/wn9l_ni3hao3bo1le4/wn9_index b/model_data/wn9l_ni3hao3bo1le4/wn9_index new file mode 100644 index 0000000..ad479dd Binary files /dev/null and b/model_data/wn9l_ni3hao3bo1le4/wn9_index differ diff --git a/partitions/partitions.csv b/partitions/partitions.csv new file mode 100644 index 0000000..e0b6ce8 --- /dev/null +++ b/partitions/partitions.csv @@ -0,0 +1,8 @@ +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x6000, +otadata, data, ota, 0xF000, 0x2000, +phy_init, data, phy, 0x11000, 0x1000, +ota_0, app, ota_0, 0x20000, 0x400000, +ota_1, app, ota_1, 0x420000, 0x400000, +model, data, spiffs, 0x820000, 0x100000, +claude_mem, data, spiffs, 0x920000, 0x6E0000, diff --git a/sdkconfig.defaults b/sdkconfig.defaults new file mode 100644 index 0000000..a10d4a2 --- /dev/null +++ b/sdkconfig.defaults @@ -0,0 +1,132 @@ +CONFIG_IDF_TARGET="esp32s3" + +CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions/partitions.csv" + +CONFIG_FREERTOS_HZ=1000 +CONFIG_FREERTOS_USE_TRACE_FACILITY=y +CONFIG_SPIRAM=y +CONFIG_SPIRAM_MODE_OCT=y +CONFIG_SPIRAM_SPEED_80M=y +CONFIG_SPIRAM_USE_MALLOC=y +# WiFi/lwIP buffers go to PSRAM first, exactly as the previous firmware +# (its sdkconfig.defaults line 92). Without this they come out of the internal +# heap, and with the capture stack + hot buffers also internal the device was +# measured running at free=1511 min=791 bytes — lwIP and TLS starve, the TCP +# receive window collapses, and the symptom is "no uplink, no TTS, no prompts". +CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP=y +CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY=y +# TRY_ALLOCATE_WIFI_LWIP silently RAISES the WiFi buffer defaults (static +# rx 10->16, rx_ba_win 6->16) on the theory that PSRAM absorbs the cost — +# but static RX/TX buffers are DMA and always come from internal RAM. Left +# uncapped they ate ~40 KB: internal free fell to 5 KB and the driver could +# not even malloc auth frames ("wifi:m f auth"), so the device sat in an +# auth->init retry loop while the credentials were perfectly valid. These +# caps are the previous firmware's proven pairing for the same flag. +CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=6 +CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=8 +CONFIG_ESP_WIFI_RX_BA_WIN=8 +# malloc() >= 1 KB prefers PSRAM (IDF default: 16 KB). Mid-size plain-malloc +# buffers (websocket rx, http client, cJSON) were squatting on internal RAM, +# which must stay available for DMA-capable allocations — esp-aes bounces +# every TLS record through an internal DMA buffer and drops the connection +# when it cannot get one ("esp-aes: Failed to allocate memory"). +# +# 2026-9-22 从 4096 降到 1024:双击配网时打印的内部堆快照显示 +# 0x3fcdad1c len 59391 free 14571 allocated 43908 / largest_free_block 11264 +# 0x3fce9710 len 22308 free 4 allocated 21204 / largest_free_block ... +# 两个内部区合计 ~85KB,被 71 个 <4KB 的小分配塞到只剩 4 字节,最大连续块只有 +# 11KB,而 BT 控制器初始化需要一次 30KB 连续内部块(BLE_INIT: Malloc failed)。 +# 阈值降到 1024 后这批小分配改落 PSRAM(还有 ~2.8MB 空闲),内部区得以腾空。 +CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=1024 +# 内部专用保留池:只服务于"必须在内部 RAM"的请求(DMA 缓冲、FreeRTOS 任务栈、 +# esp-aes bounce 等),普通 malloc 拿不到它。默认 32KB 已经被开机的几个动态栈 +# 吃掉大半:main 8KB + sys_evt 3KB + esp_timer + lwIP tcpip + ipc ≈ 25KB,剩下 +# 的碎块最大只有 11KB。而 BT 控制器初始化时要一次性要一个 **30KB 连续内部块** +# (BLE_INIT: Malloc failed → ROM assert emi.c/r_ble_util_buf_rx_alloc param 0x7800), +# 同一池子也是之前 "wifi:mem fail" / "esp-aes: Failed to allocate memory" 的现场。 +# 因此把池子扩到 64KB:装下 30KB 连续块后仍有余量。 +# 代价:主内部堆相应少 32KB(普通 malloc < 1KB 仍走内部),实测 PSRAM 侧还有 +# ~2.8MB 空闲,普通分配会落到 PSRAM。如果之后出现别的 malloc 失败,先回退到 49152。 +CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=65536 + +CONFIG_CODEC_ES8389_SUPPORT=y + +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y +CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y +CONFIG_COMPILER_OPTIMIZATION_PERF=y +CONFIG_COMPILER_CXX_EXCEPTIONS=n +CONFIG_COMPILER_CXX_RTTI=n + +CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y +CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC=y +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y +# Carried from the previous firmware: ssl_check_ctr_renegotiate dereferences +# ssl->session, which can be NULL during connection teardown -> LoadProhibited +# panic. Renegotiation is unused by our servers; keep it off. +CONFIG_MBEDTLS_SSL_RENEGOTIATION=n +CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=4096 +CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 +CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=n +CONFIG_MODEL_IN_FLASH=y +CONFIG_AFE_INTERFACE_V1=y +CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 + +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +CONFIG_BT_BLUEDROID_ENABLED=n +CONFIG_BT_CONTROLLER_ENABLED=y +CONFIG_BT_NIMBLE_MAX_CONNECTIONS=1 +CONFIG_BT_CTRL_BLE_MAX_ACT=2 +CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU=517 +CONFIG_BT_NIMBLE_ROLE_CENTRAL=n +CONFIG_BT_NIMBLE_ROLE_OBSERVER=y +CONFIG_BT_NIMBLE_GATT_CLIENT=n +# NimBLE HOST pools (msys mbufs, HCI evt/cmd/ACL buffers) go to PSRAM. The +# host is pure software and never touches DMA; only the controller needs +# internal RAM (bt_osi_mem_*_internal, unaffected by this switch). With the +# host pools internal, provisioning-mode BLE died at esp_nimble_init: after +# the controller claimed its share the fragmented internal heap (free 63KB, +# largest block 24.5KB) could not fit them -> "BLE_INIT: hci inits failed". +CONFIG_BT_NIMBLE_MEM_ALLOC_MODE_EXTERNAL=y + +CONFIG_LWIP_PPP_SUPPORT=y +CONFIG_LWIP_PPP_ENABLE_IPV4=y +CONFIG_LWIP_PPP_ENABLE_IPV6=n +CONFIG_LWIP_PPP_NOTIFY_PHASE_SUPPORT=y +CONFIG_LWIP_PPP_PAP_SUPPORT=y +CONFIG_LWIP_PPP_CHAP_SUPPORT=y +CONFIG_UART_ISR_IN_IRAM=y +CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK=y + +# sys_evt ran at 292 bytes of stack headroom (diagnostics LOW warning, IDF +# default 2304). One deep WiFi/IP event callback away from a corrupting +# overflow; +768 bytes of internal RAM buys the margin. +CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=3072 + +# Debug-phase only: stream mic+speaker PCM to tools/audio_tap_dump.py for +# boot-to-shutdown WAV capture. An open microphone on the LAN — flip to n +# before any release build. +CONFIG_BORLA_AUDIO_TAP=n + +# ML307 cellular: China Mobile APN; dial must use full 3GPP form with explicit +# PDP context id — ATD*99# gets immediate ERROR (ML307A rejects implicit dial). +CONFIG_BORLA_ML307_APN="cmiot" +CONFIG_BORLA_ML307_DIAL_COMMAND="ATD*99***1#" + +CONFIG_PM_ENABLE=y +CONFIG_FREERTOS_USE_TICKLESS_IDLE=n +CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y +CONFIG_PM_RESTORE_CACHE_TAGMEM_AFTER_LIGHT_SLEEP=y +CONFIG_PM_SLP_IRAM_OPT=y + +CONFIG_TOUCH_PAD_ENABLE=y +CONFIG_ESP_DRIVER_TOUCH_SENS_ENABLE=n + +CONFIG_LWIP_IPV6=n +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=n +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n +CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=n +CONFIG_MBEDTLS_TLS_CLIENT=y +CONFIG_MBEDTLS_TLS_SERVER=n \ No newline at end of file diff --git a/tools/audio_tap_dump.py b/tools/audio_tap_dump.py new file mode 100644 index 0000000..c731526 --- /dev/null +++ b/tools/audio_tap_dump.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Boot-to-shutdown audio recorder for the firmware2 debug audio tap. + +The device (CONFIG_BORLA_AUDIO_TAP=y) buffers everything the microphone +captured and everything the DAC played in PSRAM and serves both streams on +TCP port 3401. This script connects — retrying until the device boots — and +writes each power-on session as a timestamped pair of WAV files: + + firmware2/temp/video/-mic.wav (麦克风录入, 24 kHz mono) + firmware2/temp/video/-spk.wav (喇叭输出, 24 kHz mono) + +Start it BEFORE powering the device on and the files are gapless from the +boot prompt (the device pre-buffers ~32 s per channel while waiting for us). +When the device shuts down the socket dies, the pair is finalised, and the +script goes back to waiting for the next boot. Ctrl+C finalises and exits. + +Usage: + python3 tools/audio_tap_dump.py [--port 3401] [--out DIR] +""" + +import argparse +import datetime +import pathlib +import socket +import struct +import sys +import time + +MAGIC = b"BTAP" +HELLO_SIZE = 16 +CHANNEL_NAMES = {0: "mic", 1: "spk", 2: "uplink"} + + +def read_exact(sock: socket.socket, size: int) -> bytes: + """Reads exactly `size` bytes or raises ConnectionError on EOF.""" + chunks = [] + remaining = size + while remaining > 0: + chunk = sock.recv(remaining) + if not chunk: + raise ConnectionError("device closed the stream") + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) + + +def record_session(sock: socket.socket, out_dir: pathlib.Path) -> None: + import wave + + hello = read_exact(sock, HELLO_SIZE) + if hello[:4] != MAGIC or hello[4] != 2: + raise ConnectionError(f"unexpected hello: {hello!r}") + sample_rate = struct.unpack_from(" {path}") + + received = {channel: 0 for channel in CHANNEL_NAMES} + try: + while True: + header = read_exact(sock, 4) + channel = header[0] + payload_size = header[2] | (header[3] << 8) + payload = read_exact(sock, payload_size) + writer = writers.get(channel) + if writer is not None: + writer.writeframes(payload) + received[channel] += payload_size + finally: + for channel, writer in writers.items(): + writer.close() + seconds = received[channel] / 2 / channel_rates[channel] + print(f"[tap] closed {paths[channel]} ({seconds:.1f}s)") + + +def local_subnet_hosts(): + """Yields the /24 neighbours of this machine's primary interface.""" + probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + probe.connect(("8.8.8.8", 80)) + local_ip = probe.getsockname()[0] + except OSError: + return [] + finally: + probe.close() + prefix = local_ip.rsplit(".", 1)[0] + return [f"{prefix}.{host}" for host in range(1, 255) + if f"{prefix}.{host}" != local_ip] + + +def discover_device(port: int) -> str: + """Scans the local /24 for the one host listening on the tap port.""" + import concurrent.futures + + def probe(ip: str): + try: + with socket.create_connection((ip, port), timeout=0.4): + return ip + except OSError: + return None + + hosts = local_subnet_hosts() + while True: + if hosts: + with concurrent.futures.ThreadPoolExecutor(64) as pool: + for found in pool.map(probe, hosts): + if found: + print(f"[tap] found device at {found}") + return found + print("[tap] no device on the LAN yet, rescanning in 3 s " + "(power the device on; Ctrl+C to stop)") + time.sleep(3) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "device_ip", nargs="?", default=None, + help="device IP address (omit to auto-scan the local network)") + parser.add_argument("--port", type=int, default=3401) + parser.add_argument( + "--out", + default=None, + help="output directory (default: /temp/video)") + arguments = parser.parse_args() + + firmware_root = pathlib.Path(__file__).resolve().parent.parent + out_dir = (pathlib.Path(arguments.out) + if arguments.out + else firmware_root / "temp" / "video") + + device_ip = arguments.device_ip + try: + if device_ip is None: + device_ip = discover_device(arguments.port) + print(f"[tap] waiting for {device_ip}:{arguments.port} " + f"(power the device on now; Ctrl+C to stop)") + while True: + try: + sock = socket.create_connection( + (device_ip, arguments.port), timeout=3) + except OSError: + # DHCP can hand the device a different address next boot; + # fall back to a rescan instead of camping on a stale IP. + if arguments.device_ip is None: + device_ip = discover_device(arguments.port) + else: + time.sleep(1) + continue + sock.settimeout(None) + try: + record_session(sock, out_dir) + except ConnectionError as error: + print(f"[tap] session ended: {error}") + finally: + sock.close() + print("[tap] waiting for next boot...") + except KeyboardInterrupt: + print("\n[tap] stopped") + return 0 + + +if __name__ == "__main__": + sys.exit(main())