diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 009b4f1..f096206 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -13,6 +13,7 @@ - Wiring or pin-map impact: None - Flash, partition, or persistent-data impact: None - Backward-compatibility impact: None +- Release-flow impact: None ## Verification @@ -39,5 +40,5 @@ Commands run: - [ ] I ran the relevant validation command or explained why it was not run. - [ ] I separated build, host-test, and device-test results. - [ ] I updated authoritative documentation for changed hardware facts or durable behavior. -- [ ] I updated `docs/CHANGELOG.md` if this changes user-visible behavior, compatibility, or release workflow. +- [ ] I followed changelog ownership: ordinary pull requests leave it unchanged; release-preparation pull requests update both language files together. - [ ] I removed credentials, private device links, personal data, and unsanitized logs. diff --git a/.github/PULL_REQUEST_TEMPLATE.zh_CN.md b/.github/PULL_REQUEST_TEMPLATE.zh_CN.md index c513da6..22c244c 100644 --- a/.github/PULL_REQUEST_TEMPLATE.zh_CN.md +++ b/.github/PULL_REQUEST_TEMPLATE.zh_CN.md @@ -15,6 +15,7 @@ - 接线或引脚映射影响:无 - Flash、分区或持久化数据影响:无 - 向后兼容性影响:无 +- 发布流程影响:无 ## 验证 @@ -41,5 +42,5 @@ - [ ] 已运行相关验证命令,或说明未运行原因。 - [ ] 已分别报告 build、host tests 与 device tests。 - [ ] 已更新发生变化的硬件事实或长期行为对应的权威文档。 -- [ ] 若用户可见行为、兼容性或发布流程变化,已更新 `docs/CHANGELOG.zh_CN.md`。 +- [ ] 已遵守变更日志所有权:普通 PR 不修改变更日志;发布准备 PR 同时更新中英文文件。 - [ ] 已移除凭证、私密设备链接、个人数据和未脱敏日志。 diff --git a/AGENTS.md b/AGENTS.md index 5d8ef72..7785385 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,12 +9,16 @@ This file is the only mandatory entry point for AI-assisted work in this reposit ## Project and safety baseline - Target: ESP32-C3, 8 MB Flash, no PSRAM, ESP-IDF 5.5.3. -- Preserve the protected Flash layout: the 3 MB application limit and `cardid` - at `0x356000` are mandatory template contracts. +- Keep the repository's default partition table minimal: NVS, PHY data, and + one factory application spanning the rest of the 8 MB Flash. User firmware + may deliberately change this layout; validate the resulting table and do not + turn product-specific partitions into mandatory template contracts. - Preserve existing user changes. Start with `git status --short --branch`; never overwrite or clean unrelated files. +- Flashing new firmware does not require backing up the firmware already on the device; do not make a Flash readback a prerequisite. This does not guarantee preservation of user data or authorize a full-chip erase. Follow the [flashing and data policy](docs/development/engineering/firmware-layout.md#flashing-and-stored-data). - Hardware facts follow this priority: product specifications and measured results → `components/bsp/include/bsp_pins.h` → BSP headers and implementation → hardware guide → README/demo code. If a task requires a hardware detail not defined by these sources, ask the user instead of guessing. - Reusable board logic belongs in `components/bsp`; pages, state machines, animations, and application tasks belong in `main`. - LVGL is not thread-safe. Code outside the LVGL task must hold `bsp_lvgl_lock()` while accessing LVGL objects. +- Before adding Chinese UI text, follow the [font checklist](docs/development/engineering/coding-conventions.md#chinese-fonts-and-missing-glyphs). The default Montserrat fonts have no Chinese glyphs; UTF-8 and a successful build do not prove display support. Verify glyph coverage, widget font selection, and on-device rendering. - Button callbacks must stay non-blocking. Audio, storage, networking, and other slow operations belong in worker tasks. - A demo must stop every task, timer, callback, and event handler that can access its UI before deleting the screen. - Keep testable state machines, protocols, timing, and layout calculations independent from ESP-IDF/LVGL and cover them with host tests. @@ -29,7 +33,8 @@ This file is the only mandatory entry point for AI-assisted work in this reposit | Environment bootstrap or missing toolchain | `docs/development/engineering/environment-setup.md` | | BSP, pins, buses, display, audio, battery | `docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md`, `components/bsp/include/bsp_pins.h` | | Demo or menu | `main/demo.h`, `main/main.c`, the nearest `main/demo_*.c` implementation | -| Build, test, dependencies, partitions | `docs/development/engineering/build-and-test.md`, `docs/development/engineering/protected-flash-layout.md`, `sdkconfig.defaults`, `partitions.csv` | +| Chinese UI text or fonts | `docs/development/engineering/lvgl-chinese-fonts.md`, the application's font assets, configuration, and widget styles | +| Build, test, dependencies, partitions | `docs/development/engineering/build-and-test.md`, `docs/development/engineering/firmware-layout.md`, `sdkconfig.defaults`, `partitions.csv` | | CI or release | the matching file in `docs/development/ci/CI-*.md` and `.github/workflows/` | | Project completion | `docs/development/release/project-completion.md` (then the `issue-suggestions` or `experience-pr` skill) | | Documentation | `docs/contribution/doc-conventions.md`, `docs/README.md` | @@ -56,6 +61,6 @@ Device tests: PASS / FAIL / NOT RUN Unverified: remaining board, instrument, or user checks ``` -Create commits and push only when the user requests them or the active workflow explicitly requires them. Record user-visible changes in `docs/CHANGELOG.md`; internal refactors, CI maintenance, typo fixes, and generated-file refreshes do not require a changelog entry. +Create commits and push only when the user requests them or the active workflow explicitly requires them. Ordinary feature, application, and documentation pull requests must not edit `docs/CHANGELOG.md` or `docs/CHANGELOG.zh_CN.md`; describe user-visible behavior, compatibility, and release-flow impact in the pull-request body and authoritative documentation instead. During release preparation, the release maintainer aggregates merged user-visible changes into both changelog files before creating the tag. Community guidance is in `.github/CONTRIBUTING.md`, `.github/CODE_OF_CONDUCT.md`, `.github/SECURITY.md`, and `.github/SUPPORT.md`. diff --git a/AGENTS.zh_CN.md b/AGENTS.zh_CN.md index 3c068d6..7bc31bb 100644 --- a/AGENTS.zh_CN.md +++ b/AGENTS.zh_CN.md @@ -9,12 +9,15 @@ ## 项目与安全基线 - 目标平台:ESP32-C3、8 MB Flash、无 PSRAM、ESP-IDF 5.5.3。 -- 必须保持受保护的 Flash 布局:3 MB 应用上限与 `cardid@0x356000` - 均为模板强制契约。 +- 仓库默认分区表保持最简:只包含 NVS、PHY data,以及占用 8 MB Flash + 剩余空间的单个 factory app。用户固件可以按需求明确调整布局;修改后必须 + 验证结果,不得把产品专用分区变成模板的强制契约。 - 保留用户已有修改。先执行 `git status --short --branch`,不得覆盖或清理无关文件。 +- 下载(烧录)新固件无需备份设备内原有固件,不得把读取 Flash 备份作为前置条件。这不保证保留用户数据,也不授权全片擦除;遵循[烧录与数据说明](docs/development/engineering/firmware-layout.zh_CN.md#烧录与已存数据)。 - 硬件事实优先级:产品规格与实测结果 → `components/bsp/include/bsp_pins.h` → BSP 头文件与实现 → 硬件指南 → README/demo。任务所需硬件细节未在这些来源中定义时,直接询问用户,不得猜测。 - 可复用板级逻辑放入 `components/bsp`;页面、状态机、动画和应用任务放入 `main`。 - LVGL 非线程安全。LVGL 任务之外访问 LVGL 对象时必须持有 `bsp_lvgl_lock()`。 +- 添加中文 UI 前必须遵循[字体检查清单](docs/development/engineering/coding-conventions.zh_CN.md#中文字体与缺字排查)。默认 Montserrat 字体不含中文字形;UTF-8 正确、编译成功均不代表能够显示中文。必须核对字形覆盖、控件实际字体并完成真机显示验收。 - 按键回调不得阻塞。音频、存储、网络等慢操作必须放入工作任务。 - demo 删除 screen 前,必须停止所有可能访问其 UI 的任务、定时器、回调和事件处理器。 - 可测试的状态机、协议、计时和布局计算应与 ESP-IDF/LVGL 解耦,并由 host tests 覆盖。 @@ -29,7 +32,8 @@ | 环境引导或缺少工具链 | `docs/development/engineering/environment-setup.zh_CN.md` | | BSP、引脚、总线、显示、音频、电池 | `docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md`、`components/bsp/include/bsp_pins.h` | | Demo 或菜单 | `main/demo.h`、`main/main.c`、最近的 `main/demo_*.c` 实现 | -| 构建、测试、依赖、分区 | `docs/development/engineering/build-and-test.zh_CN.md`、`docs/development/engineering/protected-flash-layout.zh_CN.md`、`sdkconfig.defaults`、`partitions.csv` | +| 中文 UI 或字体 | `docs/development/engineering/lvgl-chinese-fonts.zh_CN.md`、应用字体素材、配置与控件样式 | +| 构建、测试、依赖、分区 | `docs/development/engineering/build-and-test.zh_CN.md`、`docs/development/engineering/firmware-layout.zh_CN.md`、`sdkconfig.defaults`、`partitions.csv` | | CI 或发布 | `docs/development/ci/CI-*.zh_CN.md` 中的对应文件与 `.github/workflows/` | | 项目开发完成 | `docs/development/release/project-completion.zh_CN.md`(再进入 `issue-suggestions` 或 `experience-pr` skill) | | 文档 | `docs/contribution/doc-conventions.zh_CN.md`、`docs/README.zh_CN.md` | @@ -56,6 +60,6 @@ Device tests: PASS / FAIL / NOT RUN Unverified: 仍需板卡、仪器或用户确认的事项 ``` -仅在用户请求或当前工作流明确要求时创建 commit 和 push。用户可见变化记录到 `docs/CHANGELOG.zh_CN.md`;内部重构、CI 维护、拼写修复和生成文件刷新无需记录。 +仅在用户请求或当前工作流明确要求时创建 commit 和 push。普通功能、应用和文档 PR 不得修改 `docs/CHANGELOG.md` 或 `docs/CHANGELOG.zh_CN.md`;用户可见行为、兼容性和发布流程影响改为写入 PR 正文及对应权威文档。发布准备期间,由发布负责人在创建 tag 前把已合并的用户可见变化统一汇总到两份变更日志。 社区规范见 `.github/CONTRIBUTING.zh_CN.md`、`.github/CODE_OF_CONDUCT.zh_CN.md`、`.github/SECURITY.zh_CN.md` 与 `.github/SUPPORT.zh_CN.md`。 diff --git a/components/bsp/CMakeLists.txt b/components/bsp/CMakeLists.txt index b202b04..8e4adce 100644 --- a/components/bsp/CMakeLists.txt +++ b/components/bsp/CMakeLists.txt @@ -2,8 +2,10 @@ idf_component_register( SRCS "src/bsp_i2c.c" "src/bsp_display.c" "src/bsp_display_lvgl.c" + "src/bsp_display_rounding.c" "src/bsp_button.c" "src/bsp_audio.c" + "src/bsp_es8311_sleep_check.c" "src/bsp_battery.c" INCLUDE_DIRS "include" REQUIRES driver esp_driver_i2c esp_driver_i2s esp_lcd esp_lvgl_port button esp_adc esp_codec_dev diff --git a/components/bsp/include/bsp_audio.h b/components/bsp/include/bsp_audio.h index 126df79..c328159 100644 --- a/components/bsp/include/bsp_audio.h +++ b/components/bsp/include/bsp_audio.h @@ -6,7 +6,8 @@ #include #include -// 初始化 codec 与 I2S。内部会调 bsp_i2c_init()(幂等),无需外部先调。 +// 初始化 codec 与 I2S。内部会调 bsp_i2c_init()(幂等),无需外部先调。成功调用可重复; +// 失败会释放本次已创建的 codec 接口和 I2S channel,修正故障后可重试。 esp_err_t bsp_audio_init(void); // 设置采样格式。同格式重复调用是廉价的(直接复用已打开的 codec)。 @@ -16,6 +17,22 @@ esp_err_t bsp_audio_init(void); // 音调和速度都快一倍。故本函数在格式变化时先 close 再 open。 esp_err_t bsp_audio_set_format(uint32_t hz, uint8_t bits, uint8_t ch); +// 进入低功耗前强制执行 ES8311 完整 suspend 寄存器序列,回读关键寄存器 +// (REG0E 只比较 bit6:0,其余寄存器比较全部位), +// 失败时重试一次,并显式停止 I2S TX/RX。该路径不依赖 codec-dev 是否打开过, +// 因此开机后从未播放也能正确暂停。调用前必须停止所有 PCM 读写;函数幂等, +// 音频未初始化时视为无需处理并返回成功。 +esp_err_t bsp_audio_sleep(void); + +// deep sleep 专用:确保 I2S TX/RX 已停止,再将 MCLK/BCLK/WS/DOUT/DIN +// 设为无上下拉的高阻输入。调用后 I2S 不能在本次运行中恢复,必须立即 +// 进入 deep sleep 或重启;不得用于 light sleep。 +esp_err_t bsp_audio_prepare_deep_sleep(void); + +// 从 light sleep 返回后恢复 ES8311 和休眠前的采样格式。函数幂等;deep sleep +// 唤醒会重启应用,应由 bsp_audio_init() 按正常启动流程重新初始化。 +esp_err_t bsp_audio_wake(void); + // 播放 / 录音。bytes 为字节数(16bit 单声道时 = 采样数 x 2)。 esp_err_t bsp_audio_write(const void *pcm, size_t bytes); esp_err_t bsp_audio_read(void *pcm, size_t bytes); diff --git a/components/bsp/include/bsp_battery.h b/components/bsp/include/bsp_battery.h index 2a48ae7..57e979a 100644 --- a/components/bsp/include/bsp_battery.h +++ b/components/bsp/include/bsp_battery.h @@ -9,6 +9,10 @@ // 芯片不应答时返回 ESP_ERR_NOT_FOUND —— 上层可据此在 UI 上标记该项不可用。 esp_err_t bsp_battery_init(void); +// 将 CW2017 CONFIG 写为睡眠值并回读确认,失败时重试一次。这是 deep +// sleep 前的终端操作;芯片未初始化时视为无需处理并返回成功。 +esp_err_t bsp_battery_sleep(void); + // 剩余电量百分比 0..100;读失败返回 -1。 int bsp_battery_soc(void); diff --git a/components/bsp/include/bsp_button.h b/components/bsp/include/bsp_button.h index 63e7a26..5bc740e 100644 --- a/components/bsp/include/bsp_button.h +++ b/components/bsp/include/bsp_button.h @@ -19,9 +19,11 @@ typedef enum { BSP_BTN_LONG, // 长按 } bsp_btn_ev_t; -// 按键事件回调。运行于 button 组件的定时器任务,勿在其中阻塞或做重活。 +// 按键事件回调。运行于 button 组件使用的共享 esp_timer 任务,只能入队或执行同等级 +// 的有界操作;勿在其中阻塞、访问 LVGL 或做重活。 typedef void (*bsp_btn_cb_t)(bsp_btn_t btn, bsp_btn_ev_t ev, void *user); +// 成功调用可重复,并更新回调与 user;失败会回滚本次已创建的按键和 ADC 资源。 esp_err_t bsp_button_init(bsp_btn_cb_t cb, void *user); // 读当前 ADC 原始电压(mV)。松开时约 3300;按住某键时约为该键的分压值。 diff --git a/components/bsp/include/bsp_display.h b/components/bsp/include/bsp_display.h index a2a41cc..488e612 100644 --- a/components/bsp/include/bsp_display.h +++ b/components/bsp/include/bsp_display.h @@ -7,7 +7,11 @@ #include #include -// 初始化 SPI 总线、面板、厂商寄存器、背光 LEDC。成功后屏幕已上电但内容未定。 +// The final LVGL frame is masked to this radius; pixels outside are pure black. +#define BSP_LVGL_SCREEN_RADIUS 30 + +// 初始化 SPI 总线、面板、厂商寄存器、背光 LEDC。成功调用可重复;失败会回滚本次 +// 已创建的显示资源,修正故障后可重试。成功后屏幕已上电但内容未定。 esp_err_t bsp_display_init(void); // 取底层面板句柄。想直接 esp_lcd_panel_draw_bitmap 画,或接 LVGL 以外的 GUI 时用。 @@ -20,6 +24,11 @@ esp_lcd_panel_io_handle_t bsp_display_io(void); // 背光亮度 0..100(%)。LEDC PWM,0=全灭。 void bsp_display_backlight(uint8_t percent); +// deep sleep 专用:关闭显示、让 ST7789 进入 Sleep In,停止背光 PWM, +// 将 CS/SCLK/MOSI/DC/背光设为安全电平并在 deep sleep 中保持。调用时必须 +// 已阻止 LVGL 刷屏,调用后必须立即进入 deep sleep 或重启。 +esp_err_t bsp_display_prepare_deep_sleep(void); + // --------------------------------------------------------------------------- // LVGL 接入(可选层)。必须先 bsp_display_init() 成功后再调。 // 不想用 LVGL 的开发者可忽略本段,直接用 bsp_display_panel() 自己画。 @@ -28,9 +37,10 @@ void bsp_display_backlight(uint8_t percent); // 故此处用 struct 形式即可,避免本头文件强行 include lvgl.h。 struct _lv_display_t; -// 启动 LVGL 与其渲染任务,返回 lv_display_t*。失败返回 NULL。 +// 启动 LVGL 与其渲染任务,返回 lv_display_t*。失败返回 NULL;display 注册失败会回滚 port。 struct _lv_display_t *bsp_lvgl_init(void); // LVGL 非线程安全:在【非 LVGL 任务】里操作任何 lv_* 对象前后必须加解锁。 +// LVGL 尚未就绪或超时时 lock 返回 false;只有 lock 成功后才调用 unlock。 bool bsp_lvgl_lock(int timeout_ms); void bsp_lvgl_unlock(void); diff --git a/components/bsp/include/bsp_i2c.h b/components/bsp/include/bsp_i2c.h index 7b86012..f28b566 100644 --- a/components/bsp/include/bsp_i2c.h +++ b/components/bsp/include/bsp_i2c.h @@ -15,3 +15,8 @@ i2c_master_bus_handle_t bsp_i2c_bus(void); // 扫描 0x08..0x77 并打印所有应答的设备。排查"芯片是不是没焊好/地址对不对"极有用。 // 直接在正式总线上扫,不要另开临时总线 —— 原因见 bsp_i2c.c 中 bsp_i2c_scan() 的注释。 esp_err_t bsp_i2c_scan(void); + +// deep sleep 专用:所有共享外设的最后一笔 I2C 事务完成后,将 SDA/SCL +// 设为无上下拉的高阻输入。调用后禁止再访问总线,必须立即进入 deep sleep +// 或重启。板上外部上拉电阻的静态功耗不受此接口控制。 +esp_err_t bsp_i2c_prepare_deep_sleep(void); diff --git a/components/bsp/src/bsp_audio.c b/components/bsp/src/bsp_audio.c index 85b2633..fb705f3 100644 --- a/components/bsp/src/bsp_audio.c +++ b/components/bsp/src/bsp_audio.c @@ -1,22 +1,190 @@ // components/bsp/src/bsp_audio.c // 移植自 trae_card/components/platform/platform_esp32/src/audio_es8311.c #include "bsp_audio.h" +#include "bsp_es8311_sleep_check.h" #include "bsp_i2c.h" #include "bsp_pins.h" #include "esp_codec_dev.h" #include "esp_codec_dev_defaults.h" #include "es8311_codec.h" +#include "driver/gpio.h" #include "driver/i2s_std.h" #include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" static const char *TAG = "bsp_audio"; static esp_codec_dev_handle_t s_dev; static i2s_chan_handle_t s_tx, s_rx; +static const audio_codec_ctrl_if_t *s_ctrl; +static const audio_codec_data_if_t *s_data; +static const audio_codec_if_t *s_codec; +static const audio_codec_gpio_if_t *s_gpio; // 记录当前已打开的格式,用于判断"要不要 close 重开"(见头文件里的坑说明)。 static uint32_t s_hz; static uint8_t s_bits, s_ch; static bool s_opened; +static bool s_sleeping; + +#define AUDIO_DEFAULT_HZ 16000 +#define AUDIO_DEFAULT_BITS 16 +#define AUDIO_DEFAULT_CH 1 +#define ES8311_SLEEP_ATTEMPTS 2 +#define ES8311_SLEEP_RETRY_MS 5 + +typedef struct { + uint8_t reg; + uint8_t value; +} es8311_reg_value_t; + +// 寄存器序列不依赖 esp_codec_dev 的 opened 标志。REG45=0x01 额外关闭 +// BCLK/LRCK 内部上拉,比当前 esp_codec_dev 1.6.2 的默认 suspend 更彻底。 +static const es8311_reg_value_t s_es8311_sleep_sequence[] = { + {0x32, 0x00}, {0x17, 0x00}, {0x0E, 0xFF}, {0x12, 0x02}, + {0x14, 0x00}, {0x0D, 0xFA}, {0x15, 0x00}, {0x02, 0x10}, + {0x00, 0x00}, {0x00, 0x1F}, {0x01, 0x30}, {0x01, 0x00}, + {0x45, 0x01}, {0x0D, 0xFC}, {0x02, 0x00}, +}; + +static esp_err_t audio_disable_i2s_channels(void) { + esp_err_t first_error = ESP_OK; + const struct { + i2s_chan_handle_t channel; + const char *name; + } channels[] = { + {s_tx, "TX"}, + {s_rx, "RX"}, + }; + + for (size_t i = 0; i < sizeof(channels) / sizeof(channels[0]); i++) { + if (!channels[i].channel) continue; + esp_err_t e = i2s_channel_disable(channels[i].channel); + if (e == ESP_ERR_INVALID_STATE) e = ESP_OK; // READY 即已停止。 + if (e != ESP_OK) { + ESP_LOGE(TAG, "I2S %s 停止失败: %s", channels[i].name, + esp_err_to_name(e)); + if (first_error == ESP_OK) first_error = e; + } + } + return first_error; +} + +static esp_err_t es8311_force_sleep_once(unsigned attempt) { + bool valid = true; + + for (size_t i = 0; i < sizeof(s_es8311_sleep_sequence) / + sizeof(s_es8311_sleep_sequence[0]); i++) { + const es8311_reg_value_t *item = &s_es8311_sleep_sequence[i]; + uint8_t value = item->value; + int write_result = s_ctrl->write_reg(s_ctrl, item->reg, 1, &value, 1); + if (write_result == ESP_CODEC_DEV_OK) continue; + + uint8_t actual = 0; + int read_result = s_ctrl->read_reg(s_ctrl, item->reg, 1, &actual, 1); + if (read_result == ESP_CODEC_DEV_OK) { + ESP_LOGE(TAG, "ES8311 休眠写入失败 attempt=%u REG%02X " + "expected=0x%02X actual=0x%02X error=%d", + attempt, item->reg, item->value, actual, write_result); + } else { + ESP_LOGE(TAG, "ES8311 休眠写入失败 attempt=%u REG%02X " + "expected=0x%02X actual=unavailable error=%d read_error=%d", + attempt, item->reg, item->value, write_result, read_result); + } + valid = false; + } + + for (size_t i = 0; i < bsp_es8311_sleep_check_count; i++) { + const bsp_es8311_reg_check_t *item = &bsp_es8311_sleep_checks[i]; + uint8_t actual = 0; + int read_result = s_ctrl->read_reg(s_ctrl, item->reg, 1, &actual, 1); + if (read_result == ESP_CODEC_DEV_OK && + bsp_es8311_sleep_check_matches(item, actual)) continue; + + ESP_LOGE(TAG, "ES8311 休眠校验失败 attempt=%u REG%02X " + "expected=0x%02X mask=0x%02X actual=0x%02X error=%d", + attempt, item->reg, item->value, item->mask, actual, read_result); + valid = false; + } + return valid ? ESP_OK : ESP_FAIL; +} + +static esp_err_t es8311_force_sleep(void) { + if (!s_ctrl || !s_ctrl->read_reg || !s_ctrl->write_reg) { + return ESP_ERR_INVALID_STATE; + } + + for (unsigned attempt = 1; attempt <= ES8311_SLEEP_ATTEMPTS; attempt++) { + esp_err_t e = es8311_force_sleep_once(attempt); + if (e == ESP_OK) { + ESP_LOGI(TAG, "ES8311 已进入低功耗状态并通过寄存器校验"); + return ESP_OK; + } + if (attempt < ES8311_SLEEP_ATTEMPTS) { + vTaskDelay(pdMS_TO_TICKS(ES8311_SLEEP_RETRY_MS)); + } + } + + ESP_LOGE(TAG, "ES8311 强制休眠失败"); + return ESP_FAIL; +} + +// esp_codec_dev_open() 会先 disable 再重配 I2S;close 后通道处于 READY, +// 先 enable 一次可让下一次 open 的内部 disable 合法。 +static esp_err_t audio_prepare_i2s_reopen(void) { + esp_err_t e = s_tx ? i2s_channel_enable(s_tx) : ESP_ERR_INVALID_STATE; + if (e != ESP_OK) { + ESP_LOGE(TAG, "I2S TX 恢复失败: %s", esp_err_to_name(e)); + return e; + } + e = s_rx ? i2s_channel_enable(s_rx) : ESP_ERR_INVALID_STATE; + if (e != ESP_OK) { + ESP_LOGE(TAG, "I2S RX 恢复失败: %s", esp_err_to_name(e)); + i2s_channel_disable(s_tx); + } + return e; +} + +// esp_codec_dev 不拥有传入的接口和 I2S channel;失败回滚必须按依赖逆序逐一释放。 +static void audio_cleanup(void) { + if (s_dev) { + esp_codec_dev_delete(s_dev); + s_dev = NULL; + } + if (s_codec) { + audio_codec_delete_codec_if(s_codec); + s_codec = NULL; + } + if (s_gpio) { + audio_codec_delete_gpio_if(s_gpio); + s_gpio = NULL; + } + if (s_data) { + audio_codec_delete_data_if(s_data); + s_data = NULL; + } + if (s_rx) { + i2s_channel_disable(s_rx); + esp_err_t e = i2s_del_channel(s_rx); + if (e == ESP_OK) s_rx = NULL; + else ESP_LOGE(TAG, "I2S RX 回滚失败: %s", esp_err_to_name(e)); + } + if (s_tx) { + i2s_channel_disable(s_tx); + esp_err_t e = i2s_del_channel(s_tx); + if (e == ESP_OK) s_tx = NULL; + else ESP_LOGE(TAG, "I2S TX 回滚失败: %s", esp_err_to_name(e)); + } + if (s_ctrl) { + audio_codec_delete_ctrl_if(s_ctrl); + s_ctrl = NULL; + } + s_opened = false; + s_sleeping = false; + s_hz = 0; + s_bits = 0; + s_ch = 0; +} static esp_err_t i2s_full_duplex_init(void) { i2s_chan_config_t chan = { @@ -66,39 +234,47 @@ static esp_err_t i2s_full_duplex_init(void) { // esp_codec_dev_open 内部重配前会先 i2s_channel_disable,而 disable 要求通道处于 // RUNNING;刚 init 的通道是 READY,会打一条 "channel has not been enabled yet" 错误日志。 // 这里先 enable 一次让那次 disable 合法(此时 codec 未配,不出声)。 - i2s_channel_enable(s_tx); - i2s_channel_enable(s_rx); - return ESP_OK; + e = i2s_channel_enable(s_tx); + if (e == ESP_OK) e = i2s_channel_enable(s_rx); + if (e != ESP_OK) ESP_LOGE(TAG, "i2s channel enable 失败: %s", esp_err_to_name(e)); + return e; } esp_err_t bsp_audio_init(void) { if (s_dev) return ESP_OK; + if (s_tx || s_rx || s_ctrl || s_data || s_codec || s_gpio) { + ESP_LOGE(TAG, "上次音频初始化回滚不完整,拒绝覆盖仍存活的资源句柄"); + return ESP_ERR_INVALID_STATE; + } esp_err_t e = bsp_i2c_init(); if (e != ESP_OK) return e; - const audio_codec_ctrl_if_t *ctrl = audio_codec_new_i2c_ctrl(&(audio_codec_i2c_cfg_t){ + s_ctrl = audio_codec_new_i2c_ctrl(&(audio_codec_i2c_cfg_t){ .port = BSP_I2C_PORT, .addr = BSP_I2C_ES8311_ADDR << 1, // 该接口要 8 位地址形式 .bus_handle = bsp_i2c_bus(), }); - if (!ctrl) { + if (!s_ctrl) { ESP_LOGE(TAG, "ES8311 控制口创建失败 —— 用 bsp_i2c_scan() 确认 0x%02X 是否应答;" "检查 SDA=GPIO%d / SCL=GPIO%d 接线与 codec 供电", BSP_I2C_ES8311_ADDR, BSP_I2C_SDA, BSP_I2C_SCL); return ESP_FAIL; } - if ((e = i2s_full_duplex_init()) != ESP_OK) return e; + if ((e = i2s_full_duplex_init()) != ESP_OK) goto fail; - const audio_codec_data_if_t *data = audio_codec_new_i2s_data(&(audio_codec_i2s_cfg_t){ + s_data = audio_codec_new_i2s_data(&(audio_codec_i2s_cfg_t){ .port = BSP_I2S_PORT, .tx_handle = s_tx, .rx_handle = s_rx, }); - if (!data) { ESP_LOGE(TAG, "I2S 数据口创建失败"); return ESP_FAIL; } + if (!s_data) { ESP_LOGE(TAG, "I2S 数据口创建失败"); e = ESP_ERR_NO_MEM; goto fail; } - const audio_codec_if_t *codec = es8311_codec_new(&(es8311_codec_cfg_t){ - .ctrl_if = ctrl, - .gpio_if = audio_codec_new_gpio(), + s_gpio = audio_codec_new_gpio(); + if (!s_gpio) { ESP_LOGE(TAG, "codec GPIO 接口创建失败"); e = ESP_ERR_NO_MEM; goto fail; } + + s_codec = es8311_codec_new(&(es8311_codec_cfg_t){ + .ctrl_if = s_ctrl, + .gpio_if = s_gpio, .codec_mode = ESP_CODEC_DEV_WORK_MODE_BOTH, .pa_pin = BSP_I2S_PA_CTRL, .pa_reverted = false, @@ -109,30 +285,36 @@ esp_err_t bsp_audio_init(void) { // ADCL+DACR 参考模式,单声道读到的那一路是 DAC 参考 → 【录音恒为 0】。 .no_dac_ref = true, }); - if (!codec) { ESP_LOGE(TAG, "es8311_codec_new 失败"); return ESP_FAIL; } + if (!s_codec) { ESP_LOGE(TAG, "es8311_codec_new 失败"); e = ESP_ERR_NO_MEM; goto fail; } s_dev = esp_codec_dev_new(&(esp_codec_dev_cfg_t){ .dev_type = ESP_CODEC_DEV_TYPE_IN_OUT, - .codec_if = codec, - .data_if = data, + .codec_if = s_codec, + .data_if = s_data, }); - if (!s_dev) { ESP_LOGE(TAG, "esp_codec_dev_new 失败"); return ESP_FAIL; } + if (!s_dev) { ESP_LOGE(TAG, "esp_codec_dev_new 失败"); e = ESP_ERR_NO_MEM; goto fail; } ESP_LOGI(TAG, "ES8311 就绪"); return ESP_OK; + +fail: + audio_cleanup(); + return e; } esp_err_t bsp_audio_set_format(uint32_t hz, uint8_t bits, uint8_t ch) { if (!s_dev) return ESP_ERR_INVALID_STATE; + if (s_sleeping) return ESP_ERR_INVALID_STATE; if (s_opened && s_hz == hz && s_bits == bits && s_ch == ch) return ESP_OK; // 同格式复用 if (s_opened) { - esp_codec_dev_close(s_dev); + if (esp_codec_dev_close(s_dev) != ESP_CODEC_DEV_OK) { + ESP_LOGE(TAG, "esp_codec_dev_close 失败"); + return ESP_FAIL; + } s_opened = false; - // close 把 I2S 通道退回 READY,而接下来的 open 内部又会 disable 一次 → - // 会打 "channel has not been enabled yet"。补一次 enable 让它合法。 - if (s_tx) i2s_channel_enable(s_tx); - if (s_rx) i2s_channel_enable(s_rx); + esp_err_t e = audio_prepare_i2s_reopen(); + if (e != ESP_OK) return e; } esp_codec_dev_sample_info_t fs = { @@ -155,16 +337,94 @@ esp_err_t bsp_audio_set_format(uint32_t hz, uint8_t bits, uint8_t ch) { return ESP_OK; } +esp_err_t bsp_audio_sleep(void) { + if (!s_dev || s_sleeping) return ESP_OK; + + esp_err_t first_error = ESP_OK; + // 已打开路径仍让 codec-dev 更新软件状态;寄存器强制序列在 close + // 之后再执行,以覆盖依赖库中 REG45=0x00 的较弱 suspend 序列。 + if (s_opened) { + if (!s_codec || !s_codec->enable || + s_codec->enable(s_codec, false) != ESP_CODEC_DEV_OK) { + ESP_LOGE(TAG, "ES8311 codec-dev suspend 状态更新失败"); + first_error = ESP_FAIL; + } + if (esp_codec_dev_close(s_dev) != ESP_CODEC_DEV_OK) { + ESP_LOGE(TAG, "ES8311 codec-dev close 失败"); + if (first_error == ESP_OK) first_error = ESP_FAIL; + } + } + s_opened = false; + + esp_err_t e = es8311_force_sleep(); + if (e != ESP_OK && first_error == ESP_OK) first_error = e; + + e = audio_disable_i2s_channels(); + if (e != ESP_OK && first_error == ESP_OK) first_error = e; + s_sleeping = true; + return first_error; +} + +esp_err_t bsp_audio_prepare_deep_sleep(void) { + esp_err_t first_error = audio_disable_i2s_channels(); + const int pins[] = { + BSP_I2S_MCLK, BSP_I2S_BCLK, BSP_I2S_WS, BSP_I2S_DOUT, BSP_I2S_DIN, + }; + uint64_t mask = 0; + for (size_t i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) { + if (pins[i] >= 0) mask |= 1ULL << (unsigned)pins[i]; + } + + gpio_config_t cfg = { + .pin_bit_mask = mask, + .mode = GPIO_MODE_INPUT, + .pull_up_en = GPIO_PULLUP_DISABLE, + .pull_down_en = GPIO_PULLDOWN_DISABLE, + .intr_type = GPIO_INTR_DISABLE, + }; + esp_err_t e = gpio_config(&cfg); + if (e != ESP_OK) { + ESP_LOGE(TAG, "I2S 引脚高阻配置失败: %s", esp_err_to_name(e)); + if (first_error == ESP_OK) first_error = e; + } else { + ESP_LOGI(TAG, "I2S MCLK/BCLK/WS/DOUT/DIN 已切换为高阻"); + } + return first_error; +} + +esp_err_t bsp_audio_wake(void) { + if (!s_dev || !s_sleeping) return ESP_OK; + + esp_err_t e = audio_prepare_i2s_reopen(); + if (e != ESP_OK) return e; + + // 允许内部格式设置重新 open codec;失败时再次 close,避免留下半唤醒状态。 + s_sleeping = false; + e = bsp_audio_set_format(s_hz ? s_hz : AUDIO_DEFAULT_HZ, + s_bits ? s_bits : AUDIO_DEFAULT_BITS, + s_ch ? s_ch : AUDIO_DEFAULT_CH); + if (e != ESP_OK) { + (void)esp_codec_dev_close(s_dev); + s_opened = false; + s_sleeping = true; + ESP_LOGE(TAG, "ES8311 唤醒失败: %s", esp_err_to_name(e)); + return e; + } + + ESP_LOGI(TAG, "ES8311 已从低功耗状态恢复"); + return ESP_OK; +} + esp_err_t bsp_audio_write(const void *pcm, size_t bytes) { - if (!s_dev) return ESP_ERR_INVALID_STATE; + if (!s_dev || !s_opened || s_sleeping) return ESP_ERR_INVALID_STATE; return esp_codec_dev_write(s_dev, (void *)pcm, bytes) == 0 ? ESP_OK : ESP_FAIL; } esp_err_t bsp_audio_read(void *pcm, size_t bytes) { - if (!s_dev) return ESP_ERR_INVALID_STATE; + if (!s_dev || !s_opened || s_sleeping) return ESP_ERR_INVALID_STATE; return esp_codec_dev_read(s_dev, pcm, bytes) == 0 ? ESP_OK : ESP_FAIL; } void bsp_audio_set_volume(uint8_t percent) { - if (s_dev) esp_codec_dev_set_out_vol(s_dev, percent); + if (s_dev && s_opened && !s_sleeping) esp_codec_dev_set_out_vol(s_dev, percent); } diff --git a/components/bsp/src/bsp_battery.c b/components/bsp/src/bsp_battery.c index b7138f1..09a338a 100644 --- a/components/bsp/src/bsp_battery.c +++ b/components/bsp/src/bsp_battery.c @@ -41,15 +41,15 @@ _Static_assert(sizeof(s_battery_profile) == CW_PROFILE_SIZE, static i2c_master_dev_handle_t s_dev; -static int cw_read(uint8_t reg, uint8_t *buf, size_t n) { - if (!s_dev) return -1; - return i2c_master_transmit_receive(s_dev, ®, 1, buf, n, 100) == ESP_OK ? 0 : -1; +static esp_err_t cw_read(uint8_t reg, uint8_t *buf, size_t n) { + if (!s_dev) return ESP_ERR_INVALID_STATE; + return i2c_master_transmit_receive(s_dev, ®, 1, buf, n, 100); } -static int cw_write(uint8_t reg, uint8_t val) { - if (!s_dev) return -1; +static esp_err_t cw_write(uint8_t reg, uint8_t val) { + if (!s_dev) return ESP_ERR_INVALID_STATE; uint8_t b[2] = { reg, val }; - return i2c_master_transmit(s_dev, b, 2, 100) == ESP_OK ? 0 : -1; + return i2c_master_transmit(s_dev, b, 2, 100); } // CONFIG 的低 4 bit 为保留位。复位、睡眠和激活均按芯片规定的时序切换。 @@ -187,6 +187,31 @@ fail: return e; } +esp_err_t bsp_battery_sleep(void) { + if (!s_dev) return ESP_OK; + + for (unsigned attempt = 1; attempt <= 2; attempt++) { + uint8_t actual = 0; + esp_err_t write_error = cw_write(CW_REG_CONFIG, CW_CONFIG_SLEEP); + vTaskDelay(pdMS_TO_TICKS(5)); + esp_err_t read_error = cw_read(CW_REG_CONFIG, &actual, 1); + if (write_error == ESP_OK && read_error == ESP_OK && + actual == CW_CONFIG_SLEEP) { + ESP_LOGI(TAG, "CW2017 已进入休眠并通过寄存器校验"); + return ESP_OK; + } + + ESP_LOGW(TAG, "CW2017 休眠失败 attempt=%u write=%s(0x%x) " + "read=%s(0x%x) actual=0x%02X", + attempt, esp_err_to_name(write_error), (unsigned)write_error, + esp_err_to_name(read_error), (unsigned)read_error, actual); + if (attempt < 2) vTaskDelay(pdMS_TO_TICKS(5)); + } + + ESP_LOGE(TAG, "CW2017 连续两次未能进入休眠"); + return ESP_FAIL; +} + int bsp_battery_soc(void) { uint8_t b[2] = { 0 }; if (cw_read(CW_REG_SOC_H, b, 2) != 0) return -1; diff --git a/components/bsp/src/bsp_button.c b/components/bsp/src/bsp_button.c index c160bb8..625d143 100644 --- a/components/bsp/src/bsp_button.c +++ b/components/bsp/src/bsp_button.c @@ -16,6 +16,7 @@ static const uint16_t BTN_MV[BSP_BTN_COUNT][2] = BSP_BTN_MV_TABLE; static button_handle_t s_btn[BSP_BTN_COUNT]; static bsp_btn_cb_t s_cb; static void *s_user; +static bool s_ready; // ADC1 是 unit 级独占资源:iot_button 与 bsp_button_read_mv() 必须共用同一个 oneshot // 句柄。谁第二个调 adc_oneshot_new_unit() 谁就拿到 "adc1 is already in use"。 @@ -38,7 +39,60 @@ static void cb_click (void *a, void *u) { on_event(a, u, BSP_BTN_CLICK); } static void cb_double(void *a, void *u) { on_event(a, u, BSP_BTN_DOUBLE); } static void cb_long (void *a, void *u) { on_event(a, u, BSP_BTN_LONG); } +// 初始化中途失败时先停掉所有 button driver,再释放本文件持有的校准与 ADC unit。 +// button driver 仍在轮询时不能先删 ADC,否则 timer callback 会访问失效句柄。 +static void button_cleanup(void) { + s_cb = NULL; + s_user = NULL; + s_ready = false; + + for (int i = BSP_BTN_COUNT - 1; i >= 0; i--) { + if (!s_btn[i]) continue; + esp_err_t e = iot_button_delete(s_btn[i]); + if (e != ESP_OK) { + ESP_LOGE(TAG, "按键 %d 回滚失败: %s", i, esp_err_to_name(e)); + continue; + } + s_btn[i] = NULL; + } + + if (s_cali) { + esp_err_t e = adc_cali_delete_scheme_curve_fitting(s_cali); + if (e != ESP_OK) ESP_LOGE(TAG, "ADC 校准回滚失败: %s", esp_err_to_name(e)); + else s_cali = NULL; + } + if (s_adc) { + esp_err_t e = adc_oneshot_del_unit(s_adc); + if (e != ESP_OK) ESP_LOGE(TAG, "ADC unit 回滚失败: %s", esp_err_to_name(e)); + else s_adc = NULL; + } +} + +static esp_err_t register_callbacks(button_handle_t button, void *index) { + esp_err_t e = iot_button_register_cb(button, BUTTON_PRESS_DOWN, NULL, cb_press, index); + if (e == ESP_OK) e = iot_button_register_cb(button, BUTTON_SINGLE_CLICK, NULL, cb_click, index); + if (e == ESP_OK) e = iot_button_register_cb(button, BUTTON_DOUBLE_CLICK, NULL, cb_double, index); + if (e == ESP_OK) e = iot_button_register_cb(button, BUTTON_LONG_PRESS_START, NULL, cb_long, index); + return e; +} + esp_err_t bsp_button_init(bsp_btn_cb_t cb, void *user) { + if (s_ready) { + s_cb = cb; + s_user = user; + return ESP_OK; + } + if (s_adc || s_cali) { + ESP_LOGE(TAG, "上次按键初始化回滚不完整,拒绝覆盖仍存活的 ADC 句柄"); + return ESP_ERR_INVALID_STATE; + } + for (int i = 0; i < BSP_BTN_COUNT; i++) { + if (s_btn[i]) { + ESP_LOGE(TAG, "上次按键 %d 回滚不完整,拒绝重复分配资源", i); + return ESP_ERR_INVALID_STATE; + } + } + s_cb = cb; s_user = user; // 先由 BSP 建 unit,再把句柄交给 button 组件(button_adc.h:adc_handle 非 NULL 即复用), @@ -48,6 +102,7 @@ esp_err_t bsp_button_init(bsp_btn_cb_t cb, void *user) { if (ae != ESP_OK) { ESP_LOGE(TAG, "ADC unit 创建失败 (%s)", esp_err_to_name(ae)); s_adc = NULL; + button_cleanup(); return ae; } @@ -65,13 +120,17 @@ esp_err_t bsp_button_init(bsp_btn_cb_t cb, void *user) { if (e != ESP_OK || !s_btn[i]) { ESP_LOGE(TAG, "按键 %d 创建失败 (%s) —— 检查 GPIO%d 的 ADC 配置与分压电阻", i, esp_err_to_name(e), BSP_BTN_ADC_CHANNEL); - return e == ESP_OK ? ESP_FAIL : e; + e = e == ESP_OK ? ESP_FAIL : e; + button_cleanup(); + return e; } void *idx = (void *)(intptr_t)i; - iot_button_register_cb(s_btn[i], BUTTON_PRESS_DOWN, NULL, cb_press, idx); - iot_button_register_cb(s_btn[i], BUTTON_SINGLE_CLICK, NULL, cb_click, idx); - iot_button_register_cb(s_btn[i], BUTTON_DOUBLE_CLICK, NULL, cb_double, idx); - iot_button_register_cb(s_btn[i], BUTTON_LONG_PRESS_START,NULL, cb_long, idx); + e = register_callbacks(s_btn[i], idx); + if (e != ESP_OK) { + ESP_LOGE(TAG, "按键 %d 回调注册失败: %s", i, esp_err_to_name(e)); + button_cleanup(); + return e; + } } // 通道已由组件配置好,这里只补一份校准句柄给 bsp_button_read_mv() 用。 @@ -87,6 +146,7 @@ esp_err_t bsp_button_init(bsp_btn_cb_t cb, void *user) { s_cali = NULL; } + s_ready = true; ESP_LOGI(TAG, "按键就绪:ADC1_CH%d 三键分压", BSP_BTN_ADC_CHANNEL); return ESP_OK; } diff --git a/components/bsp/src/bsp_display.c b/components/bsp/src/bsp_display.c index 5525118..1109397 100644 --- a/components/bsp/src/bsp_display.c +++ b/components/bsp/src/bsp_display.c @@ -2,6 +2,7 @@ // 移植自 trae_card/components/platform/platform_esp32/src/disp_st7789.c #include "bsp_display.h" #include "bsp_pins.h" +#include "driver/gpio.h" #include "driver/spi_master.h" #include "driver/ledc.h" #include "esp_lcd_panel_io.h" @@ -15,7 +16,52 @@ static const char *TAG = "bsp_disp"; static esp_lcd_panel_handle_t s_panel; static esp_lcd_panel_io_handle_t s_io; +static bool s_bus_ready; static bool s_bl_ready; +static bool s_ready; + +static const gpio_num_t s_deep_sleep_pins[] = { + BSP_LCD_CS, BSP_LCD_SCLK, BSP_LCD_MOSI, BSP_LCD_DC, BSP_LCD_BL, +}; + +static const uint8_t s_deep_sleep_levels[] = { + 1, 0, 0, 0, 0, +}; + +static esp_err_t display_set_safe_levels(void) { + esp_err_t first_error = ESP_OK; + for (size_t i = 0; i < sizeof(s_deep_sleep_pins) / + sizeof(s_deep_sleep_pins[0]); i++) { + gpio_num_t pin = s_deep_sleep_pins[i]; + if ((int)pin < 0) continue; + gpio_config_t cfg = { + .pin_bit_mask = 1ULL << (unsigned)pin, + .mode = GPIO_MODE_OUTPUT, + .pull_up_en = GPIO_PULLUP_DISABLE, + .pull_down_en = GPIO_PULLDOWN_DISABLE, + .intr_type = GPIO_INTR_DISABLE, + }; + esp_err_t e = gpio_config(&cfg); + if (e == ESP_OK) e = gpio_set_level(pin, s_deep_sleep_levels[i]); + if (e != ESP_OK && first_error == ESP_OK) first_error = e; + } + return first_error; +} + +// deep-sleep hold 可跨 reset 保留。先禁用全局 deep hold,在单引脚 hold +// 仍生效时写入与休眠期一致的安全值,再解锁各引脚,避免唤醒瞬间毛刺。 +static esp_err_t display_release_deep_sleep_holds(void) { + gpio_deep_sleep_hold_dis(); + esp_err_t first_error = display_set_safe_levels(); + for (size_t i = 0; i < sizeof(s_deep_sleep_pins) / + sizeof(s_deep_sleep_pins[0]); i++) { + gpio_num_t pin = s_deep_sleep_pins[i]; + if ((int)pin < 0) continue; + esp_err_t e = gpio_hold_dis(pin); + if (e != ESP_OK && first_error == ESP_OK) first_error = e; + } + return first_error; +} // --------------------------------------------------------------------------- // ST7789P3 厂商专属初始化序列(porch / power / gamma)。 @@ -53,8 +99,8 @@ static const st_init_cmd_t ST7789P3_CMDS[] = { 0x40, 0x3A, 0x15, 0x15, 0x26, 0x2A}, 14, 10}, // NVGAMCTRL 负伽马 }; -static void backlight_init(void) { - if (BSP_LCD_BL < 0) { ESP_LOGW(TAG, "背光引脚未接 MCU,亮度不可调"); return; } +static esp_err_t backlight_init(void) { + if (BSP_LCD_BL < 0) { ESP_LOGW(TAG, "背光引脚未接 MCU,亮度不可调"); return ESP_OK; } ledc_timer_config_t t = { .speed_mode = BSP_BL_LEDC_MODE, .timer_num = BSP_BL_LEDC_TIMER, @@ -63,7 +109,7 @@ static void backlight_init(void) { .clk_cfg = LEDC_AUTO_CLK, }; esp_err_t e = ledc_timer_config(&t); - if (e != ESP_OK) { ESP_LOGE(TAG, "ledc_timer_config 失败: %s", esp_err_to_name(e)); return; } + if (e != ESP_OK) { ESP_LOGE(TAG, "ledc_timer_config 失败: %s", esp_err_to_name(e)); return e; } ledc_channel_config_t ch = { .gpio_num = BSP_LCD_BL, @@ -74,14 +120,28 @@ static void backlight_init(void) { .hpoint = 0, }; e = ledc_channel_config(&ch); - if (e != ESP_OK) { ESP_LOGE(TAG, "ledc_channel_config 失败: %s", esp_err_to_name(e)); return; } + if (e != ESP_OK) { + ESP_LOGE(TAG, "ledc_channel_config 失败: %s", esp_err_to_name(e)); + ledc_timer_rst(BSP_BL_LEDC_MODE, BSP_BL_LEDC_TIMER); + return e; + } s_bl_ready = true; ESP_LOGI(TAG, "背光 LEDC 就绪 gpio=%d", BSP_LCD_BL); + return ESP_OK; } esp_err_t bsp_display_init(void) { - if (s_panel) return ESP_OK; + if (s_ready) return ESP_OK; + esp_err_t e = display_release_deep_sleep_holds(); + if (e != ESP_OK) { + ESP_LOGE(TAG, "LCD deep-sleep hold 解除失败: %s", esp_err_to_name(e)); + return e; + } + if (s_panel || s_io || s_bus_ready) { + ESP_LOGE(TAG, "上次显示初始化回滚不完整,拒绝覆盖仍存活的 SPI 资源"); + return ESP_ERR_INVALID_STATE; + } spi_bus_config_t bus = { .mosi_io_num = BSP_LCD_MOSI, @@ -89,12 +149,13 @@ esp_err_t bsp_display_init(void) { .miso_io_num = -1, .quadwp_io_num = -1, .quadhd_io_num = -1, .max_transfer_sz = BSP_LCD_W * 80 * 2, }; - esp_err_t e = spi_bus_initialize(BSP_LCD_SPI_HOST, &bus, SPI_DMA_CH_AUTO); + e = spi_bus_initialize(BSP_LCD_SPI_HOST, &bus, SPI_DMA_CH_AUTO); if (e != ESP_OK) { ESP_LOGE(TAG, "SPI 总线初始化失败 (%s) —— 检查 MOSI=GPIO%d / SCLK=GPIO%d 是否冲突", esp_err_to_name(e), BSP_LCD_MOSI, BSP_LCD_SCLK); return e; } + s_bus_ready = true; esp_lcd_panel_io_spi_config_t io_cfg = { .cs_gpio_num = BSP_LCD_CS, @@ -105,7 +166,7 @@ esp_err_t bsp_display_init(void) { .trans_queue_depth = 10, }; e = esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)BSP_LCD_SPI_HOST, &io_cfg, &s_io); - if (e != ESP_OK) { ESP_LOGE(TAG, "panel_io 创建失败: %s", esp_err_to_name(e)); return e; } + if (e != ESP_OK) { ESP_LOGE(TAG, "panel_io 创建失败: %s", esp_err_to_name(e)); goto fail; } esp_lcd_panel_dev_config_t dev = { .reset_gpio_num = BSP_LCD_RST, // -1 → SWRESET 软复位 @@ -113,26 +174,57 @@ esp_err_t bsp_display_init(void) { .bits_per_pixel = 16, }; e = esp_lcd_new_panel_st7789(s_io, &dev, &s_panel); - if (e != ESP_OK) { ESP_LOGE(TAG, "面板创建失败: %s", esp_err_to_name(e)); return e; } + if (e != ESP_OK) { ESP_LOGE(TAG, "面板创建失败: %s", esp_err_to_name(e)); goto fail; } - esp_lcd_panel_reset(s_panel); // rst=-1 时走 SWRESET - esp_lcd_panel_init(s_panel); // SLPOUT / COLMOD / RAMCTRL + e = esp_lcd_panel_reset(s_panel); // rst=-1 时走 SWRESET + if (e != ESP_OK) { ESP_LOGE(TAG, "面板复位失败: %s", esp_err_to_name(e)); goto fail; } + e = esp_lcd_panel_init(s_panel); // SLPOUT / COLMOD / RAMCTRL + if (e != ESP_OK) { ESP_LOGE(TAG, "面板初始化失败: %s", esp_err_to_name(e)); goto fail; } for (size_t i = 0; i < sizeof(ST7789P3_CMDS) / sizeof(ST7789P3_CMDS[0]); i++) { const st_init_cmd_t *c = &ST7789P3_CMDS[i]; - esp_err_t r = esp_lcd_panel_io_tx_param(s_io, c->cmd, c->data, c->len); - if (r != ESP_OK) ESP_LOGE(TAG, "厂商初始化命令 0x%02X 失败: %s", c->cmd, esp_err_to_name(r)); + e = esp_lcd_panel_io_tx_param(s_io, c->cmd, c->data, c->len); + if (e != ESP_OK) { + ESP_LOGE(TAG, "厂商初始化命令 0x%02X 失败: %s", c->cmd, esp_err_to_name(e)); + goto fail; + } if (c->delay_ms) vTaskDelay(pdMS_TO_TICKS(c->delay_ms)); } - esp_lcd_panel_invert_color(s_panel, BSP_LCD_INVERT_COLOR); // 0x21 / 0x20 - esp_lcd_panel_mirror(s_panel, false, false); // 0x36 MADCTL:本板不需镜像(XY 双镜像 = 画面 180°) - esp_lcd_panel_set_gap(s_panel, 0, 0); - esp_lcd_panel_disp_on_off(s_panel, true); // 0x29 DISPON + e = esp_lcd_panel_invert_color(s_panel, BSP_LCD_INVERT_COLOR); // 0x21 / 0x20 + if (e != ESP_OK) { ESP_LOGE(TAG, "面板反色设置失败: %s", esp_err_to_name(e)); goto fail; } + e = esp_lcd_panel_mirror(s_panel, false, false); // 0x36 MADCTL:本板不需镜像(XY 双镜像 = 画面 180°) + if (e != ESP_OK) { ESP_LOGE(TAG, "面板镜像设置失败: %s", esp_err_to_name(e)); goto fail; } + e = esp_lcd_panel_set_gap(s_panel, 0, 0); + if (e != ESP_OK) { ESP_LOGE(TAG, "面板偏移设置失败: %s", esp_err_to_name(e)); goto fail; } + e = esp_lcd_panel_disp_on_off(s_panel, true); // 0x29 DISPON + if (e != ESP_OK) { ESP_LOGE(TAG, "面板显示开启失败: %s", esp_err_to_name(e)); goto fail; } - backlight_init(); + e = backlight_init(); + if (e != ESP_OK) goto fail; + s_ready = true; ESP_LOGI(TAG, "显示就绪 %dx%d", BSP_LCD_W, BSP_LCD_H); return ESP_OK; + +fail: + s_ready = false; + if (s_panel) { + esp_err_t cleanup = esp_lcd_panel_del(s_panel); + if (cleanup == ESP_OK) s_panel = NULL; + else ESP_LOGE(TAG, "面板回滚失败: %s", esp_err_to_name(cleanup)); + } + if (!s_panel && s_io) { + esp_err_t cleanup = esp_lcd_panel_io_del(s_io); + if (cleanup == ESP_OK) s_io = NULL; + else ESP_LOGE(TAG, "panel IO 回滚失败: %s", esp_err_to_name(cleanup)); + } + if (!s_io && s_bus_ready) { + esp_err_t cleanup = spi_bus_free(BSP_LCD_SPI_HOST); + if (cleanup == ESP_OK) s_bus_ready = false; + else ESP_LOGE(TAG, "SPI 总线回滚失败: %s", esp_err_to_name(cleanup)); + } + s_bl_ready = false; + return e; } esp_lcd_panel_handle_t bsp_display_panel(void) { return s_panel; } @@ -147,3 +239,50 @@ void bsp_display_backlight(uint8_t percent) { ledc_set_duty(BSP_BL_LEDC_MODE, BSP_BL_LEDC_CHANNEL, duty); ledc_update_duty(BSP_BL_LEDC_MODE, BSP_BL_LEDC_CHANNEL); } + +esp_err_t bsp_display_prepare_deep_sleep(void) { + esp_err_t first_error = ESP_OK; + if (!s_ready || !s_panel) { + first_error = ESP_ERR_INVALID_STATE; + ESP_LOGE(TAG, "LCD 未就绪,无法发送 deep-sleep 命令"); + } else { + esp_err_t e = esp_lcd_panel_disp_on_off(s_panel, false); + if (e != ESP_OK) { + ESP_LOGE(TAG, "ST7789 关闭显示失败: %s", esp_err_to_name(e)); + first_error = e; + } + e = esp_lcd_panel_disp_sleep(s_panel, true); + if (e != ESP_OK) { + ESP_LOGE(TAG, "ST7789 Sleep In 失败: %s", esp_err_to_name(e)); + if (first_error == ESP_OK) first_error = e; + } + } + + bsp_display_backlight(0); + if (s_bl_ready && BSP_LCD_BL >= 0) { + esp_err_t e = ledc_stop(BSP_BL_LEDC_MODE, BSP_BL_LEDC_CHANNEL, 0); + if (e != ESP_OK) { + ESP_LOGE(TAG, "LCD 背光 PWM 停止失败: %s", esp_err_to_name(e)); + if (first_error == ESP_OK) first_error = e; + } + } + + esp_err_t e = display_set_safe_levels(); + if (e != ESP_OK) { + ESP_LOGE(TAG, "LCD SPI 安全电平配置失败: %s", esp_err_to_name(e)); + if (first_error == ESP_OK) first_error = e; + } + for (size_t i = 0; i < sizeof(s_deep_sleep_pins) / + sizeof(s_deep_sleep_pins[0]); i++) { + gpio_num_t pin = s_deep_sleep_pins[i]; + if ((int)pin < 0) continue; + e = gpio_hold_en(pin); + if (e != ESP_OK) { + ESP_LOGE(TAG, "LCD GPIO%d hold 失败: %s", (int)pin, esp_err_to_name(e)); + if (first_error == ESP_OK) first_error = e; + } + } + gpio_deep_sleep_hold_en(); + ESP_LOGI(TAG, "ST7789 已休眠,LCD SPI 与背光安全电平已保持"); + return first_error; +} diff --git a/components/bsp/src/bsp_display_lvgl.c b/components/bsp/src/bsp_display_lvgl.c index 935f6bd..924624d 100644 --- a/components/bsp/src/bsp_display_lvgl.c +++ b/components/bsp/src/bsp_display_lvgl.c @@ -1,14 +1,49 @@ // components/bsp/src/bsp_display_lvgl.c // LVGL 接入单独成文件:不用 LVGL 的开发者删掉本文件 + idf_component.yml 里的两条依赖即可。 #include "bsp_display.h" +#include "bsp_display_rounding.h" #include "bsp_pins.h" #include "esp_lvgl_port.h" #include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" static const char *TAG = "bsp_lvgl"; static lv_display_t *s_disp; +static void rounded_flush_event(lv_event_t *event) +{ + lv_display_t *disp = lv_event_get_target(event); + const lv_area_t *area = lv_event_get_param(event); + lv_draw_buf_t *draw_buf = lv_display_get_buf_active(disp); + if (!area || !draw_buf || !draw_buf->data || + lv_display_get_color_format(disp) != LV_COLOR_FORMAT_RGB565) { + return; + } + + const int32_t width = lv_area_get_width(area); + if (draw_buf->header.stride < (uint32_t)width * sizeof(uint16_t)) return; + + for (int32_t y = area->y1; y <= area->y2; ++y) { + if (y >= BSP_LVGL_SCREEN_RADIUS && + y < BSP_LCD_H - BSP_LVGL_SCREEN_RADIUS) { + continue; + } + + uint16_t *row = (uint16_t *)(draw_buf->data + + (y - area->y1) * draw_buf->header.stride); + for (int32_t x = area->x1; x <= area->x2; ++x) { + if (bsp_display_pixel_outside_rounded_rect( + x, y, BSP_LCD_W, BSP_LCD_H, BSP_LVGL_SCREEN_RADIUS)) { + // The port swaps RGB565 bytes after this event; black is 0 in + // either byte order, so masking here is safe. + row[x - area->x1] = 0; + } + } + } +} + lv_display_t *bsp_lvgl_init(void) { if (s_disp) return s_disp; if (!bsp_display_panel()) { @@ -38,11 +73,28 @@ lv_display_t *bsp_lvgl_init(void) { .flags = { .buff_dma = true, .swap_bytes = true }, }; s_disp = lvgl_port_add_disp(&dc); - if (!s_disp) { ESP_LOGE(TAG, "lvgl_port_add_disp 失败"); return NULL; } + if (!s_disp) { + ESP_LOGE(TAG, "lvgl_port_add_disp 失败"); + esp_err_t e = lvgl_port_deinit(); + if (e != ESP_OK) ESP_LOGE(TAG, "lvgl_port_deinit 回滚失败: %s", esp_err_to_name(e)); + // 2.9.0 的 deinit 由 LVGL task 完成;无 display 时该 task 每 tick 检查退出标志。 + vTaskDelay(pdMS_TO_TICKS(10)); + return NULL; + } - ESP_LOGI(TAG, "LVGL 就绪"); + // Mask the final RGB565 flush instead of using root-screen clip_corner. + // Full-screen rounded clipping creates an ARGB layer that does not fit the + // 24 KB LVGL pool reliably on this no-PSRAM target. + lv_display_add_event_cb(s_disp, rounded_flush_event, LV_EVENT_FLUSH_START, NULL); + + ESP_LOGI(TAG, "LVGL 就绪,全局圆角=%d,外部填充=黑色", BSP_LVGL_SCREEN_RADIUS); return s_disp; } -bool bsp_lvgl_lock(int timeout_ms) { return lvgl_port_lock(timeout_ms); } -void bsp_lvgl_unlock(void) { lvgl_port_unlock(); } +bool bsp_lvgl_lock(int timeout_ms) { + if (!s_disp) return false; + return lvgl_port_lock(timeout_ms); +} +void bsp_lvgl_unlock(void) { + if (s_disp) lvgl_port_unlock(); +} diff --git a/components/bsp/src/bsp_display_rounding.c b/components/bsp/src/bsp_display_rounding.c new file mode 100644 index 0000000..16d0992 --- /dev/null +++ b/components/bsp/src/bsp_display_rounding.c @@ -0,0 +1,32 @@ +#include "bsp_display_rounding.h" + +bool bsp_display_pixel_outside_rounded_rect(int32_t x, int32_t y, + int32_t width, int32_t height, + int32_t radius) +{ + if (x < 0 || y < 0 || x >= width || y >= height) return true; + if (radius <= 0 || width <= 0 || height <= 0) return false; + + int32_t max_radius = (width < height ? width : height) / 2; + if (radius > max_radius) radius = max_radius; + + int32_t dx; + if (x < radius) { + dx = radius - x; + } else if (x >= width - radius) { + dx = x - (width - 1 - radius); + } else { + return false; + } + + int32_t dy; + if (y < radius) { + dy = radius - y; + } else if (y >= height - radius) { + dy = y - (height - 1 - radius); + } else { + return false; + } + + return dx * dx + dy * dy > radius * radius; +} diff --git a/components/bsp/src/bsp_display_rounding.h b/components/bsp/src/bsp_display_rounding.h new file mode 100644 index 0000000..4c562b8 --- /dev/null +++ b/components/bsp/src/bsp_display_rounding.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +// Pure geometry helper kept independent from ESP-IDF/LVGL for host tests. +bool bsp_display_pixel_outside_rounded_rect(int32_t x, int32_t y, + int32_t width, int32_t height, + int32_t radius); diff --git a/components/bsp/src/bsp_es8311_sleep_check.c b/components/bsp/src/bsp_es8311_sleep_check.c new file mode 100644 index 0000000..650efda --- /dev/null +++ b/components/bsp/src/bsp_es8311_sleep_check.c @@ -0,0 +1,17 @@ +#include "bsp_es8311_sleep_check.h" + +// REG0E bit 7 is not a defined control bit and reads as 0 on reported boards. +// Keep writing the vendor suspend value 0xFF, but verify only bits 6:0. +const bsp_es8311_reg_check_t bsp_es8311_sleep_checks[] = { + {0x00, 0x1F, 0xFF}, {0x01, 0x00, 0xFF}, {0x0D, 0xFC, 0xFF}, + {0x0E, 0x7F, 0x7F}, {0x12, 0x02, 0xFF}, {0x45, 0x01, 0xFF}, +}; + +const size_t bsp_es8311_sleep_check_count = + sizeof(bsp_es8311_sleep_checks) / sizeof(bsp_es8311_sleep_checks[0]); + +bool bsp_es8311_sleep_check_matches(const bsp_es8311_reg_check_t *check, + uint8_t actual) +{ + return (actual & check->mask) == (check->value & check->mask); +} diff --git a/components/bsp/src/bsp_es8311_sleep_check.h b/components/bsp/src/bsp_es8311_sleep_check.h new file mode 100644 index 0000000..2929622 --- /dev/null +++ b/components/bsp/src/bsp_es8311_sleep_check.h @@ -0,0 +1,19 @@ +// Hardware-independent ES8311 suspend readback policy; private to the BSP. +#pragma once + +#include +#include +#include + +typedef struct { + uint8_t reg; + uint8_t value; + uint8_t mask; +} bsp_es8311_reg_check_t; + +extern const bsp_es8311_reg_check_t bsp_es8311_sleep_checks[]; +extern const size_t bsp_es8311_sleep_check_count; + +// Call only after a successful register read; an I2C error is never a match. +bool bsp_es8311_sleep_check_matches(const bsp_es8311_reg_check_t *check, + uint8_t actual); diff --git a/components/bsp/src/bsp_i2c.c b/components/bsp/src/bsp_i2c.c index f8ee84a..e7e06e9 100644 --- a/components/bsp/src/bsp_i2c.c +++ b/components/bsp/src/bsp_i2c.c @@ -1,6 +1,7 @@ // components/bsp/src/bsp_i2c.c #include "bsp_i2c.h" #include "bsp_pins.h" +#include "driver/gpio.h" #include "esp_log.h" static const char *TAG = "bsp_i2c"; @@ -61,3 +62,20 @@ esp_err_t bsp_i2c_scan(void) { else ESP_LOGI(TAG, "I2C 扫描完成,共 %d 个设备", found); return ESP_OK; } + +esp_err_t bsp_i2c_prepare_deep_sleep(void) { + gpio_config_t cfg = { + .pin_bit_mask = (1ULL << BSP_I2C_SDA) | (1ULL << BSP_I2C_SCL), + .mode = GPIO_MODE_INPUT, + .pull_up_en = GPIO_PULLUP_DISABLE, + .pull_down_en = GPIO_PULLDOWN_DISABLE, + .intr_type = GPIO_INTR_DISABLE, + }; + esp_err_t e = gpio_config(&cfg); + if (e != ESP_OK) { + ESP_LOGE(TAG, "I2C SDA/SCL 高阻配置失败: %s", esp_err_to_name(e)); + return e; + } + ESP_LOGI(TAG, "I2C SDA/SCL 已切换为高阻;外部上拉功耗仍由硬件决定"); + return ESP_OK; +} diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8d2992f..e3f5ccf 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,6 +4,12 @@ # Changelog +> **Release-maintainer owned:** ordinary feature, application, and documentation +> pull requests do not edit this file. Before creating a release tag, the release +> maintainer reviews merged user-visible changes and updates this file together +> with `CHANGELOG.zh_CN.md`. The entries currently under `Unreleased` are pending +> review for the next release; they are not a finalized release history. + ## Unreleased - Added the supplied 80-byte CW2017 profile for the specified 520 mAh cell, including content/update-flag checks, verified writes, the required restart sequence, and bounded SOC-readiness polling. diff --git a/docs/CHANGELOG.zh_CN.md b/docs/CHANGELOG.zh_CN.md index 20e39f1..5ce12e3 100644 --- a/docs/CHANGELOG.zh_CN.md +++ b/docs/CHANGELOG.zh_CN.md @@ -4,6 +4,10 @@ # Changelog +> **由发布负责人维护:** 普通功能、应用和文档 PR 不修改本文件。创建发布 tag 前, +> 发布负责人检查已合并的用户可见变化,并与 `CHANGELOG.md` 同步更新。当前 +> `Unreleased` 下的条目是下次发布的待核对内容,不是已经定稿的发布历史。 + ## Unreleased - 加入厂家为优特利 520mAh 电芯生成的 80 字节 CW2017 profile,并实现内容与更新标志检查、写入后校验、规定的重启时序以及有上限的 SOC 就绪等待。 diff --git a/docs/README.md b/docs/README.md index 9dc9e6b..cd97106 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,17 +20,17 @@ The table below describes the application capabilities implemented by the curren | --- | --- | --- | --- | | Display | ST7789P3, 240 × 320 portrait RGB565, SPI2 at 40 MHz; LEDC backlight | `bsp_display_*`, `bsp_lvgl_*` | The ESP32-C3 has no PSRAM; the current design uses a small single DMA buffer; the BSP exposes no LCD MISO, touch, or TE interface | | Input | `UP`, `DOWN`, and `OK` share an ADC resistor ladder on GPIO0 | `bsp_button_init()`, `bsp_button_read_mv()` | Callbacks run in the button component task and must not block; do not create a second ADC1 unit | -| Audio | ES8311 with full-duplex PCM over I2S0, supporting playback and microphone capture | `bsp_audio_*` | PCM reads and writes block and belong in a worker task; format changes must retain the BSP close/open sequence | +| Audio | ES8311 with full-duplex PCM over I2S0, supporting playback, microphone capture, and software suspend/resume | `bsp_audio_*` | PCM reads and writes block and belong in a worker task; stop PCM I/O before codec sleep; format changes must retain the BSP close/open sequence | | Battery | CW2017 state-of-charge and voltage readings | `bsp_battery_*` | This capability is optional at runtime; accuracy depends on the cell and battery profile and is not equivalent to a calibrated result | | Wi-Fi | On-demand 2.4 GHz STA scan demo | `main/demo_wifi.c` | Scans only; it does not connect, store credentials, or validate antenna/RF performance | | Bluetooth LE | On-demand non-connectable NimBLE advertising as `FoloPassport` | `main/demo_ble.c` | ESP32-C3 does not support Bluetooth Classic; radio range, coexistence, and power draw require device measurements | -| Low power | Two-second light sleep and five-second deep sleep, both with RTC timer wakeup | `main/demo_low_power.c` | Deep sleep restarts the application; the current demo exposes RTC timer wake only | +| Low power | Two-second light sleep and five-second deep sleep, both with RTC timer wakeup | `main/demo_low_power.c` | Both modes force and verify ES8311 suspend; light sleep restores audio, while deep sleep first suspends CW2017, releases I2S/shared-I2C pins, sleeps and holds the LCD pins, then restarts on wake; the current demo exposes RTC timer wake only | | Shared bus | ES8311 and CW2017 share I2C0 | `bsp_i2c_*` | Every device must reuse the bus owned by the BSP; do not create another bus on the same port for scanning or a new device | | Logging and flashing | Native ESP32-C3 USB Serial/JTAG | ESP-IDF console | GPIO18/19 are reserved for USB; the default UART0 TX on GPIO21 conflicts with the backlight | All pins, addresses, panel parameters, and button voltage windows are defined only in [`components/bsp/include/bsp_pins.h`](../components/bsp/include/bsp_pins.h). Application code must not duplicate these constants. See the [AI Hardware Development Guide](hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md) for the complete pin map, panel initialization, ADC thresholds, I2C addressing rules, audio clocks, and memory details. -Applications may also use ESP-IDF timers, FreeRTOS tasks, and internal Flash/NVS; the Pomodoro branch contains an NVS example. Wi-Fi and Bluetooth LE remain ESP-IDF application services rather than BSP APIs: their menu pages initialize each stack only while open and release it on exit. `demo/claude-buddy-port` remains a fuller BLE application architecture reference, not a substitute for measuring the current board's antenna, RF performance, power consumption, and coexistence behavior. The current product and firmware baseline uses 8 MB Flash with a 3 MB factory-app partition and fixed protected `cardid` storage. +Applications may also use ESP-IDF timers, FreeRTOS tasks, and internal Flash/NVS; the Pomodoro branch contains an NVS example. Wi-Fi and Bluetooth LE remain ESP-IDF application services rather than BSP APIs: their menu pages initialize each stack only while open and release it on exit. `demo/claude-buddy-port` remains a fuller BLE application architecture reference, not a substitute for measuring the current board's antenna, RF performance, power consumption, and coexistence behavior. The default custom-firmware baseline uses 8 MB Flash with only NVS, PHY data, and one factory-app partition spanning the remaining space; user firmware may replace it with another valid 8 MB layout. ### Capabilities outside the current contract @@ -68,6 +68,8 @@ When details are omitted, the assistant may choose conservative defaults that do Each `demo/*` branch evolves the baseline into an independent application. The branches demonstrate how specific problems were solved. New applications should normally branch from `main` and consult relevant examples instead of merging multiple demos wholesale. +The menu and `demo_*.c` pages on `main` are also hardware-capability demonstrations, not a ready-made product UI. A new application must redesign and implement its screens and interaction flow for its own requirements rather than directly using or copying the current demo interface. BSP APIs, lifecycle patterns, and isolated logic may still be reused. + | Branch | Application | Patterns worth reusing | | --- | --- | --- | | `demo/stopwatch` | Stopwatch | Minimal timer application, separation of pure logic from LVGL, host-side logic tests | diff --git a/docs/README.zh_CN.md b/docs/README.zh_CN.md index 8b33e62..e66c34a 100644 --- a/docs/README.zh_CN.md +++ b/docs/README.zh_CN.md @@ -20,17 +20,17 @@ FoloToy AI Passport 是一个开放式可穿戴 AI 硬件,本仓库是这款 A | --- | --- | --- | --- | | 显示 | ST7789P3,240 × 320,竖屏 RGB565,SPI2 40 MHz;LEDC 背光 | `bsp_display_*`、`bsp_lvgl_*` | ESP32-C3 无 PSRAM;当前为小型单 DMA 缓冲;BSP 未暴露 LCD MISO、触摸或 TE 接口 | | 输入 | `UP` / `DOWN` / `OK` 三键,共用 GPIO0 的 ADC 电阻分压 | `bsp_button_init()`、`bsp_button_read_mv()` | 回调运行在 button 组件任务中,不能阻塞;不能再创建第二个 ADC1 unit | -| 音频 | ES8311,I2S0 全双工 PCM,可播放和麦克风录音 | `bsp_audio_*` | PCM 读写为阻塞调用,应放工作任务;格式切换必须保留 BSP 内的 close/open 流程 | +| 音频 | ES8311,I2S0 全双工 PCM,支持播放、麦克风录音及软件休眠/恢复 | `bsp_audio_*` | PCM 读写为阻塞调用,应放工作任务;codec 休眠前必须停止 PCM I/O;格式切换必须保留 BSP 内的 close/open 流程 | | 电池 | CW2017 的 SOC 与电压读取 | `bsp_battery_*` | 是可缺省能力;读数精度取决于电芯与 profile,不能等同于已标定结果 | | Wi-Fi | 按需 2.4 GHz STA 扫描 demo | `main/demo_wifi.c` | 仅扫描;不连接、不存凭证、不验证天线/射频表现 | | Bluetooth LE | 按需以 `FoloPassport` 名义做不可连接的 NimBLE 广播 | `main/demo_ble.c` | ESP32-C3 不支持蓝牙经典;射频范围、共存与功耗需实测 | -| 低功耗 | 两秒浅睡眠与五秒深睡眠,均以 RTC 定时器唤醒 | `main/demo_low_power.c` | 深睡眠会重启应用;当前 demo 只提供 RTC 定时器唤醒 | +| 低功耗 | 两秒浅睡眠与五秒深睡眠,均以 RTC 定时器唤醒 | `main/demo_low_power.c` | 两种模式都强制暂停 ES8311 并回读校验;浅睡眠恢复音频,深睡眠则先暂停 CW2017、释放 I2S/共享 I2C 引脚、休眠并保持 LCD 引脚,唤醒时重启应用;当前 demo 只提供 RTC 定时器唤醒 | | 共享总线 | ES8311 与 CW2017 共用 I2C0 | `bsp_i2c_*` | 所有设备复用 BSP 持有的总线;不能为扫描或新设备再创建同端口总线 | | 日志与烧录 | ESP32-C3 原生 USB Serial/JTAG | ESP-IDF console | GPIO18/19 保留给 USB;UART0 默认 TX GPIO21 与背光冲突 | 所有引脚、地址、面板参数和按键电压窗口只在 [`components/bsp/include/bsp_pins.h`](../components/bsp/include/bsp_pins.h) 定义。应用代码不得复制这些常量。完整引脚表、面板初始化、ADC 阈值、I2C 地址规则、音频时钟和内存说明见 [AI 硬件开发指南](hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md)。 -应用也可以使用 ESP-IDF 提供的定时器、FreeRTOS 任务和内部 Flash/NVS;番茄钟分支提供了 NVS 示例。Wi-Fi 和 Bluetooth LE 仍是 ESP-IDF 应用服务而非 BSP API:其菜单页面仅在打开时初始化对应协议栈、退出时释放。`demo/claude-buddy-port` 仍是更完整的 BLE 应用架构参考,不能替代对当前板卡天线、射频表现、功耗和共存行为的实测。当前产品与固件基线使用 8 MB Flash,包含 3 MB factory-app 分区,并固定保留受保护的 `cardid` 存储区。 +应用也可以使用 ESP-IDF 提供的定时器、FreeRTOS 任务和内部 Flash/NVS;番茄钟分支提供了 NVS 示例。Wi-Fi 和 Bluetooth LE 仍是 ESP-IDF 应用服务而非 BSP API:其菜单页面仅在打开时初始化对应协议栈、退出时释放。`demo/claude-buddy-port` 仍是更完整的 BLE 应用架构参考,不能替代对当前板卡天线、射频表现、功耗和共存行为的实测。默认自定义固件基线使用 8 MB Flash,只包含 NVS、PHY data,以及占用剩余空间的单个 factory-app 分区;用户固件可以替换成其它合法的 8 MB 布局。 ### 不属于当前能力契约的事项 @@ -66,6 +66,8 @@ FoloToy AI Passport 是一个开放式可穿戴 AI 硬件,本仓库是这款 A 每个 `demo/*` 分支都从基线演化出一个独立应用。它们的价值是展示具体问题的实现方式;新应用通常应从 `main` 建分支,按需参考,而不是把多个 demo 整体合并。 +`main` 上的菜单和 `demo_*.c` 页面同样只是硬件能力展示与验证界面,不是可直接使用的成品 UI。新开发应用必须根据自身需求重新设计并实现页面与交互流程,不能直接使用或照搬当前 demo 界面;BSP API、生命周期模式和已拆分的纯逻辑仍可按需复用。 + | 分支 | 展示的应用 | 值得复用的模式 | | --- | --- | --- | | `demo/stopwatch` | 秒表 | 最小计时应用、纯逻辑与 LVGL 分离、主机逻辑测试 | diff --git a/docs/contribution/commit-and-pr.md b/docs/contribution/commit-and-pr.md index ecdd05e..055ab38 100644 --- a/docs/contribution/commit-and-pr.md +++ b/docs/contribution/commit-and-pr.md @@ -10,7 +10,7 @@ - Use `feat`, `fix`, `docs`, `refactor`, `perf`, `test`, `chore`, `build`, or `ci`. Keep the subject at most 72 characters and omit the final period. - Keep each commit independently reviewable. Describe the final diff, not the debugging journey. - Review the complete diff, run applicable checks, and exclude credentials, generated firmware, and unrelated files. -- Update `docs/CHANGELOG.md` only for user-visible behavior, compatibility, or release-flow changes. +- Do not edit the paired changelog files in an ordinary feature, application, or documentation commit. Describe user-visible behavior, compatibility, and release-flow impact in the pull-request body; only a release-preparation change maintained before tagging aggregates those merged changes into both files. - Creating a commit does not authorize pushing, opening a PR, releasing, or merging. - Write durable product constraints, data formats, architecture decisions, and acceptance criteria back to their authoritative document. Do not preserve transient debugging notes. diff --git a/docs/contribution/commit-and-pr.zh_CN.md b/docs/contribution/commit-and-pr.zh_CN.md index 9361d79..6f14cdf 100644 --- a/docs/contribution/commit-and-pr.zh_CN.md +++ b/docs/contribution/commit-and-pr.zh_CN.md @@ -10,7 +10,7 @@ - `type` 使用 `feat`、`fix`、`docs`、`refactor`、`perf`、`test`、`chore`、`build` 或 `ci`;标题不超过 72 个字符,结尾不加句号。 - 一个 commit 只表达一个可独立 review 的逻辑变化,message 描述最终 diff,不记录调试过程。 - 提交前检查完整 diff,运行适用测试,并排除凭证、生成固件和无关文件。 -- 仅用户可见的行为、兼容性和发布流程变化需要更新 `docs/CHANGELOG.zh_CN.md`;内部重构、CI 维护、拼写修复和依赖锁刷新不强制记录。 +- 普通功能、应用和文档 commit 不修改中英文变更日志。用户可见行为、兼容性和发布流程影响写入 PR 正文;只有打 tag 前的发布准备变更,才把已合并内容统一汇总到两份变更日志。 - 不因创建 commit 自动获得 push、创建 PR、发布 Release 或合并的权限;这些外部操作由用户请求或明确工作流授权。 - 需求形成了需要长期维护的产品约束、数据格式、架构决定或验收标准时,写回对应设计/规范文档;临时讨论和调试记录不必落仓。 diff --git a/docs/contribution/doc-conventions.md b/docs/contribution/doc-conventions.md index 666927a..c8b63dd 100644 --- a/docs/contribution/doc-conventions.md +++ b/docs/contribution/doc-conventions.md @@ -15,6 +15,39 @@ These rules apply equally to human contributors and AI agents. Documentation is - Code, commands, paths, URLs, identifiers, and data fields remain unchanged between translations where appropriate. - The repository check rejects an unpaired document, a missing language switch, or CJK prose in an English default file. +## Vendored third-party documentation + +Preserve upstream documentation when copying a third-party component into the +repository. To exempt its original Markdown from local-link and bilingual +checks, explicitly register the component's directory in `VENDORED_DOC_ROOTS` +in [`tools/check_repo.py`](../../tools/check_repo.py). The registry is empty by +default. For example, after adding a component at `components/vendor_audio`: + +```python +VENDORED_DOC_ROOTS: tuple[str, ...] = ( + "components/vendor_audio", +) +``` + +Register an existing, concrete component directory using a repository-relative +path with `/` separators. Empty paths, the repository root, absolute paths, +`.` or `..` segments, and symlink directories are rejected. Matching uses whole +path segments: this entry does not exempt `components/vendor_audio_extra`. +Files linked outside the registered directory are not exempt. Do not register +broad first-party trees such as `components` or `docs`. + +Only upstream Markdown under the registered roots skips `check_markdown_links` +and `check_document_languages`. Keep those files in the normal repository scan: +secret patterns, unsanitized device QR links, and merge-conflict markers still +fail validation. Do not implement these exceptions through `.gitignore`, +`git_files()`, or `text_files()` filters. + +Record the component's upstream source URL, pinned version or commit, license, +and any local modifications in a project-maintained English/Chinese document +pair outside its exempt directory. Project-authored integration guides remain +subject to the normal language and link rules. Adding an exemption does not +require rewriting or translating the original upstream documents. + ## Task-based context - Every task starts with root `AGENTS.md` only. @@ -38,11 +71,16 @@ These rules apply equally to human contributors and AI agents. Documentation is Do not create empty document scaffolding without a concrete purpose. Register added documents in `docs/README.md` or their directory index and update links when moving or deleting files. +## Changelog ownership + +- Ordinary feature, application, and documentation pull requests leave `docs/CHANGELOG.md` and `docs/CHANGELOG.zh_CN.md` unchanged. They describe user-visible behavior, compatibility, and release-flow impact in the pull-request body and update the authoritative product or application documentation. +- During release preparation, the release maintainer reviews merged pull requests since the previous release, keeps only user-visible changes, and updates both changelog languages together before creating the tag. +- The release-preparation change places the released entries under a version-and-date heading and leaves a fresh `Unreleased` section. Existing entries under `Unreleased` are pending input for the next release and must be checked against the merged changes rather than copied blindly. + ## Writing, safety, and file operations - Explain rationale, boundaries, failure modes, and validation instead of restating source code. - State product facts and public hardware interfaces directly; omit provenance and source-availability commentary. - Enforce automatable rules in `tools/` and CI as well as documentation. -- Record user-visible behavior, compatibility, and release-flow changes in `docs/CHANGELOG.md`. - Never commit credentials, tokens, keys, authorization files, private keys, personal data, internal endpoints, or unsanitized device QR parameters. Run `./tools/validate.sh --static` before committing. - Preserve existing user changes and untracked files. Use recoverable deletion for user files, and confirm intent before deleting branches, tags, or remote references. diff --git a/docs/contribution/doc-conventions.zh_CN.md b/docs/contribution/doc-conventions.zh_CN.md index c01ca3e..1fd7d8d 100644 --- a/docs/contribution/doc-conventions.zh_CN.md +++ b/docs/contribution/doc-conventions.zh_CN.md @@ -14,6 +14,34 @@ - 新增、移动或删除任一语言文件时,必须同步处理配对文件和所有索引。 - `tools/check_repo.py` 与 CI 会拒绝缺少配对文件、缺少切换链接或英文默认页包含中文正文的变更。 +## 随仓库引入的第三方文档 + +把第三方组件复制到仓库时,应保留其上游原始文档。如需豁免其中 Markdown +的本地链接和双语检查,在 [`tools/check_repo.py`](../../tools/check_repo.py) +的 `VENDORED_DOC_ROOTS` 中显式登记组件目录。该列表默认为空。例如,引入位于 +`components/vendor_audio` 的组件后,可登记: + +```python +VENDORED_DOC_ROOTS: tuple[str, ...] = ( + "components/vendor_audio", +) +``` + +登记项必须是已存在的具体组件目录,使用相对仓库根目录的路径和 `/` 分隔符。 +空路径、仓库根目录、绝对路径、`.` 或 `..` 路径段以及符号链接目录均会被拒绝。 +匹配按完整路径段进行,因此此项不会豁免 `components/vendor_audio_extra`。 +链接到登记目录之外的文件也不豁免。不要登记 `components`、`docs` 等包含自有 +内容的大范围目录。 + +只有登记目录内的上游 Markdown 跳过 `check_markdown_links` 和 +`check_document_languages`。这些文件仍参加正常的仓库扫描:敏感凭证模式、 +未脱敏的设备二维码链接和合并冲突标记仍会导致校验失败。不得通过 `.gitignore`、 +`git_files()` 或 `text_files()` 过滤来实现这些豁免。 + +组件的上游来源 URL、固定版本或提交、许可证以及本地修改,应记录在豁免目录外、 +由项目维护的中英文配对文档中。项目自己编写的集成说明仍须遵守正常的双语和链接 +规则。添加豁免不要求改写或翻译第三方原始文档。 + ## 按任务加载上下文 - 所有任务只强制先读仓库根 `AGENTS.md`。 @@ -37,6 +65,12 @@ 不要创建只有目录说明而没有实际用途的空骨架。新增文档必须在 `docs/README.md` 或所属目录索引中登记;删除或移动文档时同步更新所有链接。 +## 变更日志所有权 + +- 普通功能、应用和文档 PR 不修改 `docs/CHANGELOG.md` 与 `docs/CHANGELOG.zh_CN.md`。用户可见行为、兼容性和发布流程影响写入 PR 正文,并同步更新对应的产品或应用权威文档。 +- 发布准备期间,发布负责人检查自上一版本以来已合并的 PR,只保留用户可见变化,并在创建 tag 前同时更新两种语言的变更日志。 +- 发布准备变更把本次发布条目归入带版本号和日期的标题,并留下新的 `Unreleased` 章节。现有 `Unreleased` 条目是下次发布的待核对输入,必须与实际合并内容核对,不能直接照搬。 + ## 写作与维护 - 中文版正文使用全角标点;代码、命令、路径、URL、标识符、YAML/JSON 字段和英文句子保持 ASCII 格式。 @@ -44,7 +78,6 @@ - 直接陈述产品事实和公开硬件接口,不加入来源及资料开放状态说明。 - 中英文双语文档必须保持章节和事实一致;只修改一侧时,在交付中明确另一侧是否需要同步。 - 能由脚本检查的规则必须落实到 `tools/` 和 CI,不能只写在文档里。 -- 用户可见行为、兼容性或发布流程变化记录到 `docs/CHANGELOG.zh_CN.md`;内部整理和拼写修复不强制记录。 ## 内容安全 diff --git a/docs/development/README.md b/docs/development/README.md index a46d04a..7ad3fc7 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -14,8 +14,9 @@ This directory contains AI Passport engineering rules and reusable workflows, gr - [environment-setup.md](engineering/environment-setup.md): clean-machine bootstrap for AI agents, including international and mainland China download routes. - [build-and-test.md](engineering/build-and-test.md): ESP-IDF build and validation. -- [protected-flash-layout.md](engineering/protected-flash-layout.md): mandatory merged-artifact and protected-partition layout. -- [coding-conventions.md](engineering/coding-conventions.md): source-code and resource conventions. +- [firmware-layout.md](engineering/firmware-layout.md): default and user-defined partition layouts and merged-artifact validation. +- [coding-conventions.md](engineering/coding-conventions.md): source-code and resource conventions, including Chinese font integration, blank/boxed text troubleshooting, and display acceptance. +- [lvgl-chinese-fonts.md](engineering/lvgl-chinese-fonts.md): step-by-step CJK configuration, font generation/linking, fallback examples, glyph checks, and troubleshooting. ## CI diff --git a/docs/development/README.zh_CN.md b/docs/development/README.zh_CN.md index 446d651..b026b0d 100644 --- a/docs/development/README.zh_CN.md +++ b/docs/development/README.zh_CN.md @@ -23,8 +23,9 @@ - [environment-setup.zh_CN.md](engineering/environment-setup.zh_CN.md):AI 在全新机器上的环境引导,包含国际与中国大陆下载线路。 - [build-and-test.zh_CN.md](engineering/build-and-test.zh_CN.md):构建与验证(ESP-IDF 命令、逻辑测试、改动验证要求)。 -- [protected-flash-layout.zh_CN.md](engineering/protected-flash-layout.zh_CN.md):合并产物与保护分区的强制布局。 -- [coding-conventions.zh_CN.md](engineering/coding-conventions.zh_CN.md):代码约定(语言风格、复用、注释、测试同步、资源约束等)。 +- [firmware-layout.zh_CN.md](engineering/firmware-layout.zh_CN.md):默认/用户自定义分区布局与合并产物验证。 +- [coding-conventions.zh_CN.md](engineering/coding-conventions.zh_CN.md):代码约定(语言风格、复用、注释、测试同步、资源约束等),包含中文字体接入、空白/方框排查与显示验收。 +- [lvgl-chinese-fonts.zh_CN.md](engineering/lvgl-chinese-fonts.zh_CN.md):CJK 配置、字体生成/链接、fallback 示例、缺字检查和故障排查的分步指南。 ## CI(ci) diff --git a/docs/development/ai-guide.md b/docs/development/ai-guide.md index 6531fc2..faa760c 100644 --- a/docs/development/ai-guide.md +++ b/docs/development/ai-guide.md @@ -47,9 +47,10 @@ Only reusable hardware capabilities belong in the BSP. Document blocking behavio - Button callbacks dispatch lightweight events only; move audio, storage, networking, and other slow work to worker tasks. - Stop tasks and timers that may access a page before deleting its screen. - Preserve menu `UP`/`DOWN`, `OK` click to enter, and page `OK` long-press to return unless the change explicitly redefines them. -- When the user asks to remove unnecessary components or go straight into a feature, you may drop the main menu and its elements and launch the target feature screen directly. Keep the `ui_pixel` theme (the sky background, grass, title plate, mascot, and ink-outlined panels) intact — do not delete the theme as part of the cleanup, or the screen will render blank. Reuse `ui_pixel_screen_create()` / `ui_pixel_panel_create()` so the feature keeps the shared visual identity. +- The `main` menu, `demo_*.c` pages, and `ui_pixel` visuals are a board-capability demonstration, not a production application shell. A newly developed application must redesign and implement its own screens and interaction flow from its product requirements instead of directly shipping or copying the current demo UI. Reuse BSP interfaces and applicable implementation patterns; inherit the demo menu or visual theme only when the developer explicitly requests it. A hardware-validation page that intentionally remains part of the baseline demo should still use `ui_pixel_screen_create()` / `ui_pixel_panel_create()` for consistency. - By default show the battery level in the top-right corner of a user interface (read via `bsp_battery_soc()`), unless the developer specifies a different placement or explicitly does not want it. Degrade gracefully when the reading is `-1` (unavailable) instead of drawing a number. Place it so it does not overlap the cloud decoration (`add_cloud`, around `x≈188, y≈8`) in the top-right; use the clear sky space rather than covering the cloud. - Budget internal RAM for images, fonts, networking, audio, LVGL, and task stacks; this board has no PSRAM. +- Treat Chinese text as a font-integration task, not just a string translation. Follow the [Chinese font checklist](engineering/coding-conventions.md#chinese-fonts-and-missing-glyphs) when changing text, fonts, sizes, themes, or dynamic content; never hide missing-glyph boxes as a fix. - Isolate testable state machines, protocols, timing, and layout calculations from ESP-IDF/LVGL and cover them with host tests. ## Material placement diff --git a/docs/development/ai-guide.zh_CN.md b/docs/development/ai-guide.zh_CN.md index 0331dce..c410c93 100644 --- a/docs/development/ai-guide.zh_CN.md +++ b/docs/development/ai-guide.zh_CN.md @@ -57,9 +57,10 @@ Natural-language requirement - 按键回调只派发轻量事件;录音、播放、存储和其他慢操作放到工作任务。 - 页面退出时先停止可能访问 UI 的任务或定时器,再删除 screen 并清空对象指针。 - 全局交互默认是菜单中 `UP`/`DOWN` 导航、`OK` 单击进入、页面中 `OK` 长按返回;改动时要明确说明。 -- 当用户要求删除不必要组件或直接进入某功能时,可以去掉主界面及其元素、直接载入目标功能界面;但必须**保留 `ui_pixel` 主题体系**(天空底色、草地、标题牌、吉祥物、墨色描边面板),不要把它当成"不必要组件"删掉,否则界面会渲染成空白。复用 `ui_pixel_screen_create()` / `ui_pixel_panel_create()`,让功能页保持统一的视觉身份。 +- 当前 `main` 菜单、`demo_*.c` 页面和 `ui_pixel` 视觉仅用于展示与验证板级能力,不是成品应用界面。新开发应用必须根据产品需求重新设计并实现页面与交互流程,不能直接交付或照搬当前 demo UI;可以复用 BSP 接口和适用的实现模式,只有开发者明确要求时才沿用 demo 菜单或视觉主题。若新增页面本身就是继续留在基础 demo 中的硬件验证页,则仍应使用 `ui_pixel_screen_create()` / `ui_pixel_panel_create()` 保持一致。 - 默认情况下,在用户界面的**右上角显示电量信息**(读取 `bsp_battery_soc()`),除非开发者明确指定其它位置或明确不需要。读值为 `-1`(不可用)时优雅降级,而不是画一个数字。位置要避开右上角已有的**白云装饰**(`add_cloud`,约 `x≈188, y≈8`),用空闲的蓝天区,不要盖住白云。 - 新图片、字体、网络栈、音频缓存、LVGL buffer 或任务栈都要评估内部 RAM;总空闲堆足够不代表存在足够大的连续内存块。 +- 中文显示属于字体集成任务,不只是翻译字符串。修改文案、字体、字号、主题或动态内容时,必须执行[中文字体检查清单](engineering/coding-conventions.zh_CN.md#中文字体与缺字排查);不得通过隐藏缺字方框来假装修复显示问题。 - 可测试的状态机、协议、计时和布局计算应与 ESP-IDF/LVGL 分离,优先加入主机逻辑测试。 ## 5. 素材放置(Material placement) diff --git a/docs/development/ci/CI-build-and-release.md b/docs/development/ci/CI-build-and-release.md index 50c25ea..4687d3f 100644 --- a/docs/development/ci/CI-build-and-release.md +++ b/docs/development/ci/CI-build-and-release.md @@ -6,7 +6,7 @@ `.github/workflows/build-firmware.yml` builds and publishes firmware for tags and supports manual dispatch. Ordinary branch pushes do not trigger it. Keep this page synchronized with the workflow. -The build job restores ccache, runs `./tools/validate.sh --firmware` with ESP-IDF 5.5.3 for ESP32-C3, verifies the bootloader at `0x0`, partition table at `0x8000`, application at `0x10000`, 8 MB Flash arguments, and the protected Flash layout, then uploads `FoloToy-AI-Passport-full.bin`. A separate least-privilege release job publishes that artifact only for a tag. +The build job restores ccache, runs `./tools/validate.sh --firmware` with ESP-IDF 5.5.3 for ESP32-C3, verifies the bootloader, partition table, and application at the offsets generated in `flash_args`, checks the 8 MB Flash arguments and configured partition layout, then uploads `FoloToy-AI-Passport-full.bin`. The repository default places these images at `0x0`, `0x8000`, and `0x10000`; user-defined partition tables may change the application offset. A separate least-privilege release job publishes that artifact only for a tag. All Actions are pinned to full commit SHAs. The build job has `contents: read`; only the tag release job receives `contents: write`. @@ -39,6 +39,26 @@ make sure the release title shows both. is visible in both the tag list and the release list. Do not rely on a human-readable body alone to carry the app name. +## Changelog preparation + +Ordinary feature, application, and documentation pull requests leave the paired +changelog files unchanged. Before creating and pushing a release tag, the +release maintainer: + +1. Identifies the previous release and reviews the pull requests merged since it, + together with the authoritative product and application documentation. +2. Collects user-visible features, fixes, compatibility changes, and release-flow + changes. Internal refactors, CI maintenance, typo fixes, and generated-file + refreshes are omitted. +3. Updates `docs/CHANGELOG.md` and `docs/CHANGELOG.zh_CN.md` together, places the + released entries under a `## - YYYY-MM-DD` heading, and leaves a fresh + `Unreleased` section before committing the release preparation. + +Treat any existing `Unreleased` entries as pending input: verify them against the +merged changes and the target release instead of copying them blindly. This +release-preparation change is the owner of the shared changelog write and must be +part of the commit that is tagged. + ## Release notes A tag-triggered release succeeds only when the merged firmware and its release @@ -55,8 +75,9 @@ things: interactions or hardware requirements of the release. Write the release notes in English (and a Simplified Chinese version where the -project is bilingual) and link them from the GitHub/GitLab release. Keep them -consistent with `docs/CHANGELOG.md` for user-visible behavior. +project is bilingual) and link them from the GitHub/GitLab release. Derive the +user-visible summary from the release-preparation changelog so the two remain +consistent. ## Related documents diff --git a/docs/development/ci/CI-build-and-release.zh_CN.md b/docs/development/ci/CI-build-and-release.zh_CN.md index 6ca9697..d2b77af 100644 --- a/docs/development/ci/CI-build-and-release.zh_CN.md +++ b/docs/development/ci/CI-build-and-release.zh_CN.md @@ -19,7 +19,7 @@ 1. **ccache 缓存恢复**:使用 `actions/cache` 缓存编译中间产物(`.ccache`),二次编译大幅提速。缓存 key 含 ref 与 commit SHA;缓存保留时间以仓库的 GitHub Actions 设置为准。 2. **编译与验证**(ESP-IDF 5.5.3 / esp32c3):运行与本地相同的 `./tools/validate.sh --firmware`。脚本使用 `sdkconfig.defaults` 和 `partitions.csv` 构建固件,再执行 `idf.py merge-bin`。 -3. **验证完整固件**:脚本逐字节确认 bootloader、partition-table 和 app 位于 `0x0`、`0x8000` 和 `0x10000`,确认 `flash_args` 使用 8 MB Flash,并完整检查受保护的 Flash 布局,最后输出 `build/FoloToy-AI-Passport-full.bin`。 +3. **验证完整固件**:脚本按 `flash_args` 生成的实际偏移逐字节确认 bootloader、partition-table 和 app,确认使用 8 MB Flash,并检查当前配置的分区布局,最后输出 `build/FoloToy-AI-Passport-full.bin`。仓库默认偏移为 `0x0`、`0x8000` 和 `0x10000`;用户自定义分区表时可以改变 app 偏移。 4. **上传 artifact**:每次成功构建都上传 `FoloToy-AI-Passport-full.bin`。普通分支只有从该分支手动运行 `workflow_dispatch` 才会构建;普通 push 不触发。 5. **发布 tag**:tag 构建完成后,独立 release job 下载上述 artifact,并创建 GitHub Release。 @@ -52,6 +52,18 @@ - **标题与 tag 保持一致**:用 `<版本>-<应用名>`,让应用名在 tag 列表和 Release 列表里都可见。不要只靠 人类可读的正文承载应用名。 +## 变更日志准备 + +普通功能、应用和文档 PR 不修改中英文变更日志。创建并推送发布 tag 前,发布负责人需要: + +1. 确认上一版本,并检查此后已合并的 PR,以及对应的产品和应用权威文档。 +2. 汇总用户可见功能、修复、兼容性变化和发布流程变化;忽略内部重构、CI 维护、拼写修复与生成文件刷新。 +3. 同时更新 `docs/CHANGELOG.md` 和 `docs/CHANGELOG.zh_CN.md`,把本次发布条目放入 + `## - YYYY-MM-DD` 标题下,保留一个新的 `Unreleased` 章节,再提交发布准备变更。 + +现有 `Unreleased` 条目只作为待核对输入:必须与实际合并内容及目标版本核对,不能直接照搬。该发布准备 +变更是共享变更日志的唯一写入方,并且必须包含在 tag 所指向的 commit 中。 + ## Release 说明 tag 触发的 Release 只有在合并固件与它的 Release 说明一起发布时才完整。发布 Release 后,要写一份 @@ -64,8 +76,8 @@ tag 触发的 Release 只有在合并固件与它的 Release 说明一起发布 - **使用(How to use / 使用)**:如何烧录(上方在线刷机工具),以及本次 Release 的关键交互或硬件 要求。 -用英文写 Release 说明(项目双语时再配一份简体中文),并在 GitHub/GitLab Release 上链接它们。对 -用户可见的行为,保持与 `docs/CHANGELOG.md` 一致。 +用英文写 Release 说明(项目双语时再配一份简体中文),并在 GitHub/GitLab Release 上链接它们。 +用户可见摘要以发布准备阶段的变更日志为依据,确保两者一致。 ## 相关文件 diff --git a/docs/development/engineering/build-and-test.md b/docs/development/engineering/build-and-test.md index 8b5f8bd..1549e80 100644 --- a/docs/development/engineering/build-and-test.md +++ b/docs/development/engineering/build-and-test.md @@ -7,10 +7,17 @@ Use ESP-IDF 5.5.3. On a clean machine or when the toolchain is missing, follow the [environment bootstrap](environment-setup.md) first. -> Prefer `./tools/validate.sh --firmware` for firmware builds and flash its -> verified `build/FoloToy-AI-Passport-full.bin` at offset `0x0` only when the -> target is blank or the merged byte range ends before protected `cardid`. -> On a provisioned device, use segmented `idf.py flash`. Treat +> **No original-firmware backup is required before downloading (flashing) new +> firmware to the device.** Reading out the installed firmware is not a +> prerequisite. Flashing replaces the installed firmware and does not provide +> automatic restoration of it. This does not mean user data is preserved: if +> you need existing settings or records, export or otherwise save them first. +> See [flashing and stored data](firmware-layout.md#flashing-and-stored-data). + +> Prefer `./tools/validate.sh --firmware` for firmware builds. Flash its +> verified `build/FoloToy-AI-Passport-full.bin` at offset `0x0` for a blank +> device or an intentional complete refresh. The merged image may reset NVS; +> use segmented `idf.py flash` when existing NVS state must be preserved. Treat > `idf.py build` and `idf.py flash` as incremental development commands, not the > default delivery path. @@ -56,7 +63,7 @@ exclusions. The tracked `dependencies.lock` pins Managed Component resolution. After changing an `idf_component.yml`, regenerate the lock with ESP-IDF 5.5.3, review version changes, and commit it with the manifest. An ordinary build must not leave an unexplained lock-file diff. -Firmware validation uses a fresh temporary build directory and an isolated `sdkconfig` generated from the tracked defaults. It does not consume or overwrite a developer's root `sdkconfig`, and it copies only the verified merged image to `build/FoloToy-AI-Passport-full.bin`. The gate also enforces the [protected Flash layout](protected-flash-layout.md): the protected `cardid` address, application size, partition-table MD5, and absence of device-specific identity data. +Firmware validation uses a fresh temporary build directory and an isolated `sdkconfig` generated from the tracked defaults. It does not consume or overwrite a developer's root `sdkconfig`, and it copies only the verified merged image to `build/FoloToy-AI-Passport-full.bin`. The gate also validates the [configured firmware layout](firmware-layout.md): image offsets from `flash_args`, partition-table MD5, bounds and non-overlap, and an application that starts in and fits its configured app partition. User-defined partition layouts are allowed. The baseline also has a hardware-independent logic test: @@ -71,7 +78,7 @@ Use the unified validation entry point: ```bash ./tools/validate.sh --static # repository checks, workflows, links, secrets, host tests -./tools/validate.sh --firmware # build, merge-bin, offsets, and protected layout +./tools/validate.sh --firmware # build, merge-bin, offsets, and configured layout ./tools/validate.sh # complete gate; requires an activated ESP-IDF environment ``` diff --git a/docs/development/engineering/build-and-test.zh_CN.md b/docs/development/engineering/build-and-test.zh_CN.md index 6c5af47..492c377 100644 --- a/docs/development/engineering/build-and-test.zh_CN.md +++ b/docs/development/engineering/build-and-test.zh_CN.md @@ -7,10 +7,15 @@ 使用 ESP-IDF 5.5.3。全新机器或缺少工具链时,先按 [环境引导](environment-setup.zh_CN.md)完成安装。 -> 固件编译优先运行 `./tools/validate.sh --firmware`,烧录优先把验证通过的 -> `build/FoloToy-AI-Passport-full.bin` 写入空白设备;对已有身份的设备,只有合并文件 -> 在保护区 `cardid` 之前结束时才可从 `0x0` 直刷,其余情况使用分段 -> `idf.py flash`。`idf.py build` 和 +> **向设备下载(烧录)新固件前,无需备份设备内部原有固件。** 不要求先读出 +> 原固件,也不把原固件备份作为烧录前置条件。烧录会覆盖原固件,不会自动恢复 +> 原固件。这不代表用户数据会被保留:如果需要保留已有设置或记录,应事先 +> 导出或另行保存。详见[烧录与已存数据](firmware-layout.zh_CN.md#烧录与已存数据)。 + +> 固件编译优先运行 `./tools/validate.sh --firmware`。空白设备初始化或有意完整 +> 刷新时,把验证通过的 `build/FoloToy-AI-Passport-full.bin` 从 `0x0` 写入; +> 合并镜像可能重置 NVS,需要保留已有 NVS 状态时使用分段 `idf.py flash`。 +> `idf.py build` 和 > `idf.py flash` 只作为增量开发命令,不作为默认交付方式。 ```bash @@ -49,7 +54,7 @@ ccache 缓存位于 `build/` 之外,因此 `idf.py fullclean` 和临时验证 仓库提交 `dependencies.lock` 以固定 ESP-IDF Managed Components 的解析结果。修改 `idf_component.yml` 后必须使用 ESP-IDF 5.5.3 重新生成锁文件、review 版本变化并与 manifest 一起提交;普通构建不应产生未提交的锁文件差异。 -固件门禁使用全新的临时构建目录,并从仓库 `sdkconfig.defaults` 生成隔离的 `sdkconfig`。它不会读取或覆盖开发者根目录的 `sdkconfig`,只把验证通过的合并镜像复制到 `build/FoloToy-AI-Passport-full.bin`。门禁同时强制检查[受保护的 Flash 布局](protected-flash-layout.zh_CN.md):受保护的 `cardid` 地址、应用大小、分区表 MD5 以及单机身份数据不入包。 +固件门禁使用全新的临时构建目录,并从仓库 `sdkconfig.defaults` 生成隔离的 `sdkconfig`。它不会读取或覆盖开发者根目录的 `sdkconfig`,只把验证通过的合并镜像复制到 `build/FoloToy-AI-Passport-full.bin`。门禁同时验证[当前配置的固件布局](firmware-layout.zh_CN.md):从 `flash_args` 读取镜像偏移,检查分区表 MD5、边界和不重叠,并确认应用从所配置的 app 分区起点开始且未超出分区。允许用户自定义分区布局。 当前基线含一个可独立运行的纯逻辑测试: @@ -64,7 +69,7 @@ cc -std=c11 -Wall -Wextra -Werror -Imain \ ```bash ./tools/validate.sh --static # 仓库一致性、workflow、文档链接、敏感信息、host tests -./tools/validate.sh --firmware # ESP-IDF build、merge-bin、偏移与保护布局校验 +./tools/validate.sh --firmware # ESP-IDF build、merge-bin、偏移与当前布局校验 ./tools/validate.sh # 完整验证 ``` diff --git a/docs/development/engineering/coding-conventions.md b/docs/development/engineering/coding-conventions.md index 8886de3..14ec178 100644 --- a/docs/development/engineering/coding-conventions.md +++ b/docs/development/engineering/coding-conventions.md @@ -5,8 +5,8 @@ # Coding Conventions - Write C with four-space indentation and K&R braces, following neighboring files. Use `snake_case`, `BSP_*` public constants, `s_` file-local state, `bsp_` public BSP APIs, and `demo__` demo entry points. Prefer `static` for internal symbols. -- Keep UI text and default documentation in English. Explanatory source comments may use Chinese while retaining established English technical terms. -- The baseline enables only LVGL Montserrat 14 and 20, which do not contain CJK glyphs. Chinese UTF-8 text therefore renders as missing-glyph boxes; changing source-file encoding does not fix it. Before adding Chinese UI text, compile and select a CJK font that covers every displayed character, prefer a glyph subset over a full font, configure a suitable fallback for mixed-language text, budget Flash and internal RAM, and verify the result on the device. +- Keep baseline-demo UI text and default documentation in English. Application UI may use Chinese when its font support is implemented and verified. Explanatory source comments may use Chinese while retaining established English technical terms. +- Before adding Chinese UI text, complete the [font checklist](#chinese-fonts-and-missing-glyphs); changing strings to UTF-8 alone does not add missing glyphs. - Put reusable hardware behavior in `components/bsp`; keep menus, animations, product interaction, and validation pages in `main`. - The `ui_pixel` theme (sky background, grass, title plate, mascot, ink-outlined panels) is part of the user interface, not a removable component. When trimming components or routing straight to a feature screen, keep the theme and build the screen through `ui_pixel_screen_create()` / `ui_pixel_panel_create()`. - Show the battery level in the top-right corner of a user interface by default, unless the developer specifies a different placement or explicitly does not want it. Read it from `bsp_battery_soc()` (and `bsp_battery_mv()` where useful); render it as a small battery indicator or percentage in the top-right area of the screen, and degrade gracefully when it reads `-1` (unavailable). Place it where it does not overlap the existing cloud decoration (`add_cloud`, around `x≈188, y≈8`): use the clear sky space beside or below the cloud, or the very top-right edge, rather than covering the cloud. @@ -15,3 +15,45 @@ - If adding a cache, define expiration and cleanup unless durable retention is explicitly justified. - The ESP32-C3 has no PSRAM. Review internal RAM and largest-contiguous-block impact before increasing LVGL buffers, audio allocations, network state, or task stacks. - **Watch power consumption.** This is a wearable powered by a small battery; keep it efficient. Avoid keeping the screen lit for long periods: dim or turn off the backlight, and return to a low-power state (light/deep sleep) whenever the screen is idle, so the device is not left displaying a bright screen while doing nothing. See the guidance on sleep in [`../hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md`](../../hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md). + +## Chinese fonts and missing glyphs + +For configuration, converter commands, CMake integration, safe fallback code, and glyph-check examples, follow the [detailed LVGL Chinese text guide](lvgl-chinese-fonts.md). + +The baseline enables Montserrat 14 and 20 in [`sdkconfig.defaults`](../../../sdkconfig.defaults); neither contains Chinese glyphs. A correct UTF-8 string can therefore appear as boxes or blank text. Serial-console output, an installed computer font, and a successful firmware build do not prove that LVGL can render that text. + +### Before implementing or changing Chinese UI + +1. **Define coverage.** Collect all displayed text: titles, buttons, hints, empty/error states, units, punctuation, and dynamic content. Include Latin letters, digits, full-width punctuation, and any `LV_SYMBOL_*` icons in the chosen font or fallback chain. Regenerate each affected size/subset when text changes. A built-in CJK subset or a subset extracted from fixed UI strings does not guarantee arbitrary Chinese names, Wi-Fi SSIDs, or server/user input; define the supported character set and an explicit unsupported-character policy. +2. **Generate reproducible assets.** Select a licensed font whose source actually contains the required glyphs. Prefer a subset at the sizes needed by the application instead of embedding an entire font family. Keep reusable sources/generated files under `assets/fonts/` and record the license, converter version, command, character inventory, size, and bit depth in the [assets documentation](../../../assets/README.md). Use output compatible with the LVGL version pinned in [`dependencies.lock`](../../../dependencies.lock) (currently 9.5.0). See the [official font converter](https://github.com/lvgl/lv_font_conv) for generation options; this baseline does not bundle an application-specific Chinese font. +3. **Compile and select the font.** Add the generated `.c` file to the consuming component's CMake `SRCS`, declare its exported symbol with `LV_FONT_DECLARE`, and assign it to the actual text widget/part. Copying a TTF/OTF or `.c` into `assets/` does not automatically compile, load, or select it. Check the generated `sdkconfig` has `CONFIG_LV_TXT_ENC_UTF8=y`; changing defaults alone does not necessarily update an existing configuration (see [build and test](build-and-test.md)). +4. **Check style overrides and fallback.** Changing the default font or a screen's inherited font does not override explicit child fonts. [`main/ui_pixel.c`](../../../main/ui_pixel.c) sets a local font in `ui_pixel_label()` and explicitly uses Montserrat 20 for its title; menu/demo labels also select fonts directly. Audit titles, labels, widget parts, and focused/pressed/disabled states. For mixed text, use a font containing all required glyphs or a deliberate fallback chain. Do not cast away `const` to modify Flash-resident font descriptors, create fallback cycles, or free a font while widgets still use it. +5. **Budget resources.** Inspect Flash/static RAM after generation and free heap/largest free block at runtime, including when networking is active. Constant bitmap font data can reside in Flash; runtime font loading, decoding, and caches may need RAM. Do not blindly enlarge the LVGL heap or display buffers to treat missing glyphs; more memory cannot supply glyphs absent from the font. + +For example, after generating and linking `app_font_20` with the required glyphs, select it explicitly. This symbol is illustrative, not a font supplied by this repository. Run object operations in the LVGL task or while holding `bsp_lvgl_lock()`: + +```c +LV_FONT_DECLARE(app_font_20); + +/* Inside the application's UI creation function. */ +lv_obj_t *label = lv_label_create(parent); +lv_obj_set_style_text_font(label, &app_font_20, LV_PART_MAIN | LV_STATE_DEFAULT); +lv_label_set_text(label, "\u4E2D\u6587 ABC 123"); +``` + +### Troubleshooting order + +| Symptom | Check first | +| --- | --- | +| Latin text works; Chinese is blank or boxed | Actual widget font and its fallback coverage, UTF-8 input, and `CONFIG_LV_TXT_ENC_UTF8`; disabling `CONFIG_LV_USE_FONT_PLACEHOLDER` only hides the missing-glyph indicator, not the defect | +| Only some characters or new text fail | Missing subset entries, punctuation, each font size, and dynamic text outside the supported set; regenerate and relink the affected assets | +| Body text works but titles/buttons or selected states fail | Explicit local fonts, theme/state overrides, and the font on the widget part that draws the text | +| Glyph coverage is correct but text is invisible or cut off | Text color/opacity, hidden flags, label size, line height, parent clipping, and draw/allocation errors; do not assume every blank label is a font defect | + +### Required acceptance + +- Check every required printable Unicode code point against each font/fallback chain actually used. With the pinned LVGL API, `lv_font_get_glyph_dsc()` must succeed and `is_placeholder` must be false; a placeholder is not coverage. Decode UTF-8 into code points rather than testing individual bytes. Record uncovered code points and add a repeatable coverage check alongside the application's font-generation pipeline. +- On the device, verify all pages and error/empty states, Chinese/Latin/digit/punctuation/icon mixtures, different sizes and interaction states, long text, and dynamic content both inside and outside the declared supported set. Check for boxes, blanks, clipping, and fallback baseline/line-height mismatches; do not accept one successful sample label as whole-application validation. +- Report the tested text/character set, font sizes, and resource changes. The baseline's host tests do not validate a derivative application's font coverage or screen output. Without a physical-device check, report `Device tests: NOT RUN` and explicitly list Chinese rendering under `Unverified`. + +Font selection and fallback semantics: [LVGL 9.5 font overview](https://docs.lvgl.io/9.5/main-modules/fonts/overview.html). Missing-glyph handling: [LVGL 9.5 implementation](https://github.com/lvgl/lvgl/blob/v9.5.0/src/font/lv_font.c). diff --git a/docs/development/engineering/coding-conventions.zh_CN.md b/docs/development/engineering/coding-conventions.zh_CN.md index 5c5f8c3..39946da 100644 --- a/docs/development/engineering/coding-conventions.zh_CN.md +++ b/docs/development/engineering/coding-conventions.zh_CN.md @@ -4,8 +4,8 @@ # 代码约定(Coding Conventions) -- **语言/风格**:C 用四空格缩进 + K&R 大括号,跟随相邻文件;函数/局部变量 `snake_case`,公开硬件常量 `BSP_*`,文件内状态 `s_` 前缀;BSP API 用 `bsp_` 前缀,demo 入口 `demo__`;内部符号优先 `static`。UI 文案用英文,解释性注释可用中文;保留记录硬件寄存器值与内存约束的注释。 -- **中文方框字陷阱**:当前基线只启用 LVGL Montserrat 14 和 20,这些字体不包含 CJK glyph。即使源码和字符串均为 UTF-8,中文也会显示为缺字方框,修改源文件编码不能解决。添加中文 UI 前,必须编译并选用覆盖全部实际字符的 CJK 字体,优先生成 glyph 子集而非引入完整字库;中英文混排时配置合适的 fallback,同时核对 Flash、内部 RAM 占用并在真机逐字验证。 +- **语言/风格**:C 用四空格缩进 + K&R 大括号,跟随相邻文件;函数/局部变量 `snake_case`,公开硬件常量 `BSP_*`,文件内状态 `s_` 前缀;BSP API 用 `bsp_` 前缀,demo 入口 `demo__`;内部符号优先 `static`。基础 demo UI 文案与默认文档用英文;应用 UI 可以使用中文,但必须实现并验证字体支持。解释性注释可用中文并保留通用英文技术术语;保留记录硬件寄存器值与内存约束的注释。 +- **中文空白/方框陷阱**:添加中文 UI 前必须完成[字体检查清单](#中文字体与缺字排查);仅把字符串改成 UTF-8 不会补齐缺失的字形。 - **复用既有组件**:可复用硬件逻辑放 `components/bsp`;菜单/动画/业务交互/验证页面放 `main`。不要另造轮子,遵循既有 BSP API。 - **主题不是可删组件**:`ui_pixel` 主题体系(天空底色、草地、标题牌、吉祥物、墨色描边面板)属于用户界面的一部分,不是可删除的"不必要组件"。精简组件或直接载入功能界面时,保留该主题,并通过 `ui_pixel_screen_create()` / `ui_pixel_panel_create()` 建屏。 - **默认右上角电量**:用户界面在没有默认要求的情况下,默认在**右上角显示电量信息**;除非开发者明确指定其它位置或明确不需要。电量读取 `bsp_battery_soc()`(需要时用 `bsp_battery_mv()`),以小型电池图标或百分比呈现在屏幕右上区域;读值为 `-1`(不可用)时优雅降级,不要画一个数字。**位置不能和右上角已有的白云装饰冲突**(`add_cloud`,约 `x≈188, y≈8`):放在白云旁边或下方的空闲蓝天区,或屏幕最右上边角,不要盖住白云。 @@ -18,3 +18,45 @@ - **缓存组件**:若引入缓存组件(如 NVS 缓存、内存缓存等),默认设置过期时间;长期缓存需说明保留原因、过期风险与清理机制。当前固件不含需要 TTL 约束的缓存,无需特别处理。 - **资源约束**:ESP32-C3 无 PSRAM,不增加 LVGL buffer / 音频分配 / 任务栈前先核对内部 RAM;足够的总空闲堆不保证有足够大连续块。 - **关注功耗**:本设备是小电池供电的可穿戴产品,编写固件时要留意功耗。避免让屏幕长时间点亮:屏幕空闲时调暗或关闭背光,并及时回到低功耗状态(light/deep sleep),不要让它无事可做地一直亮着。睡眠相关指引见 [`../hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md`](../../hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md)。 + +## 中文字体与缺字排查 + +配置项、转换命令、CMake 接入、安全 fallback 代码和缺字检查示例见 [LVGL 中文显示详细指南](lvgl-chinese-fonts.zh_CN.md)。 + +基线在 [`sdkconfig.defaults`](../../../sdkconfig.defaults) 中启用 Montserrat 14 和 20,两者都不包含中文字形。因此,即使字符串是正确的 UTF-8,中文仍可能显示为方框或空白。串口能打印中文、电脑安装了中文字体、固件编译成功,都不能证明 LVGL 能显示这些文字。 + +### 开发或修改中文 UI 前 + +1. **明确字符范围。** 收集所有显示文案,包括标题、按钮、提示、空状态/错误状态、单位、标点和动态内容。所选字体或 fallback 链必须覆盖实际使用的英文字母、数字、全角标点以及 `LV_SYMBOL_*` 图标。文案变化时,重新生成受影响的各字号/子集。内置 CJK 子集或从固定 UI 文案提取的子集不保证覆盖任意中文姓名、Wi-Fi SSID、服务器/用户输入;必须声明支持的字符范围和明确的超范围字符处理策略。 +2. **生成可复现的素材。** 选用授权允许且源字库确实包含所需字形的字体。优先按应用实际字号生成子集,不直接塞入整套字体家族。可复用源文件/生成文件放在 `assets/fonts/`,并在[素材文档](../../../assets/README.zh_CN.md)记录授权、转换工具版本、命令、字符清单、字号和位深。生成结果须兼容 [`dependencies.lock`](../../../dependencies.lock) 锁定的 LVGL 版本(当前为 9.5.0)。生成选项见[官方字体转换工具](https://github.com/lvgl/lv_font_conv);本基线不自带应用专用中文字库。 +3. **编译并实际选用字体。** 把生成的 `.c` 加入使用方组件的 CMake `SRCS`,用 `LV_FONT_DECLARE` 声明导出的字体符号,再绑定到实际绘制文字的控件/部件。只把 TTF/OTF 或 `.c` 复制进 `assets/`,不会自动完成编译、加载或选用。检查生成的 `sdkconfig` 中 `CONFIG_LV_TXT_ENC_UTF8=y`;仅修改默认值不一定更新已有配置(见[构建与验证](build-and-test.zh_CN.md))。 +4. **检查样式覆盖与 fallback。** 修改默认字体或 screen 上可继承的字体,并不会覆盖子控件显式指定的字体。[`main/ui_pixel.c`](../../../main/ui_pixel.c) 的 `ui_pixel_label()` 会设置局部字体,标题明确使用 Montserrat 20;菜单/demo 标签也有直接选用字体的代码。逐项检查标题、标签、控件部件及焦点/按下/禁用状态。混排可使用覆盖全部所需字形的字体,或明确配置 fallback 链。不得通过强制去掉 `const` 来修改 Flash 中的字体描述符,不得形成 fallback 环路,也不得在控件仍使用字体时释放它。 +5. **评估资源。** 生成后检查 Flash/静态 RAM,运行时检查 free heap/largest free block,并包含网络同时启用的场景。常量位图字体数据可以驻留 Flash;动态加载、解码和缓存仍可能消耗 RAM。不要为解决缺字而盲目扩大 LVGL 内存池或显示缓冲;更多内存不会生成字库中不存在的字形。 + +例如,生成并链接包含所需字形的 `app_font_20` 后,显式选用它。此符号仅作示例,不是仓库已经提供的字体。对象操作必须在 LVGL 任务中执行,或持有 `bsp_lvgl_lock()`: + +```c +LV_FONT_DECLARE(app_font_20); + +/* Inside the application's UI creation function. */ +lv_obj_t *label = lv_label_create(parent); +lv_obj_set_style_text_font(label, &app_font_20, LV_PART_MAIN | LV_STATE_DEFAULT); +lv_label_set_text(label, "\u4E2D\u6587 ABC 123"); +``` + +### 排查顺序 + +| 现象 | 优先检查 | +| --- | --- | +| 英文正常,中文空白或方框 | 控件实际字体及 fallback 覆盖、UTF-8 输入和 `CONFIG_LV_TXT_ENC_UTF8`;关闭 `CONFIG_LV_USE_FONT_PLACEHOLDER` 只会隐藏缺字提示,不会修复缺字 | +| 只有部分字符或新文案异常 | 子集漏字、标点、各字号字库及超出支持范围的动态内容;重新生成并链接受影响的素材 | +| 正文正常,标题/按钮或选中状态异常 | 局部显式字体、主题/状态覆盖,以及真正绘制文字的控件部件所用字体 | +| 字形覆盖正确,但文字不可见或被截断 | 文字颜色/透明度、隐藏标志、标签尺寸、行高、父容器裁剪及绘制/内存分配错误;不能把所有空白标签都认定为字库问题 | + +### 必须完成的验收 + +- 对实际使用的每个字体/fallback 链检查全部所需可打印 Unicode 码点。在当前锁定的 LVGL API 中,`lv_font_get_glyph_dsc()` 必须成功且 `is_placeholder` 为 false;占位字形不算覆盖。应先将 UTF-8 解码为码点,不能逐字节检查。记录未覆盖的码点,并在应用的字体生成流程中加入可重复执行的覆盖检查。 +- 真机检查所有页面、错误/空状态,中英数/标点/图标混排,不同字号和交互状态、长文本,以及支持范围内外的动态内容。确认无方框、空白、裁剪和 fallback 基线/行高错位;不能只凭一个测试标签显示成功就认定整个应用通过。 +- 交付时记录测试文案/字符范围、字号与资源变化。基线 host tests 不会验证衍生应用的字库覆盖或屏幕输出。没有进行真机检查时,报告 `Device tests: NOT RUN`,并在 `Unverified` 中明确列出中文显示。 + +字体选择与 fallback 语义见 [LVGL 9.5 字体概览](https://docs.lvgl.io/9.5/main-modules/fonts/overview.html),缺字处理见 [LVGL 9.5 实现](https://github.com/lvgl/lvgl/blob/v9.5.0/src/font/lv_font.c)。 diff --git a/docs/development/engineering/firmware-layout.md b/docs/development/engineering/firmware-layout.md new file mode 100644 index 0000000..ad07ef6 --- /dev/null +++ b/docs/development/engineering/firmware-layout.md @@ -0,0 +1,73 @@ +

+ 简体中文 · English +

+ +# Firmware Layout + +This repository is a minimal base for user-defined firmware targeting an +ESP32-C3 with 8 MB Flash. Its default does not reserve product-specific +identity, OTA, or unused data partitions. + +## Default layout + +The default partition table contains exactly: + +| Partition | Type/subtype | Offset | Size | Purpose | +| --- | --- | ---: | ---: | --- | +| `nvs` | data/NVS | `0x9000` | `0x6000` | ESP-IDF and application key-value storage | +| `phy_init` | data/PHY | `0xF000` | `0x1000` | PHY initialization data | +| `factory` | app/factory | `0x10000` | `0x7F0000` | The single application image; all remaining Flash | + +The default has no OTA slots. This is a starting point, not a restriction on +user firmware. + +## Custom layouts + +Users may edit `partitions.csv` to resize, move, add, or remove partitions for +their application. A custom table may use OTA slots, filesystem/resource +partitions, or other application-specific data. Keep the 8 MB device boundary, +avoid overlaps, and make sure the application image is flashed at the start of +an app partition large enough to contain it. When a derivative changes its +layout, update that project's documentation and flashing instructions. + +## Enforced validation + +Run: + +```bash +./tools/validate.sh --firmware +``` + +The check builds in an isolated directory, creates the merged image, reads the +configured image offsets from `flash_args`, validates the partition-table MD5, +partition bounds, unique labels, and non-overlap, then ensures the application +offset matches an app partition large enough to contain it. It intentionally +does not require the default partition list. CI runs the same gate. + +Upload only `build/FoloToy-AI-Passport-full.bin`; the similarly named app-only +`build/FoloToy-AI-Passport.bin` does not contain the bootloader or partition +table. + +## Flashing and stored data + +> **No backup of the firmware already installed on the device is required +> before downloading (flashing) new firmware.** Do not make reading out the +> original firmware or saving a full-Flash dump a prerequisite for this +> workflow. The new firmware replaces the original firmware; this workflow +> does not retain an automatic rollback copy or promise that the original +> firmware can be restored. + +Firmware and user data are different. If existing NVS settings, application +records, or files must be kept, export or otherwise save them before flashing +using a method supported by that application. Not requiring an original-firmware +backup does not guarantee data preservation or authorize a full-chip erase. + +The verified merged image is written from `0x0`. Because the merged file pads +the gaps between images, flashing it can reset the NVS and PHY data regions. +Use the merged image for blank-device provisioning or an intentional complete +refresh. During normal development, use segmented `idf.py flash` when existing +NVS state should be preserved; this also requires a compatible partition layout +and flash targets that do not overwrite those data regions. `idf.py erase-flash` +erases all user data. Do not add it as a routine prerequisite: use it only when +a complete erase is explicitly intended and any data that must be kept has +been saved. diff --git a/docs/development/engineering/firmware-layout.zh_CN.md b/docs/development/engineering/firmware-layout.zh_CN.md new file mode 100644 index 0000000..7cb7071 --- /dev/null +++ b/docs/development/engineering/firmware-layout.zh_CN.md @@ -0,0 +1,59 @@ +

+ 简体中文 · English +

+ +# 固件布局 + +本仓库是供用户自定义固件使用的最小基础示例,目标为带 8 MB Flash 的 +ESP32-C3。默认布局不预留产品专用身份、OTA 或未使用的数据分区。 + +## 默认布局 + +默认分区表只包含: + +| 分区 | 类型/子类型 | 偏移 | 大小 | 用途 | +| --- | --- | ---: | ---: | --- | +| `nvs` | data/NVS | `0x9000` | `0x6000` | ESP-IDF 与应用键值存储 | +| `phy_init` | data/PHY | `0xF000` | `0x1000` | PHY 初始化数据 | +| `factory` | app/factory | `0x10000` | `0x7F0000` | 唯一应用镜像,占用全部剩余 Flash | + +默认布局没有 OTA 槽;它只是起点,不限制用户固件。 + +## 自定义布局 + +用户可以根据应用需要编辑 `partitions.csv`,调整分区大小和偏移,也可以增加或 +删除分区。自定义表可以包含 OTA 槽、文件系统/资源分区或其它应用专用数据。 +布局应保持在 8 MB 设备边界内、不得重叠,应用镜像的烧录偏移必须是某个容量 +足够的 app 分区起点。派生项目改变布局时,应同步更新该项目的文档与烧录说明。 + +## 强制验证 + +执行: + +```bash +./tools/validate.sh --firmware +``` + +脚本会在隔离目录中构建并生成合并镜像,从 `flash_args` 读取实际镜像偏移, +校验分区表 MD5、分区边界、标签唯一性和分区不重叠,并确认应用偏移对应一个 +容量足够的 app 分区。门禁不会强制要求默认分区列表。CI 执行同一门禁。 + +只上传 `build/FoloToy-AI-Passport-full.bin`。名称相近的应用单镜像 +`build/FoloToy-AI-Passport.bin` 不包含 bootloader 和分区表。 + +## 烧录与已存数据 + +> **向设备下载(烧录)新固件前,无需备份设备内部原有固件。** 本流程不要求 +> 先读出原固件,也不把保存整片 Flash 镜像作为前置条件。新固件会覆盖原固件; +> 本流程不会保留可自动回滚的副本,也不承诺能够恢复原固件。 + +固件本体与用户数据不同。如果需要保留已有 NVS 设置、应用记录或文件,应在 +烧录前通过原应用支持的方式导出或另行保存。无需备份原固件,不代表用户数据 +一定保留,也不代表可以默认执行全片擦除。 + +验证通过的合并镜像从 `0x0` 写入。合并文件会对各镜像之间的空隙做填充,因此 +烧录时可能重置 NVS 与 PHY data 区域。空白设备初始化或有意完整刷新时使用合并 +镜像;日常开发若要保留已有 NVS 状态,应使用分段 `idf.py flash`,并且要求分区 +布局兼容、烧录目标不会覆盖这些数据区域。`idf.py erase-flash` 会擦除全部用户 +数据,不应作为常规前置步骤;仅在明确需要全片擦除且已保存需要保留的数据时 +执行。 diff --git a/docs/development/engineering/lvgl-chinese-fonts.md b/docs/development/engineering/lvgl-chinese-fonts.md new file mode 100644 index 0000000..9e4b613 --- /dev/null +++ b/docs/development/engineering/lvgl-chinese-fonts.md @@ -0,0 +1,164 @@ +

+ 简体中文 · English +

+ +# LVGL Chinese Text: Integration and Troubleshooting + +Use this guide when adding Chinese text, changing fonts/sizes, or displaying user/network content. The [coding checklist](coding-conventions.md#chinese-fonts-and-missing-glyphs) defines acceptance; this page provides the integration procedure for the LVGL 9.5.0 version pinned in this repository. These are application examples, not changes already enabled in the baseline. + +## 1. Keep encoding, coverage, and style selection separate + +Correct rendering requires all of the following: + +| Layer | Required condition | Typical failure | +| --- | --- | --- | +| Text input | Valid UTF-8, with no truncated multibyte characters | Corrupted text even with the correct font | +| Font asset | Each requested Unicode code point exists in the font or fallback chain | Chinese is blank/boxed while Latin text works | +| Build integration | Font source is compiled, linked, and enabled | Undefined font symbol or the intended font never being used | +| Widget style | The text-drawing part actually selects that font in the active state | Only titles, popups, or selected items fail | +| Layout/rendering | Visible color/opacity, sufficient space, valid font lifetime and draw memory | Clipped or invisible text despite correct coverage | + +Montserrat 14/20 in the default configuration has no Chinese glyphs. UTF-8 only describes how to decode text; it does not install a font. Source Han Sans SC built into this LVGL version is also a subset, not the complete Chinese character set. The font asset and widget style must both be checked; see the [LVGL font overview](https://docs.lvgl.io/9.5/main-modules/fonts/overview.html). + +## 2. Verify the configuration actually used by the application + +In `idf.py menuconfig`, search for the following symbols and check the generated `sdkconfig`: + +```text +CONFIG_LV_TXT_ENC_UTF8=y +CONFIG_LV_USE_FONT_PLACEHOLDER=y +``` + +Keep placeholders enabled while developing so missing glyphs remain visible. Disabling them can turn missing text into blanks; it does not repair coverage. Do not edit generated headers or files under `managed_components/` to force these settings. + +Save source files and text resources as UTF-8. Decode JSON escapes before display, and convert any legacy-encoded input at the application boundary. Do not truncate UTF-8 by an arbitrary byte count; leave space for the terminating NUL and cut only at a character boundary. `lv_label_set_text()` copies its string, while `lv_label_set_text_static()` requires the supplied buffer to remain valid; a stack-local buffer must not outlive its scope through the latter API. + +For local builds, inspect the generated root `sdkconfig`, not just `sdkconfig.defaults`. The repository's firmware gate instead generates an isolated configuration from tracked defaults. Persist intentional settings in your application's tracked defaults and verify both configurations as described in [build and test](build-and-test.md). + +## 3. Option A: validate a built-in CJK subset + +For a small initial experiment, enable this font in your application's configuration: + +```text +CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_16_CJK=y +``` + +Rebuild, then explicitly select it on a label. The following function is called only after LVGL/display initialization, in the LVGL task or while holding `bsp_lvgl_lock()`. Supply a visible parent with adequate space: + +```c +#include "lvgl.h" + +lv_obj_t *app_create_cjk_probe(lv_obj_t *parent) +{ + lv_obj_t *label = lv_label_create(parent); + lv_obj_set_style_text_font(label, &lv_font_source_han_sans_sc_16_cjk, + LV_PART_MAIN | LV_STATE_DEFAULT); + lv_label_set_text(label, "\u4E2D\u6587 ABC 123"); + return label; +} +``` + +The escapes identify U+4E2D and U+6587 and keep the example identical in both document languages. Valid UTF-8 source literals work too. This probe tests a few characters only. Before choosing this font for a product, check every actual label, punctuation mark, name, and supported input. Enabling the font does not select it globally; setting a theme/default font still does not replace explicit fonts in existing widgets. + +## 4. Option B: generate a reproducible application subset + +Prepare a licensed TTF/OTF font that contains the required glyphs. Store reusable materials under `assets/fonts/` and record their source/license in the [assets README](../../../assets/README.md). Install a pinned version of the [official converter](https://github.com/lvgl/lv_font_conv), record its version, and confirm the options with `lv_font_conv --help`. + +Run from the repository root, after creating the asset directory and replacing the example input path with your font: + +```bash +lv_font_conv \ + --font /path/to/licensed-cjk-font.otf \ + --range 0x20-0x7E,0x4E2D,0x6587,0xFF0C,0x3002 \ + --size 20 --bpp 4 --format lvgl --no-compress \ + --lv-font-name app_font_20 --lv-include lvgl.h \ + --output assets/fonts/app_font_20.c +``` + +This example requests printable ASCII, two Chinese characters, a full-width comma, and an ideographic full stop. It is not a production character inventory. Replace the range with every required code point, or use the converter's `--symbols` input with your real text. An absent glyph in the source font cannot be created by requesting its code point. Check conversion diagnostics and the generated coverage rather than assuming success means completeness. + +Keep the character inventory and conversion command under version control. Generate each required size separately, using distinct names such as `app_font_16` and `app_font_20`. Start uncompressed to avoid a decoder/configuration mismatch; if compression is introduced, enable `CONFIG_LV_USE_FONT_COMPRESSED=y` and measure its rendering and memory impact. Avoid enabling every size or a full CJK family merely to fix one missing character. + +### Compile and declare the generated source + +For this repository's `main` component, append this after the existing `idf_component_register(...)` in `main/CMakeLists.txt`; do not replace its source or dependency lists: + +```cmake +target_sources(${COMPONENT_LIB} PRIVATE + "${CMAKE_CURRENT_LIST_DIR}/../assets/fonts/app_font_20.c" +) +``` + +Alternatively, add that source to the component's existing `SRCS` list. Use only one method: do not compile the same font twice or `#include` its `.c` in another source. Include `lvgl.h` and use `LV_FONT_DECLARE(app_font_20)` in the application file or shared font header. The declaration must match the generated symbol; it does not define or link the font by itself. A separate font component must declare its LVGL dependency. + +## 5. Bind text and icons without modifying read-only fonts + +If `app_font_20` covers Chinese and ASCII but lacks the application's LVGL icons, it can fall back to the already enabled Montserrat 20. For these static generated fonts, keep a writable descriptor with application lifetime and initialize it once before any widget uses it: + +```c +#include "lvgl.h" + +LV_FONT_DECLARE(app_font_20); +static lv_font_t s_app_font_with_symbols; + +void app_fonts_init(void) +{ + s_app_font_with_symbols = app_font_20; + s_app_font_with_symbols.fallback = &lv_font_montserrat_20; +} + +lv_obj_t *app_create_font_probe(lv_obj_t *parent) +{ + lv_obj_t *label = lv_label_create(parent); + lv_obj_set_style_text_font(label, &s_app_font_with_symbols, + LV_PART_MAIN | LV_STATE_DEFAULT); + lv_label_set_text(label, "\u4E2D\u6587\uFF0C ABC 123\u3002 " LV_SYMBOL_OK); + return label; +} +``` + +Call `app_fonts_init()` first, after LVGL initialization and before creating labels. Run UI operations in the LVGL task or under `bsp_lvgl_lock()`. This shallow descriptor copy is for the static bitmap font in this example, not a general cloning method for dynamically loaded font engines. Keep the descriptor and referenced data alive for all users; never cast away `const` on an existing font or create a fallback loop. + +Fallback is directional: here the application font is tried first and Montserrat supplies only missing glyphs. It cannot supply additional Chinese characters absent from both fonts. Equal nominal sizes do not guarantee matching baselines or line heights; inspect mixed lines and reserve enough height, or regenerate compatible metrics. For Latin-first typography, deliberately reverse the primary/fallback choice using an application-owned descriptor and recheck metrics and coverage. + +Audit actual widget bindings, not just the screen/default font. `ui_pixel_label()` sets local fonts, `ui_pixel_screen_create()` uses Montserrat 20 for its title, and menu/demo labels select Montserrat explicitly. New applications should implement their own UI/font helpers. For compound widgets, inspect the part that draws text and any separately created popup list; check focused, pressed, checked, and disabled states too. + +## 6. Prove glyph coverage and identify the active font + +This helper checks a Unicode code point, not a UTF-8 byte or a multicharacter C literal: + +```c +#include "lvgl.h" + +bool app_font_has_glyph(const lv_font_t *font, uint32_t codepoint) +{ + if (font == NULL) return false; + lv_font_glyph_dsc_t glyph = {0}; + return lv_font_get_glyph_dsc(font, &glyph, codepoint, 0) + && !glyph.is_placeholder; +} +``` + +For an existing label, get `lv_obj_get_style_text_font(label, LV_PART_MAIN)` under the LVGL lock, then check that font rather than an unrelated global symbol. This getter resolves the current state; repeat after each relevant state transition. A positive result checks descriptors/fallback coverage, not successful bitmap decoding or final screen output. + +Decode all fixed text into Unicode code points and check the ones required by each size/style; omit control characters such as newline from printable-glyph checks. Log missing values as `U+XXXX`. For the generated subset above, U+4E2D/U+6587/U+FF0C/U+3002 should pass if the source provides them; U+9F98 is intentionally absent and should fail with the shown Montserrat fallback. Include a known-missing negative case so the coverage test cannot pass unconditionally. + +Dynamic content needs an explicit contract: accept a documented character set, add verified glyph coverage, or show a deliberate supported replacement/unsupported-text message. Do not silently drop unknown characters or claim that a fixed menu subset supports arbitrary names and network text. When the supported inventory changes, regenerate fonts and rerun coverage checks. + +## 7. Diagnose failures in order + +| Symptom | Next action | +| --- | --- | +| Undefined reference to a font | Check symbol spelling, CMake source registration, font enable macro, and a C-compatible declaration when consumed by C++ | +| Font file exists but nothing changes | Check the actual selected font; copying assets or declaring a symbol is insufficient | +| ASCII works, Chinese is blank/boxed | Check encoding, per-code-point coverage, and the actual fallback chain; do not disable placeholders | +| Body text works, title/popup fails | Inspect local fonts, widget parts, separately created children/popups, and state overrides | +| Glyph check passes but text is blank | Check the bitmap format/decoder, font lifetime, text color/opacity, hidden flags, and LVGL allocation errors | +| Characters overlap or lose their top/bottom | Check line height, baseline, parent clipping, label width/height, and fallback metrics | +| New strings fail after an otherwise successful build | Regenerate all affected subsets/sizes, inspect the actual configuration, and confirm the device is running the intended build | + +## 8. Validate without overstating the result + +Run the [complete repository gate](build-and-test.md) and your application's character-coverage tests. Inspect `idf.py size-components`/`idf.py size-files` for Flash/static RAM, and record runtime free heap and largest free block with the real UI and networking active. A font compiled into read-only Flash is not equivalent to allocating the whole font on the heap, but drawing/loading/caching can still require internal RAM. + +On the device, inspect every page and state, mixed text/icons, long lines, different sizes, and dynamic input at both sides of the supported-set boundary. Test after page recreation and restart, not just the first label. Record the firmware version, font/converter versions, tested character inventory, screenshots where useful, and any missing characters or layout defects. Without this check, Chinese rendering remains `Unverified`; neither the baseline host tests nor a successful firmware build verifies the examples' visual output. diff --git a/docs/development/engineering/lvgl-chinese-fonts.zh_CN.md b/docs/development/engineering/lvgl-chinese-fonts.zh_CN.md new file mode 100644 index 0000000..fb1099a --- /dev/null +++ b/docs/development/engineering/lvgl-chinese-fonts.zh_CN.md @@ -0,0 +1,164 @@ +

+ 简体中文 · English +

+ +# LVGL 中文显示:接入与排查 + +添加中文文案、修改字体/字号或显示用户/网络内容时使用本指南。[代码检查清单](coding-conventions.zh_CN.md#中文字体与缺字排查)定义验收要求,本文提供当前仓库锁定的 LVGL 9.5.0 的具体接入步骤。以下都是应用开发示例,不代表基线已经启用了这些配置。 + +## 1. 区分编码、字形覆盖和样式选择 + +正确显示需要同时满足以下条件: + +| 层次 | 必须满足 | 常见错误表现 | +| --- | --- | --- | +| 文本输入 | 有效 UTF-8,不能截断多字节字符 | 即使字体正确也显示乱码 | +| 字体素材 | 每个所需 Unicode 码点都在字体或 fallback 链中 | 英文正常,中文空白/方框 | +| 编译接入 | 字体源文件已编译、链接并启用 | 字体符号未定义,或预期字体根本没用上 | +| 控件样式 | 当前状态下,实际绘制文字的部件选用了该字体 | 只有标题、弹窗或选中项异常 | +| 布局/绘制 | 颜色/透明度可见、空间足够,字体生命周期和绘制内存有效 | 字形存在,但文字被裁剪或不可见 | + +默认配置中的 Montserrat 14/20 不含中文字形。UTF-8 只规定怎样解码文本,不会安装字库。此版本 LVGL 内置的 Source Han Sans SC 也只是子集,不是完整中文字库。必须同时核对字体素材和控件样式;参见 [LVGL 字体概览](https://docs.lvgl.io/9.5/main-modules/fonts/overview.html)。 + +## 2. 核对应用实际使用的配置 + +在 `idf.py menuconfig` 中搜索以下符号,并检查生成的 `sdkconfig`: + +```text +CONFIG_LV_TXT_ENC_UTF8=y +CONFIG_LV_USE_FONT_PLACEHOLDER=y +``` + +开发时保留缺字占位,让问题可见。关闭占位可能把缺字变成空白,并没有补齐字形。不要修改生成的头文件或 `managed_components/` 内的文件来强行覆盖这些配置。 + +源码和文本资源保存为 UTF-8。JSON 转义应先解码再显示,旧编码输入应在应用边界转换。不要按任意字节数截断 UTF-8;既要给结尾 NUL 留空间,也要确保截断位置在完整字符边界。`lv_label_set_text()` 会复制字符串,`lv_label_set_text_static()` 则要求传入缓冲持续有效,不能让它在栈局部缓冲离开作用域后继续使用该地址。 + +本地构建检查生成的根目录 `sdkconfig`,不能只看 `sdkconfig.defaults`。仓库固件门禁会从已跟踪的 defaults 生成隔离配置。把应用有意使用的设置写入该应用已跟踪的 defaults,并按[构建与验证](build-and-test.zh_CN.md)核对两种配置。 + +## 3. 方案 A:用内置 CJK 子集快速验证 + +小范围初步实验可以在应用配置中启用: + +```text +CONFIG_LV_FONT_SOURCE_HAN_SANS_SC_16_CJK=y +``` + +重新编译,然后在标签上显式指定字体。以下函数只在 LVGL/显示初始化后调用,必须处于 LVGL 任务或持有 `bsp_lvgl_lock()`;传入可见且有足够空间的父对象: + +```c +#include "lvgl.h" + +lv_obj_t *app_create_cjk_probe(lv_obj_t *parent) +{ + lv_obj_t *label = lv_label_create(parent); + lv_obj_set_style_text_font(label, &lv_font_source_han_sans_sc_16_cjk, + LV_PART_MAIN | LV_STATE_DEFAULT); + lv_label_set_text(label, "\u4E2D\u6587 ABC 123"); + return label; +} +``` + +转义表示 U+4E2D、U+6587,即“中文”,用来保持中英文文档示例一致;合法 UTF-8 源码也可直接写中文。这个探针只测试少量字符。用于产品前,必须检查实际文案、标点、姓名和支持的输入。启用字体不等于全局选用它;设置主题/默认字体也不会替换现有控件显式指定的字体。 + +## 4. 方案 B:生成可复现的应用子集 + +准备授权允许且覆盖所需字形的 TTF/OTF 字体。可复用素材放在 `assets/fonts/`,来源/授权记录在[素材 README](../../../assets/README.zh_CN.md)。安装固定版本的[官方字体转换工具](https://github.com/lvgl/lv_font_conv),记录版本,并通过 `lv_font_conv --help` 核对参数。 + +先创建素材目录,把输入路径换成实际字体,再从仓库根目录运行: + +```bash +lv_font_conv \ + --font /path/to/licensed-cjk-font.otf \ + --range 0x20-0x7E,0x4E2D,0x6587,0xFF0C,0x3002 \ + --size 20 --bpp 4 --format lvgl --no-compress \ + --lv-font-name app_font_20 --lv-include lvgl.h \ + --output assets/fonts/app_font_20.c +``` + +示例只请求可打印 ASCII、“中文”、全角逗号和中文句号,不是正式应用的字符清单。请把范围替换为全部所需码点,或使用转换器的 `--symbols` 输入实际文案。源字体没有的字形,不能靠填写码点生成;必须检查转换提示及生成结果的覆盖范围,不能把命令成功等同于字形齐全。 + +将字符清单和转换命令纳入版本管理。每个实际字号分别生成,使用 `app_font_16`、`app_font_20` 等不同名称。首次接入先不压缩,避免解码器/配置不匹配;后续若使用压缩字体,启用 `CONFIG_LV_USE_FONT_COMPRESSED=y` 并测量绘制与内存影响。不要为了补一个字就启用所有字号或整套 CJK 字体家族。 + +### 编译并声明生成的源文件 + +对于当前仓库的 `main` 组件,在 `main/CMakeLists.txt` 现有 `idf_component_register(...)` 之后追加以下内容,不要替换原有源文件或依赖列表: + +```cmake +target_sources(${COMPONENT_LIB} PRIVATE + "${CMAKE_CURRENT_LIST_DIR}/../assets/fonts/app_font_20.c" +) +``` + +也可以把源文件加入组件已有的 `SRCS` 列表,两种方式选一种即可。不要重复编译同一字体,也不要在其他源码里 `#include` 字体 `.c`。在应用源文件或共享字体头文件中包含 `lvgl.h` 并使用 `LV_FONT_DECLARE(app_font_20)`;声明必须匹配生成的符号,声明本身不会定义或链接字体。若独立建立字体组件,该组件必须声明 LVGL 依赖。 + +## 5. 绑定文字与图标,不修改只读字体 + +若 `app_font_20` 包含中文和 ASCII,但没有应用使用的 LVGL 图标,可以 fallback 到默认已经启用的 Montserrat 20。对于这里的静态生成字体,保留一个与应用同寿命的可写描述符,并在任何控件使用它之前初始化一次: + +```c +#include "lvgl.h" + +LV_FONT_DECLARE(app_font_20); +static lv_font_t s_app_font_with_symbols; + +void app_fonts_init(void) +{ + s_app_font_with_symbols = app_font_20; + s_app_font_with_symbols.fallback = &lv_font_montserrat_20; +} + +lv_obj_t *app_create_font_probe(lv_obj_t *parent) +{ + lv_obj_t *label = lv_label_create(parent); + lv_obj_set_style_text_font(label, &s_app_font_with_symbols, + LV_PART_MAIN | LV_STATE_DEFAULT); + lv_label_set_text(label, "\u4E2D\u6587\uFF0C ABC 123\u3002 " LV_SYMBOL_OK); + return label; +} +``` + +先完成 LVGL 初始化,再调用 `app_fonts_init()`,最后创建标签。UI 操作仍须在 LVGL 任务或 `bsp_lvgl_lock()` 内执行。此处描述符浅拷贝只针对示例的静态位图字体,不是动态加载字体引擎的通用复制方式。描述符及引用的数据必须覆盖全部使用期;不得强制去掉原字体的 `const`,也不得形成 fallback 环路。 + +Fallback 有方向:这里先查应用字体,仅在缺字时使用 Montserrat。两边都没有的中文仍然无法显示。标称字号相同不保证基线、行高相同;必须检查混排行并留足高度,必要时重新生成度量兼容的字体。若希望英文优先使用另一种字体,应通过应用持有的描述符明确调整主字体/fallback 方向,并重新核对度量与覆盖。 + +检查实际控件绑定,不能只看 screen/默认字体。`ui_pixel_label()` 设置局部字体,`ui_pixel_screen_create()` 的标题使用 Montserrat 20,菜单/demo 标签也有显式 Montserrat 配置。新应用应实现自己的 UI/字体辅助函数。复合控件需检查真正绘制文字的部件,以及单独创建的弹出列表;焦点、按下、选中和禁用状态都要检查。 + +## 6. 验证字形覆盖,查明当前字体 + +以下辅助函数检查 Unicode 码点,而不是 UTF-8 单字节或 C 的多字符字符常量: + +```c +#include "lvgl.h" + +bool app_font_has_glyph(const lv_font_t *font, uint32_t codepoint) +{ + if (font == NULL) return false; + lv_font_glyph_dsc_t glyph = {0}; + return lv_font_get_glyph_dsc(font, &glyph, codepoint, 0) + && !glyph.is_placeholder; +} +``` + +对于已有标签,在 LVGL 锁内调用 `lv_obj_get_style_text_font(label, LV_PART_MAIN)`,对获取的实际字体进行检查,而不是验证一个无关的全局字体符号。这个 getter 解析当前状态,各相关状态切换后都要重复检查。返回成功只说明描述符/fallback 字形覆盖,不证明位图解码和屏幕输出成功。 + +把所有固定文案解码为 Unicode 码点,按各字号/样式真正需要的字符检查;换行等控制字符不纳入可打印字形检查。缺字记录为 `U+XXXX`。对于上述生成子集,若源字体包含所请求字形,U+4E2D/U+6587/U+FF0C/U+3002 应通过;U+9F98 刻意未收录,使用示例中的 Montserrat fallback 时应失败。加入已知缺字的反例,避免覆盖测试无条件通过。 + +动态内容必须有明确约定:只接受已声明字符集、补齐经过验证的字形,或显示有意设计且能正确显示的替代字符/不支持提示。不要悄悄丢弃未知字符,也不要把固定菜单子集描述成支持任意姓名和网络文本。支持范围变化后,重新生成字体并运行覆盖检查。 + +## 7. 按顺序定位故障 + +| 现象 | 下一步 | +| --- | --- | +| 字体 undefined reference | 检查符号拼写、CMake 源文件注册、字体启用宏,以及 C++ 使用时是否有兼容 C 的声明 | +| 字体文件存在但界面没变化 | 检查实际选中的字体;复制素材或声明符号都不够 | +| ASCII 正常,中文空白/方框 | 检查编码、逐码点覆盖和实际 fallback 链;不要关闭占位 | +| 正文正常,标题/弹窗异常 | 检查局部字体、控件部件、单独创建的子对象/弹窗及状态覆盖 | +| 字形检查通过但仍空白 | 检查位图格式/解码器、字体生命周期、文字颜色/透明度、隐藏标志和 LVGL 分配错误 | +| 字符重叠或上下被切掉 | 检查行高、基线、父容器裁剪、标签宽高和 fallback 度量 | +| 编译成功但新文案异常 | 重新生成受影响的所有子集/字号,检查实际配置,并确认设备运行的是目标构建 | + +## 8. 验证与交付边界 + +运行[完整仓库门禁](build-and-test.zh_CN.md)和应用自己的字符覆盖测试。用 `idf.py size-components`/`idf.py size-files` 检查 Flash/静态 RAM,同时记录真实 UI 和网络启用时的 free heap、largest free block。只读 Flash 中的字体并不等于把整个字库分配到堆中,但绘制/加载/缓存仍可能需要内部 RAM。 + +真机逐页逐状态检查混排/图标、长文本、不同字号和支持范围内外的动态输入。页面重建、重启后也要测,不能只看第一个标签。记录固件版本、字体/转换器版本、测试字符清单,必要时留截图,列出任何缺字与排版问题。未完成这些检查时,中文显示仍属于 `Unverified`;基线 host tests 或固件编译通过都不能验证这些示例的实际显示效果。 diff --git a/docs/development/engineering/protected-flash-layout.md b/docs/development/engineering/protected-flash-layout.md deleted file mode 100644 index 1eaf682..0000000 --- a/docs/development/engineering/protected-flash-layout.md +++ /dev/null @@ -1,51 +0,0 @@ -

- 简体中文 · English -

- -# Protected Flash Layout - -This repository reserves the per-device identity region so derivative firmware -does not overwrite provisioned `cardid` data. - -## Mandatory layout - -Derivative projects must preserve all of the following: - -- ESP32-C3, 8 MB Flash, ESP-IDF 5.5.3. -- A merged ESP image starting at `0x0`, produced as - `build/FoloToy-AI-Passport-full.bin`. -- One main application image at `0x10000`, no larger than `0x300000` bytes. -- `cardid`: data/NVS at `0x356000`, size `0x4000`. -- A valid partition-table MD5 marker and no partition overlap with the - protected `cardid` region. -- No device-specific `cardid` payload in a community artifact. - -Applications may add resource partitions, but they must not overlap protected -`cardid`. Required resource partitions must be included in the merged -artifact rather than declared empty. - -## Enforced validation - -Run: - -```bash -./tools/validate.sh --firmware -``` - -The check builds in an isolated directory, creates the merged image, verifies -the bootloader/table/application offsets, parses the partition table, checks its -MD5 and the protected `cardid` range, enforces the 3 MB application limit, and -rejects device-specific identity bytes. CI runs the same gate. Do not publish -an artifact when this command fails. - -Upload only `build/FoloToy-AI-Passport-full.bin`; the similarly named app-only -`build/FoloToy-AI-Passport.bin` does not contain the complete validated layout. - -## Flashing safety during development - -Never run `idf.py erase-flash` on a provisioned device. It destroys the -per-device identity. Prefer segmented `idf.py flash`, which does not write an -image for protected `cardid`. A -raw single-file write from `0x0` is safe only when its byte range ends before -`cardid`; a merged artifact containing later resource partitions spans the gap -and must not be raw-flashed to a provisioned device. diff --git a/docs/development/engineering/protected-flash-layout.zh_CN.md b/docs/development/engineering/protected-flash-layout.zh_CN.md deleted file mode 100644 index fe2f8cd..0000000 --- a/docs/development/engineering/protected-flash-layout.zh_CN.md +++ /dev/null @@ -1,45 +0,0 @@ -

- 简体中文 · English -

- -# 受保护的 Flash 布局 - -本仓库保留单机身份区域,避免二创固件覆盖已写入的 `cardid` 数据。 - -## 必须保持的布局 - -二创项目必须同时保留: - -- ESP32-C3、8 MB Flash、ESP-IDF 5.5.3。 -- 从 `0x0` 开始的合并 ESP 镜像,固定产物为 - `build/FoloToy-AI-Passport-full.bin`。 -- 位于 `0x10000` 的主应用镜像,不得超过 `0x300000` 字节。 -- `cardid`:data/NVS,地址 `0x356000`,大小 `0x4000`。 -- 有效的分区表 MD5,且所有分区不得与受保护的 `cardid` 区域重叠。 -- 社区产物不得包含任何单台设备的 `cardid` 数据。 - -应用可以新增资源分区,但不得覆盖受保护的 `cardid`。必需的资源分区必须打入 -合并产物,不得只在分区表中声明空分区。 - -## 强制验证 - -执行: - -```bash -./tools/validate.sh --firmware -``` - -脚本会在隔离目录构建,生成合并镜像,验证 bootloader、分区表与应用的 -偏移,解析分区表并检查 MD5、受保护的 `cardid` 范围和 3 MB 应用上限, -同时拒绝单机身份数据入包。CI 执行同一门禁。该命令失败时不得发布。 - -只上传 `build/FoloToy-AI-Passport-full.bin`。名称相近的应用单镜像 -`build/FoloToy-AI-Passport.bin` 不包含经完整验证的布局。 - -## 开发烧录安全 - -已写入设备身份的机器严禁执行 `idf.py erase-flash`,否则会破坏单机身份。 -优先使用不会写入受保护 `cardid` 的分段 `idf.py flash`。 -只有单文件的字节范围在 `cardid` 之前结束时,从 `0x0` 直接写入才安全; -若合并产物包含位于 `cardid` 之后的资源分区,就不得对已写身份的设备做 -单文件直刷。 diff --git a/docs/development/release/project-completion.md b/docs/development/release/project-completion.md index 14d0906..16e418d 100644 --- a/docs/development/release/project-completion.md +++ b/docs/development/release/project-completion.md @@ -196,16 +196,20 @@ commit, push, tag, and release. ### Steps -1. Commit the change and push it to the fork (`origin`) — confirm separately. -2. Create and push a tag to trigger the release workflow — confirm separately. -3. Let the tagged build produce the merged firmware `.bin`. -4. Create or update the GitHub/GitLab release with the artifact — confirm +1. When preparing a repository release, review the merged user-visible changes + since the previous release and update both changelog languages as described + in [Automated Build and Release](../ci/CI-build-and-release.md). Ordinary + feature, application, and documentation pull requests skip this step. +2. Commit the change and push it to the fork (`origin`) — confirm separately. +3. Create and push a tag to trigger the release workflow — confirm separately. +4. Let the tagged build produce the merged firmware `.bin`. +5. Create or update the GitHub/GitLab release with the artifact — confirm separately. The workflow sets the default release title to the version/tag name; after the release is up, refine it to the project feature name plus the version number. -5. Write release notes in English (and a Simplified Chinese version where the +6. Write release notes in English (and a Simplified Chinese version where the project is bilingual) covering what is new, how to build, and how to use. -6. Verify the released full build on hardware (see +7. Verify the released full build on hardware (see [Post-release hardware verification](#post-release-hardware-verification)). ### Rules diff --git a/docs/development/release/project-completion.zh_CN.md b/docs/development/release/project-completion.zh_CN.md index 6744495..bfa5a20 100644 --- a/docs/development/release/project-completion.zh_CN.md +++ b/docs/development/release/project-completion.zh_CN.md @@ -145,12 +145,13 @@ flowchart TD ### 步骤 -1. 提交变更并推送到 fork(`origin`)——分开确认。 -2. 创建并推送 tag 以触发 release 工作流——分开确认。 -3. 让 tagged 构建产生合并固件 `.bin`。 -4. 用产物创建或更新 GitHub/GitLab release——分开确认。工作流把 release 标题默认设为版本/tag 名;release 发布后,把它改成项目特性名加版本号。 -5. 用英文写 release notes(项目双语时另附简体中文版),覆盖新增内容、如何构建、如何使用。 -6. 在真机验证发布的完整构建(见 [发布后真机验证](#post-release-hardware-verification))。 +1. 准备仓库发布时,检查自上一版本以来已合并的用户可见变化,并按[自动构建与发布](../ci/CI-build-and-release.zh_CN.md)同时更新中英文变更日志。普通功能、应用和文档 PR 跳过此步骤。 +2. 提交变更并推送到 fork(`origin`)——分开确认。 +3. 创建并推送 tag 以触发 release 工作流——分开确认。 +4. 让 tagged 构建产生合并固件 `.bin`。 +5. 用产物创建或更新 GitHub/GitLab release——分开确认。工作流把 release 标题默认设为版本/tag 名;release 发布后,把它改成项目特性名加版本号。 +6. 用英文写 release notes(项目双语时另附简体中文版),覆盖新增内容、如何构建、如何使用。 +7. 在真机验证发布的完整构建(见 [发布后真机验证](#post-release-hardware-verification))。 ### 规则 diff --git a/docs/development/release/publish-to-community.md b/docs/development/release/publish-to-community.md index bf91a5f..2e3061b 100644 --- a/docs/development/release/publish-to-community.md +++ b/docs/development/release/publish-to-community.md @@ -29,7 +29,7 @@ The skill's `SKILL.md` defines the exact workflow: inspect the project, prepare - **Firmware**: the single merged ESP image `build/FoloToy-AI-Passport-full.bin`. It must pass `./tools/validate.sh --firmware`, including the - [protected Flash layout](../engineering/protected-flash-layout.md). + [configured firmware layout](../engineering/firmware-layout.md). Never substitute the app-only `.bin` produced by `idf.py build`. - **Cover**: a representative JPEG / PNG / WebP image (<= 10 MiB). - **Source**: the public HTTPS Git page for the firmware repository — GitHub, Gitee, GitLab, Codeberg, or another publicly reachable HTTPS Git repository page. A fork owner publishes from their fork's source page, resolved from `git remote -v`. @@ -40,7 +40,7 @@ The skill's `SKILL.md` defines the exact workflow: inspect the project, prepare - Validation, drafting, and preview that is not confirmed by the author does **not** authorize upload. - Authorization credentials are never requested, received, or stored by the assistant. The creator registers or signs in on the official site and approves the displayed code; the assistant never handles their password. - Never retry a rejected upload automatically. Report the server response and resolve the cause with the creator first. -- Do not weaken, bypass, or remove the protected-layout gate merely to make a +- Do not weaken, bypass, or remove the firmware-layout gate merely to make a community submission pass. Fix the image layout or build packaging instead. ## How the assistant installs the skill diff --git a/docs/development/release/publish-to-community.zh_CN.md b/docs/development/release/publish-to-community.zh_CN.md index 3c6b8ba..2973e2f 100644 --- a/docs/development/release/publish-to-community.zh_CN.md +++ b/docs/development/release/publish-to-community.zh_CN.md @@ -32,7 +32,7 @@ skill 的 `SKILL.md` 定义了精确流程:检查项目、准备中英文标 ## 你需要提供给助手的东西 - **固件**:固定使用单个合并镜像 `build/FoloToy-AI-Passport-full.bin`, - 且必须通过 `./tools/validate.sh --firmware` 与[受保护的 Flash 布局](../engineering/protected-flash-layout.zh_CN.md)。 + 且必须通过 `./tools/validate.sh --firmware` 与[当前配置的固件布局](../engineering/firmware-layout.zh_CN.md)。 不得用 `idf.py build` 生成的应用单镜像替代。 - **封面**:一张代表产品的 JPEG / PNG / WebP 图(≤ 10 MiB)。 - **源码**:固件仓库的公开 HTTPS Git 项目页——GitHub、Gitee、GitLab、Codeberg 或其它公开可达的 HTTPS Git 仓库页。fork 所有者从其 fork 的来源页发布,从 `git remote -v` 解析。 @@ -43,7 +43,7 @@ skill 的 `SKILL.md` 定义了精确流程:检查项目、准备中英文标 - 未经作者确认的验证、起草与预览**不授权上传**。 - 助手绝不索取、接收或存储授权凭证。由创作者在官方站点注册或登录并批准显示的代码;助手不接触其密码。 - 不自动重试被拒的上传。先把服务端响应展示给创作者,查清原因再处理。 -- 不得为了让社区提交通过而弱化、绕过或删除保护布局门禁;应修复镜像布局或打包流程。 +- 不得为了让社区提交通过而弱化、绕过或删除固件布局门禁;应修复镜像布局或打包流程。 ## 助手如何安装该 skill diff --git a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md index 32bd40b..12870d9 100644 --- a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md +++ b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md @@ -12,7 +12,7 @@ Document scope: - Applicable target: the ESP32-C3 FoloToy AI Passport mapping implemented by this repository. - Product specifications are in [specifications.md](specifications.md); firmware behavior follows `bsp_pins.h`, BSP implementations, `sdkconfig.defaults`, `partitions.csv`, and the demo code. -- Code audit date: 2026-08-26. +- Code audit date: 2026-09-14. ## 1. Before changing hardware-facing code @@ -91,15 +91,17 @@ GPIO0 is both the button ADC node and an ESP32-C3 boot-related pin. GPIO21 is th app_main ├─ shared I2C init and scan ├─ display and LVGL init, then backlight - ├─ button init + ├─ input queue/lifecycle task, then button init ├─ audio init ├─ battery init └─ LVGL menu and independent demo pages ``` -Display/LVGL is a hard dependency. Buttons, audio, and battery are soft dependencies whose pages show `[FAIL]` while other pages remain available. Public BSP APIs are under `components/bsp/include/`; most initialization is idempotent, but there is no universal BSP deinitialization API. +Display/LVGL is a hard dependency. Buttons, audio, and battery are soft dependencies whose pages show `[FAIL]` while other pages remain available. Public BSP APIs are under `components/bsp/include/`. Successful display, button, audio, and LVGL initialization is idempotent. Display, button, and audio partial failures release resources acquired by the BSP; failed LVGL display registration deinitializes its port. The caller can correct the fault and retry, while an incomplete lower-level rollback is reported and prevents a handle from being overwritten. There is no universal BSP deinitialization API. -Wi-Fi, NimBLE, and sleep use ESP-IDF directly rather than the BSP. `demo_radio.c` owns shared NVS, `esp_netif`, and default-event-loop setup. Wi-Fi and Bluetooth pages allocate their radio stacks on entry and stop/deinitialize them on exit. Do not erase NVS to hide partition errors. Deep sleep restarts the application and the demo uses RTC slow memory for the wake counter. +Button callbacks run in the shared `esp_timer` task. They only enqueue input and return; the demo lifecycle task handles navigation and starts or stops slow services without holding the LVGL lock. Page exit first completes a bounded producer stop, then deletes timers and UI objects while holding the lock. Audio and light-sleep workers use cooperative cancellation and an explicit exit handshake rather than forced task deletion. The low-power worker force-suspends and verifies ES8311 before either sleep mode and resumes it after light sleep. For deep sleep it suspends and verifies CW2017 first, force-suspends ES8311, stops and releases I2S, releases the shared I2C pins, blocks further LVGL flushes, sleeps the LCD, and holds its safe pin levels before entering deep sleep. Individual peripheral failures are logged but do not strand the system awake; an unexpected return after terminal pin release causes a restart. Deep-sleep wake also restarts the application and follows normal BSP initialization. + +Wi-Fi, NimBLE, and sleep use ESP-IDF directly rather than the BSP. `demo_radio.c` owns shared NVS, `esp_netif`, and default-event-loop setup. Wi-Fi and Bluetooth pages allocate their radio stacks after page creation and stop/deinitialize them before page deletion. Do not erase NVS to hide partition errors. Deep sleep restarts the application and the demo uses RTC slow memory for the wake counter. ## 5. Display and LVGL @@ -111,7 +113,11 @@ Wi-Fi, NimBLE, and sleep use ESP-IDF directly rather than the BSP. `demo_radio.c The LVGL DMA buffer is one `240 × 20` RGB565 buffer, about 9.6 KB; the LVGL internal pool is 24 KB. Do not add large/double buffers without checking internal RAM, the largest contiguous heap block, and I2S DMA. -LVGL is not thread-safe. Timer callbacks in LVGL context may access objects directly. Button callbacks and worker tasks must use `bsp_lvgl_lock()`/`bsp_lvgl_unlock()`. Stop producers before deleting a page and clear static object pointers afterward. +The final LVGL RGB565 flush is masked to a global 30 px radius, so the four areas outside the rounded screen remain pure black during page changes as well as normal rendering. The mask is applied directly to the partial draw buffer and does not use root-screen `clip_corner`; full-screen rounded clipping requires an ARGB intermediate layer that can exhaust the 24 KB LVGL pool on this no-PSRAM target. Keep this behavior in the display integration instead of duplicating corner decorations in individual pages. + +Before terminal deep sleep, stop new page work and hold the LVGL lock long enough to finish any current flush. `bsp_display_prepare_deep_sleep()` then sends display-off and Sleep In, stops the backlight PWM at low level, drives CS high and SCLK/MOSI/DC/backlight low, enables per-pin hold, and enables the ESP32-C3 global deep-sleep hold. `bsp_display_init()` disables the global and per-pin holds before SPI or LEDC takes ownership after wake. This terminal API is not a reversible display blanking operation and must be followed immediately by deep sleep or restart. + +LVGL is not thread-safe. Timer callbacks in LVGL context may access objects directly. Button callbacks must not access LVGL; they enqueue input for the lifecycle task. The lifecycle task and other workers must use `bsp_lvgl_lock()`/`bsp_lvgl_unlock()` for short UI operations. Stop producers before deleting a page and clear static object pointers afterward. ## 6. ADC button ladder @@ -124,7 +130,7 @@ GPIO0 has an external 10 kΩ pull-up to 3.3 V. UP, DOWN, and OK connect it to gr | OK | about 595 mV | `[447, 1900)` mV | | Released | about 3300 mV | outside all windows | -Do not replace the external resistor with the inaccurate internal pull-up. The BSP creates one ADC1 oneshot unit and shares it with all button devices and voltage reads. Attenuation is `ADC_ATTEN_DB_12`. Callbacks originate in the button component task and must not block or perform heavy UI work. +Do not replace the external resistor with the inaccurate internal pull-up. The BSP creates one ADC1 oneshot unit and shares it with all button devices and voltage reads. Attenuation is `ADC_ATTEN_DB_12`. Callbacks originate in the button component's shared `esp_timer` task and must only enqueue work or perform similarly bounded operations. Calibrate thresholds using multiple boards, charge levels, and reasonable temperatures; leave margin between measured distributions rather than relying only on divider theory. @@ -136,6 +142,7 @@ I2C0 uses SDA GPIO10 and SCL GPIO7. ES8311 is 7-bit address `0x18`; CW2017 is `0 - Scan with `i2c_master_probe()` on the existing bus. The scan covers `0x08` through `0x77`; success means the scan completed, not that a device was found. - CW2017 runs at 100 kHz. ES8311 control is managed by `esp_codec_dev`. - The codec control API expects an 8-bit address, so ES8311 receives `0x18 << 1`; do not copy that shift into 7-bit ESP-IDF APIs. +- For deep sleep, complete the CW2017 write/readback and ES8311 write/readback before calling `bsp_i2c_prepare_deep_sleep()`. That terminal call detaches SDA/SCL as inputs with both internal pulls disabled; no later I2C transaction is valid until reboot. External board pull-ups and their resulting static current remain hardware properties. Troubleshoot in order: bus-init log, scan results for `0x18`/`0x63`, power/ground/wiring/pull-ups, address format, and accidental duplicate-bus creation. @@ -151,8 +158,22 @@ The MCU is I2S master and the ES8311 is slave. I2S0 TX/RX shares MCLK GPIO6, BCL - Microphone analog gain is 30 dB; output volume is a separate 0–100% value. - `bsp_audio_read/write` block and must not run in button callbacks or the LVGL task. - I2S DMA uses six descriptors of 240 frames each. +- Stop every PCM reader and writer before calling `bsp_audio_sleep()`. It executes the complete ES8311 suspend register sequence directly through the already-open control interface, independently of the codec-device opened flag, so a boot that never played audio does not need a silent open. It reads back registers `0x00`, `0x01`, `0x0D`, `0x0E`, `0x12`, and `0x45`, retries the full sequence once after 5 ms, and explicitly disables both I2S channels even when audio was never opened. +- Call `bsp_audio_wake()` after light sleep to reopen the saved format and restart the codec/I2S path. The calls are idempotent, and an unavailable audio subsystem is treated as having nothing to suspend or resume. Deep-sleep wake reboots and uses the normal `bsp_audio_init()` path instead. +- REG0E is still written as `0xFF`, but readback verifies only bits 6:0 with mask `0x7F` and expected value `0x7F`. Both `0x7F` and `0xFF` pass; bit 7 reading as zero must not cause a false suspend failure. The other five registers retain full-byte checks. I2C errors or mismatched checked bits still fail after one retry: the Low Power demo aborts light sleep and attempts audio recovery, while deep sleep logs the error and continues its terminal shutdown. +- Only for terminal deep sleep, call `bsp_audio_prepare_deep_sleep()` after suspend to leave MCLK, BCLK, WS, DOUT, and DIN as high-impedance inputs without internal pulls. Do not use this API for light sleep: the active I2S pin routing is intentionally not recoverable until reboot. +- Software suspend stops the ES8311 ADC/DAC, analog paths, microphone-bias path, internal clocks, internal BCLK/LRCK pull-ups, and digital/analog modules, but it does not switch off the physical 3.3 V rail. The external amplifier also remains outside software control because `BSP_I2S_PA_CTRL` is `-1`; residual standby draw from that hardware must be measured separately. -The audio demo's three-second recording buffer is about 96 KB and is the largest transient heap allocation. Prefer chunked streaming for longer audio. Production task shutdown needs a cancellable loop and explicit exit handshake rather than deleting a task blocked in codec I/O. +The audio demo's three-second recording buffer is about 96 KB and is the largest transient heap allocation. Prefer chunked streaming for longer audio. Its worker checks cancellation between PCM chunks and acknowledges exit before the page is deleted; retain that bounded handshake when extending the demo. + +### 8.1 Crackles while navigating or saving + +When extending the tone demo into continuous BGM with UI updates and NVS saves, button-correlated crackles can come from interrupted PCM delivery, even if that button plays no sound. Check these two paths separately before changing the sound effect or volume: + +- **Task starvation:** measure the longest PCM feed gap alongside redraw and save durations. Six DMA descriptors of 240 frames hold at most `6 * 240 / 16000 = 90 ms` at 16 kHz when full; available headroom can be smaller. Keep blocking work out of button callbacks and LVGL locks, avoid Flash writes for focus-only changes, and give the audio worker enough priority relative to rendering. It must still block/yield; do not use a busy loop or copy a priority number without checking the application's tasks. Preserve saves at meaningful state changes. +- **Flash/cache stalls:** Flash writes/erases can disable cache and defer the default I2S interrupt. For playback concurrent with saves, enable `CONFIG_I2S_ISR_IRAM_SAFE=y` and verify the generated `sdkconfig` (editing defaults alone does not override an existing configuration). Any registered I2S callbacks and their callees must be IRAM-safe, with accessed data in internal DRAM; `IRAM_ATTR` on the callback alone is insufficient. Do not log, allocate, or read Flash assets in that callback. See [ESP-IDF 5.5.3 I2S IRAM safety](https://docs.espressif.com/projects/esp-idf/en/v5.5.3/esp32c3/api-reference/peripherals/i2s.html#iram-safe). + +IRAM-safe interrupts do not keep a Flash-resident producer running or provide unlimited buffering. Budget queued PCM for measured stalls and internal RAM, or schedule saves at a safe playback boundary. On the exact application build, keep BGM playing while repeatedly navigating and confirming actions that really save to NVS, then check save/reload behavior. Compare feed gaps and listen on the device: clean logs or a successful standalone tone do not establish glitch-free concurrent playback. ## 9. CW2017 fuel gauge @@ -162,16 +183,17 @@ Initialization reads VERSION and checks the profile update flag plus all 80 prof - Voltage uses the 14-bit value at `0x02–0x03`, converted as `raw × 312.5 µV`, and returned in mV. - Transactions use a 100 ms timeout at 100 kHz. - A missing device returns `ESP_ERR_NOT_FOUND`; the battery page is disabled without stopping the application. +- Before terminal deep sleep, `bsp_battery_sleep()` writes `CW_CONFIG_SLEEP`, waits 5 ms, reads CONFIG back, and accepts success only when it reads the exact sleep value. It retries once and reports failure, while the application continues shutting down the remaining peripherals. Accurate production SOC requires the cell parameters, CW2017 datasheet/vendor profile, and full charge/discharge validation. ## 10. Flash, console, and memory -The current product and firmware baseline uses 8 MB Flash. `sdkconfig.defaults` fixes the image to 8 MB and disables automatic flash-size header rewriting. `partitions.csv` defines 24 KB NVS, 4 KB PHY data, one 3 MB factory application, and protected `cardid` at `0x356000`. This is not an ESP-IDF dual-slot OTA layout. A detected non-8-MB device does not match this baseline; identify the board and flash part before changing the project default. +The default custom-firmware baseline uses 8 MB Flash. `sdkconfig.defaults` fixes the image to 8 MB and disables automatic flash-size header rewriting. By default, `partitions.csv` defines only 24 KB NVS, 4 KB PHY data, and one factory application from `0x10000` through the end of Flash (`0x7F0000` bytes). It has no OTA, device-identity, or unused reserved partition. User firmware may replace this default with another valid 8 MB partition layout. A detected non-8-MB device does not match this hardware baseline; identify the board and flash part before changing the project default. -Do not erase a provisioned device or move/overlap protected `cardid`. -Community firmware contains no device identity payload. See the -[protected Flash layout](../development/engineering/protected-flash-layout.md). +Writing the merged image at `0x0` may reset NVS because gaps are padded in the +single file. Use segmented `idf.py flash` when stored application state must be +preserved. See the [firmware layout](../development/engineering/firmware-layout.md). The console is USB Serial/JTAG. Do not switch to the UART0 default output without resolving its GPIO21 conflict with the backlight. @@ -181,7 +203,7 @@ Review at least the 24 KB LVGL pool, 9.6 KB LCD DMA buffer, I2S DMA, 96 KB demo For reusable hardware capability, add `bsp_.h` and its implementation, keep constants in `bsp_pins.h`, update component CMake/dependencies, return `esp_err_t`, log actionable pin/address context, and document threading, blocking, ownership, initialization, and failure behavior. -For a validation page, implement `enter`, `exit`, and `key` in `main/demo_.c`; declare it in `demo.h`, list it in CMake, and register it in `DEMOS[]`. Create/load a page-owned screen on entry. Stop workers/timers before deleting it on exit. Keep UI text in English, put slow work in worker tasks, lock LVGL updates, and preserve global OK-long-press return behavior. +For a validation page, implement `enter`, `exit`, and `key` in `main/demo_.c`; add optional `start`/`stop` hooks for slow services or page-owned workers, declare it in `demo.h`, list it in CMake, and register it in `DEMOS[]`. Create/load a page-owned screen in `enter`, start slow work without the LVGL lock, stop producers with a bounded handshake, then delete timers and the screen in `exit`. Keep UI text in English, lock short LVGL updates, and preserve global OK-long-press return behavior. Menu initialization status arrays implicitly follow `DEMOS[]` order; update and review them together. @@ -235,7 +257,7 @@ General board acceptance: | Battery | plausible SOC/mV, graceful missing-device behavior, intermittent-I2C recovery | | Wi-Fi | visible scan count/SSID/RSSI, rescan, repeated entry/exit | | Bluetooth LE | phone sees `FoloPassport`, restart advertising, advertising stops on exit, repeated entry/exit | -| Light/deep sleep | select with UP/DOWN; 2 s light sleep resumes with backlight; 5 s deep sleep restarts with timer cause and retained count | +| Light/deep sleep | select with UP/DOWN; confirm the ES8311 readback passes before both modes; 2 s light sleep resumes codec/audio and backlight; for 5 s deep sleep confirm CW2017 precedes ES8311, I2S/I2C go high impedance, LCD safe levels remain held, timer wake retains the count, and audio/display work after reinitialization; measure board current in each state | | DMA/memory/UI | build memory report, runtime minimum heap/largest block, stable concurrent audio/display | ## 14. Troubleshooting diff --git a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md index 8866067..8e67410 100644 --- a/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md +++ b/docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.zh_CN.md @@ -12,7 +12,7 @@ - 适用对象:本仓库实现的 ESP32-C3 FoloToy AI Passport 板级映射。 - 产品规格见 [specifications.zh_CN.md](specifications.zh_CN.md);固件行为以 `bsp_pins.h`、BSP 实现、`sdkconfig.defaults`、`partitions.csv` 与 demo 代码为准。 -- 代码复核日期:2026-08-26。 +- 代码复核日期:2026-09-14。 ## 1. 开始任何任务前 @@ -95,7 +95,7 @@ GPIO0 同时是按键 ADC 节点和 ESP32-C3 启动相关管脚;GPIO21 是背 app_main ├─ bsp_i2c_init → bsp_i2c_scan ├─ bsp_display_init → bsp_lvgl_init → backlight 100% - ├─ bsp_button_init(on_key) + ├─ input queue/lifecycle task → bsp_button_init(on_key) ├─ bsp_audio_init ├─ bsp_battery_init └─ LVGL menu @@ -119,9 +119,11 @@ app_main - `bsp_battery.h`:SOC 与电压。 - `bsp_pins.h`:硬件常量,不承载业务逻辑。 -驱动初始化大多设计为幂等,但当前没有统一 deinit API。不要假设可以在运行时反复销毁和重建总线/驱动。 +显示、按键、音频和 LVGL 成功初始化后可重复调用。显示、按键与音频在 BSP 中途失败时会释放本次取得的资源;LVGL display 注册失败时会 deinit port。调用方修正故障后可以重试;若底层回滚本身失败,会明确报错并拒绝覆盖仍存活的句柄。当前没有统一 deinit API,不要假设可以在运行时任意销毁和重建总线/驱动。 -Wi-Fi、NimBLE 和 light/deep sleep 直接使用 ESP-IDF API,不属于板级 BSP。`demo_radio.c` 只管理 NVS、`esp_netif` 和默认 event loop 这些应用级共享前置。Wi-Fi 和 BLE 页在进入时初始化高内存占用的无线栈,退出时停止并释放;不自动抹除已有 NVS 数据来掩盖分区错误。deep sleep 会按 ESP32-C3 语义重启应用,示例用 RTC slow memory 记录唤醒次数。 +按键回调运行在共享 `esp_timer` 任务中,只负责将输入加入队列并立即返回。demo 生命周期任务负责页面导航,并在不持有 LVGL 锁时启动或停止慢服务。退出页面时先以有界等待停止 producer,再持锁删除定时器和 UI 对象。音频与 light-sleep 工作任务使用协作取消和明确的退出握手,不再强制删除仍可能访问外设或 UI 的任务。低功耗工作任务会在两种睡眠前强制暂停 ES8311 并回读校验,在 light sleep 返回后恢复。deep sleep 时则先暂停并校验 CW2017,再强制暂停 ES8311,停止和释放 I2S,释放共享 I2C 引脚,阻止后续 LVGL 刷屏,休眠 LCD 并保持安全引脚电平,最后进入 deep sleep。单个外设失败会记录日志,但不会让系统卡在唤醒状态;终端引脚释放后若意外返回则重启。deep sleep 唤醒同样会重启应用并走正常 BSP 初始化流程。 + +Wi-Fi、NimBLE 和 light/deep sleep 直接使用 ESP-IDF API,不属于板级 BSP。`demo_radio.c` 只管理 NVS、`esp_netif` 和默认 event loop 这些应用级共享前置。Wi-Fi 和 BLE 页在页面创建后初始化高内存占用的无线栈,在删除页面前停止并释放;不自动抹除已有 NVS 数据来掩盖分区错误。deep sleep 会按 ESP32-C3 语义重启应用,示例用 RTC slow memory 记录唤醒次数。 ## 5. 显示与 LVGL @@ -139,11 +141,15 @@ Wi-Fi、NimBLE 和 light/deep sleep 直接使用 ESP-IDF API,不属于板级 B ESP32-C3 无 PSRAM。当前 LVGL 显示缓冲为 `240 × 20` 像素的单 DMA 缓冲,RGB565 约 9.6 KB;`sdkconfig.defaults` 的 LVGL 内部池为 24 KB。不要直接改为大行数双缓冲,也不要扩大 UI 内存池而不检查内部 RAM、最大连续堆和 I2S DMA 初始化。 +LVGL 最终输出的 RGB565 刷新区域会统一套用 30 px 圆角遮罩,因此正常刷新和页面切换期间,圆角之外的四角区域都会保持纯黑。遮罩直接作用于局部绘制缓冲,不使用根 screen 的 `clip_corner`;全屏圆角裁剪需要 ARGB 中间图层,在本项目无 PSRAM、LVGL 内存池仅 24 KB 的条件下可能耗尽内存。该行为统一放在显示接入层,不应在各页面重复绘制四角装饰。 + +终端 deep sleep 前,应先阻止新页面任务,并持有 LVGL 锁等待当前 flush 完成。`bsp_display_prepare_deep_sleep()` 随后发送关闭显示和 Sleep In,将背光 PWM 停在低电平,设置 CS 为高电平,SCLK/MOSI/DC/背光为低电平,开启单引脚 hold 及 ESP32-C3 全局 deep-sleep hold。唤醒后 `bsp_display_init()` 会在 SPI 或 LEDC 接管前解除全局与单引脚 hold。该终端接口不是可恢复的息屏操作,调用后必须立即进入 deep sleep 或重启。 + LVGL 非线程安全: - LVGL 定时器回调运行在 LVGL 上下文,可直接操作对象。 -- 按键回调运行在 button 组件任务中,必须 `bsp_lvgl_lock()` / `bsp_lvgl_unlock()`。 -- 音频任务等其他 FreeRTOS 任务同样必须加锁。 +- 按键回调不得访问 LVGL,只将输入加入队列,交给生命周期任务处理。 +- 生命周期任务与音频任务等其他 FreeRTOS 任务访问 UI 时,必须短时持有 `bsp_lvgl_lock()` / `bsp_lvgl_unlock()`。 - 获取锁失败时应安全退出,且每条成功加锁路径都必须解锁。 - 页面退出时先停止可能访问页面对象的定时器/任务,再删除 screen,并将静态对象指针置空。 @@ -167,7 +173,7 @@ LVGL 非线程安全: - BSP 先创建唯一的 ADC1 oneshot unit,再把同一句柄交给三个 `iot_button` ADC 设备;`bsp_button_read_mv()` 也复用它。不要为电压显示另建 ADC1 unit。 - ADC 衰减为 `ADC_ATTEN_DB_12`,必须与依赖的 button 组件内部配置保持一致。升级组件后要重新核对。 - ADC 校准句柄创建失败不影响按键事件,但 `bsp_button_read_mv()` 返回 `-1`。 -- 回调来自 button 组件的定时器任务,不能阻塞、录音、播放或直接做重 UI 操作。 +- 回调来自 button 组件使用的共享 `esp_timer` 任务,只能入队或执行同等级的有界操作,不能阻塞、录音、播放或访问 UI。 - 事件包括 PRESS、CLICK、DOUBLE、LONG。应用菜单主要消费 CLICK;页面中的 OK LONG 被全局拦截用于返回。 重标阈值时,在 Button 页逐个长按按键记录稳定电压,采集多块板、不同电量和合理温度范围的数据,再把相邻分布之间留裕量设置为边界。不要只用理论分压值。 @@ -183,6 +189,7 @@ I2C0 使用 SDA GPIO10、SCL GPIO7。ES8311 地址为 7 bit `0x18`,CW2017 为 - `bsp_i2c_scan()` 扫描 0x08–0x77,适合启动诊断;它返回 OK 只表示扫描完成,不表示一定找到设备。 - CW2017 设备速率明确为 100 kHz。ES8311 控制接口由 `esp_codec_dev` 管理。 - ES8311 创建控制接口时库 API 要求 8 bit 地址,因此传入 `0x18 << 1`;其他使用 7 bit 地址的 ESP-IDF API 不应照搬此移位。 +- deep sleep 时必须先完成 CW2017 和 ES8311 的写入/回读,再调用 `bsp_i2c_prepare_deep_sleep()`。该终端接口把 SDA/SCL 切换为关闭两种内部上下拉的输入;重启前不得再发起 I2C 事务。板上外部上拉电阻及其静态电流仍是硬件特性。 故障定位顺序:确认 `bsp_i2c_init()` 日志 → 扫描是否看到 0x18/0x63 → 检查供电、地、SDA/SCL 和外部上拉 → 检查地址格式 → 检查是否错误创建了第二条同 port 总线。 @@ -208,10 +215,24 @@ MCU 是 I2S master,ES8311 是 slave;I2S0 的 TX/RX 全双工通道共享 MCL - 麦克风模拟输入增益当前为 30 dB;输出音量 API 为 0–100%。增益和音量不是同一个概念。 - `bsp_audio_read/write` 是阻塞调用,不能放在按键回调或 LVGL 任务中。 - I2S DMA 当前为 6 个 descriptor、每个 240 frame。更改 DMA 或 LVGL buffer 前必须联合评估内部 RAM。 +- 调用 `bsp_audio_sleep()` 前必须停止所有 PCM 读写。该接口通过已打开的控制接口直接执行完整 ES8311 suspend 寄存器序列,不依赖 codec-device opened 标志,因此开机后从未播放也不需无声 open。它会回读 `0x00`、`0x01`、`0x0D`、`0x0E`、`0x12` 和 `0x45`,失败后等待 5 ms 重试一次完整序列,并即使音频从未打开也显式停止两条 I2S channel。 +- light sleep 返回后调用 `bsp_audio_wake()`,以休眠前格式重新打开 codec/I2S 通路。两个接口均为幂等操作;音频子系统不可用时视为无需暂停或恢复。deep sleep 唤醒会重启,改由正常 `bsp_audio_init()` 流程初始化。 +- REG0E 仍写入 `0xFF`,但回读只比较 bit6:0,掩码和预期值均为 `0x7F`。读到 `0x7F` 或 `0xFF` 都通过,bit7 读为零不应误判为 suspend 失败。其余五个寄存器继续逐字节完整校验。I2C 错误或参与校验的位不符,重试一次后仍返回失败:Low Power demo 取消 light sleep 并尝试恢复音频;deep sleep 则记录错误并继续终端关闭流程。 +- 只在终端 deep sleep 中,suspend 后调用 `bsp_audio_prepare_deep_sleep()`,使 MCLK、BCLK、WS、DOUT 和 DIN 成为无内部上下拉的高阻输入。不得将该接口用于 light sleep;活动 I2S 引脚路由只会在重启后恢复。 +- 软件 suspend 会停止 ES8311 的 ADC/DAC、模拟路径、麦克风偏置路径、内部时钟、BCLK/LRCK 内部上拉及数字/模拟功能模块,但不会切断芯片物理 3.3 V 供电。由于 `BSP_I2S_PA_CTRL` 为 `-1`,外部功放也不受软件控制;这部分硬件残余待机电流需另行实测。 Audio demo 使用独立 4 KB 栈任务:OK 播放 1 秒 1 kHz 方波,UP 录 3 秒再回放。录音缓冲约 96 KB,是当前最显著的瞬时堆分配,可能因碎片或其他功能增大而失败。新增长录音应优先采用分块流式处理或外部存储,不可假设存在 PSRAM。 -当前 demo 的退出会直接删除音频任务。如果任务正阻塞于 codec 读写,实际硬件上需特别验证退出行为;若扩展为生产逻辑,应设计可取消的分块循环与明确的任务退出握手。 +Audio demo 的工作任务在 PCM 分块之间检查取消状态,并在页面删除前确认退出;扩展该页面时必须保留这一有界退出握手,不能强制删除阻塞于 codec I/O 的任务。 + +### 8.1 切换选项或存档时出现杂音 + +将音调 demo 扩展为持续 BGM、界面刷新和 NVS 存档并行的应用时,按键后出现的杂音可能来自 PCM 供给中断,即使该按键没有播放音效。修改音效或音量之前,先分别检查以下两条路径: + +- **任务供给不及时:** 同时测量 PCM 最大供给间隔、重绘和保存耗时。6 个 DMA descriptor、每个 240 frame,在 16 kHz 且缓冲填满时最多容纳 `6 * 240 / 16000 = 90 ms`;实际剩余余量可能更小。按键回调和 LVGL 锁内不做阻塞操作,纯焦点移动不写 Flash,音频工作任务相对刷屏任务应有足够优先级。任务仍须阻塞或让出 CPU;不要忙循环,也不要未检查应用任务就照抄优先级数值。仍在有意义的状态变化时保存。 +- **Flash/cache 停顿:** Flash 写入或擦除可能关闭缓存,延后默认 I2S 中断。播放与保存并行时,启用 `CONFIG_I2S_ISR_IRAM_SAFE=y`,并核对生成的 `sdkconfig`(只改 defaults 不会覆盖已有配置)。注册的 I2S 回调及其调用链必须满足 IRAM 安全要求,访问的数据放在内部 DRAM;只给回调加 `IRAM_ATTR` 不够。回调中不要打印日志、分配内存或读取 Flash 素材。参见 [ESP-IDF 5.5.3 I2S IRAM 安全说明](https://docs.espressif.com/projects/esp-idf/en/v5.5.3/esp32c3/api-reference/peripherals/i2s.html#iram-safe)。 + +中断放入 IRAM 并不能让位于 Flash 的音频生产任务持续运行,也不代表缓冲无限。应根据实测停顿和内部 RAM 预算准备排队的 PCM,或在安全的播放边界保存。在最终应用固件上,持续播放 BGM,反复切换选项并确认会实际写入 NVS 的操作,再验证保存和重新载入。对照供给间隔并实机试听:日志无告警或单独播放音调成功,都不能证明并发播放没有杂音。 ## 9. CW2017 电池计 @@ -221,15 +242,16 @@ CW2017 在共享 I2C 地址 0x63。初始化读取 VERSION 确认在线,并检 - 电压:读 0x02–0x03 的 14 bit 值,换算为 `raw × 312.5 µV`,API 返回 mV。 - 事务超时当前为 100 ms,设备时钟为 100 kHz。 - 芯片不应答时初始化返回 `ESP_ERR_NOT_FOUND`,菜单标记失败,但整机继续运行。 +- 终端 deep sleep 前,`bsp_battery_sleep()` 写入 `CW_CONFIG_SLEEP`,等待 5 ms 后回读 CONFIG,只有精确读回睡眠值才接受为成功。失败时重试一次并报告,应用仍继续关闭其余外设。 SOC 准确度取决于电芯与 profile 的匹配程度。本驱动给出的是电量计读数,不等于实验室标定结果。若产品需要准确 SOC,必须取得电芯参数、CW2017 数据手册和供应商 profile,并完成完整充放电验证。 ## 10. Flash、控制台和资源预算 -当前产品与固件基线使用 8 MB Flash。`sdkconfig.defaults` 固定使用 8 MB Flash 镜像配置,并关闭 `CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE`(不按探测容量回写镜像头,便于 `idf.py merge-bin`);`partitions.csv` 提供 24 KB NVS、4 KB PHY data、3 MB factory app,以及位于 `0x356000` 的保护 `cardid`。这不是 ESP-IDF 双槽 OTA 布局。若实机探测结果不是 8 MB,则该设备不符合当前基线;修改项目默认值前应先确认板卡和 Flash 料号。 +默认自定义固件基线使用 8 MB Flash。`sdkconfig.defaults` 固定使用 8 MB Flash 镜像配置,并关闭 `CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE`(不按探测容量回写镜像头,便于 `idf.py merge-bin`);默认 `partitions.csv` 只提供 24 KB NVS、4 KB PHY data,以及从 `0x10000` 延伸到 Flash 末尾的 factory app(大小 `0x7F0000`)。它没有 OTA、设备身份或未使用的预留分区。用户固件可以把它替换成其它合法的 8 MB 分区布局。若实机探测结果不是 8 MB,则该设备不符合当前硬件基线;修改项目默认值前应先确认板卡和 Flash 料号。 -不得擦除已写身份的设备,也不得移动或覆盖受保护的 `cardid`。社区固件不包含 -单机身份数据。详见[受保护的 Flash 布局](../development/engineering/protected-flash-layout.zh_CN.md)。 +从 `0x0` 写入合并镜像时,单文件中的间隙填充可能重置 NVS。需要保留已存应用 +状态时,应使用分段 `idf.py flash`。详见[固件布局](../development/engineering/firmware-layout.zh_CN.md)。 控制台固定为 USB Serial/JTAG,不使用 UART0 默认输出,因为其 TX GPIO21 与背光冲突。任何日志接口修改都必须同时检查引脚占用。 @@ -256,11 +278,11 @@ SOC 准确度取决于电芯与 profile 的匹配程度。本驱动给出的是 新增硬件验证页: -1. 创建 `main/demo_.c`,实现 `enter`、`exit`、`key`。 +1. 创建 `main/demo_.c`,实现 `enter`、`exit`、`key`;慢服务或页面私有任务另加可选的 `start`、`stop`。 2. 在 `main/demo.h` 声明,在 `main/CMakeLists.txt` 加源文件,在 `main.c` 的 `DEMOS[]` 注册。 -3. `enter` 创建并加载自己的 screen;`exit` 先停任务/定时器,再删 screen 和清空指针。 +3. `enter` 创建并加载自己的 screen;不持 LVGL 锁调用 `start`,用有界握手完成 `stop` 后,再由 `exit` 删除定时器、screen 并清空指针。 4. 页面文字保持英文;说明性注释可用中文。 -5. 慢操作放工作任务,结果通过 LVGL 锁更新界面。 +5. 慢操作放工作任务,结果通过短时 LVGL 锁更新界面;禁止在按键回调中启动或停止慢服务。 6. 保留 OK 长按返回这一全局交互,不在页面重复实现。 如果菜单项依赖新外设,还需扩展 `s_ok[]` 初始化与失败禁用逻辑。注意当前数组索引与 `DEMOS[]` 顺序隐式对应,修改顺序时必须同步核对。 @@ -426,7 +448,7 @@ idf.py flash monitor | 电池 | 合理 SOC 和 mV、无电量计时正确降级、断续 I2C 的错误恢复表现 | | Wi-Fi | 扫描总数和 SSID/RSSI 可见、OK 重扫描、反复进出后仍可扫描 | | Bluetooth LE | 手机看到 `FoloPassport`、OK 重启广播、退出后广播消失、反复进出无重启 | -| light/deep sleep | Low Power 页用 UP/DOWN 选择、OK 执行;light sleep 约 2 秒后原地恢复背光;deep sleep 约 5 秒后重启,页面显示 timer 唤醒和 RTC 保留计数 | +| light/deep sleep | Low Power 页用 UP/DOWN 选择、OK 执行;确认两种模式前 ES8311 回读校验通过;light sleep 约 2 秒后恢复 codec/音频和背光;deep sleep 中确认 CW2017 早于 ES8311、I2S/I2C 进入高阻、LCD 安全电平保持,约 5 秒后定时唤醒保留计数,重新初始化后音频/显示可用;分别测量板级电流 | | DMA/内存/UI | build 内存报告、运行时最小堆/最大块、音频与刷屏并发稳定性 | ## 14. 故障症状速查 diff --git a/docs/reference/README.md b/docs/reference/README.md index a16dcc4..491b089 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -24,7 +24,7 @@ The engineering rules themselves live under - [Audio Compression Trade-offs on ESP32-C3](shinku-chen/audio-compression-trade-offs.md) — how a voice-playback codec was chosen on limited flash (IMA-ADPCM vs Opus vs MP3), with measured capacity and decoder cost. - [Post-Release Follow-up for the AI Passport Publishing Flow](shinku-chen/post-release-follow-up.md) — confirm the publish destination, include the data partition in a release, and the consent gates for the post-release tracks. - [Display Refresh and Deep-sleep on ESP32-C3 (No PSRAM)](shinku-chen/display-refresh-and-deep-sleep.md) — direct panel refresh of a single image rect, RTC-GPIO deep-sleep wakeup, and the LVGL object-type misuse crash signature. -- [Shutting Down On-Board Peripherals Before Deep-Sleep](shinku-chen/deep-sleep-peripheral-power-off.md) — power the LCD panel, backlight, codec, and fuel gauge down before deep sleep, the `esp_codec_dev_close()` only-suspends-if-opened trap, and what software cannot fix (always-on PA, regulator). +- [Shutting Down On-Board Peripherals Before Deep-Sleep](shinku-chen/deep-sleep-peripheral-power-off.md) — verified register shutdown, shared-bus ordering, terminal GPIO states, LCD deep-sleep holds, the `esp_codec_dev_close()` opened-state trap, and remaining hardware loads. **Application playbooks:** diff --git a/docs/reference/README.zh_CN.md b/docs/reference/README.zh_CN.md index 060a376..08e5dd8 100644 --- a/docs/reference/README.zh_CN.md +++ b/docs/reference/README.zh_CN.md @@ -17,7 +17,7 @@ - [ESP32-C3 上音频压缩方式的权衡](shinku-chen/audio-compression-trade-offs.zh_CN.md) — 在有限 Flash 上如何为语音播放应用选编解码(IMA-ADPCM vs Opus vs MP3),含实测容量与解码器成本。 - [发布后收尾:AI Passport 发布流程的衔接](shinku-chen/post-release-follow-up.zh_CN.md) — 确认发布目的地、发布时包含数据分区、以及发布后收尾各轨道的同意门槛。 - [ESP32-C3(无 PSRAM)上的显示刷新与深睡](shinku-chen/display-refresh-and-deep-sleep.zh_CN.md) — 直接刷新单个图片矩形、RTC GPIO 深睡唤醒,以及 LVGL 对象类型误用的崩溃特征。 -- [深睡前关闭板载外设](shinku-chen/deep-sleep-peripheral-power-off.zh_CN.md) — 深睡前把 LCD 面板、背光、codec、电量计下电,`esp_codec_dev_close()` 只在「打开过」才 suspend 的坑,以及软件修不了的部分(常通功放、稳压器)。 +- [深睡前关闭板载外设](shinku-chen/deep-sleep-peripheral-power-off.zh_CN.md) — 寄存器校验关闭、共享总线顺序、终端 GPIO 状态、LCD deep-sleep hold、`esp_codec_dev_close()` 打开状态陷阱及剩余硬件负载。 **应用档案:** diff --git a/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.md b/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.md index c746836..a91c04a 100644 --- a/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.md +++ b/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.md @@ -4,87 +4,89 @@ # Shutting Down On-Board Peripherals Before Deep-Sleep -Captured after the **"Sound Effects Keychain"** v1.4.0 firmware release on the -voice-keychain edition (commit `ce9b13d`). These are general, upstream-benefiting -learnings that apply to any AI Passport app, not fork-specific customization. +This reference originated from the **"Sound Effects Keychain"** v1.4.0 firmware +on the voice-keychain edition (commit `ce9b13d`). The original device test +confirmed that the firmware slept after five idle minutes, woke on a button, +and reduced codec/panel/gauge draw. No standby-current value was measured. -> **Verification status.** All of the following was verified on device with the -> sound-keychain firmware: the device sleeps after 5 min idle and wakes on any -> button, and codec/panel/gauge draw drops in deep sleep. Standby-current numbers -> were not measured with a meter, so treat the magnitude claims as relative. +The upstream BSP now uses a more defensive shutdown contract than that historic +firmware. Its automated contracts and ESP-IDF build are checked, but its exact +current reduction still requires measurement on the target board. -## Why shut peripherals down at all +## Why peripheral shutdown is required -`esp_deep_sleep_start()` powers the MCU core down, but the peripherals that sit on -an always-on 3.3 V rail are **not** cut off — they keep drawing current even while -the chip sleeps. If the intent is minimum standby draw, each shuttable peripheral -must be told to enter its own low-power state before the chip sleeps. The MCU side -is handled for you; the peripheral side is not. +`esp_deep_sleep_start()` powers down the MCU core, but devices on the always-on +3.3 V rail remain powered. Each controllable peripheral must enter its own +low-power state before the MCU sleeps. Software suspend reduces operating blocks +and signal leakage; it does not disconnect the rail. -## The four shutdown calls, in order +## Current terminal shutdown order -Call these **after** arming the GPIO wake source and **before** -`esp_deep_sleep_start()`: +After configuring a wake source and stopping page-owned asynchronous work, use +this order before `esp_deep_sleep_start()`: -| Peripheral | Function | What it does | -|---|---|---| -| LCD panel | `bsp_display_sleep()` | `esp_lcd_panel_disp_on_off(panel, false)` (0x28 DISPOFF) then `esp_lcd_panel_disp_sleep(panel, true)` (0x10 panel sleep). A black screen is **not** powered down — the panel's controller still draws even with the backlight off and DISP off. | -| Backlight | `bsp_display_backlight(0)` | Set the LEDC duty to 0. Deep sleep also floats this un-held pin, so the LED is dark either way, but zeroing first is explicit. | -| Audio codec | `bsp_audio_sleep()` | Close the codec, which runs `es8311_suspend()` — writes 16 registers to stop the ADC/DAC, gate the clock, and disable the PA. | -| Fuel gauge | `bsp_battery_sleep()` | Put the CW2017 to sleep: write CONFIG 0x30 (restart) then 0xF0 (sleep). | +| Order | Interface | Result | +| ---: | --- | --- | +| 1 | `bsp_battery_sleep()` | Write CW2017 CONFIG sleep, wait 5 ms, read it back, and retry once if the write/readback does not match. | +| 2 | `bsp_audio_sleep()` | Run the complete ES8311 suspend sequence directly, verify six critical registers, retry once, and explicitly stop both I2S channels. | +| 3 | `bsp_audio_prepare_deep_sleep()` | Leave MCLK, BCLK, WS, DOUT, and DIN as inputs without internal pulls. | +| 4 | `bsp_i2c_prepare_deep_sleep()` | After both shared-bus devices finish, leave SDA/SCL as inputs without internal pulls. | +| 5 | `bsp_display_prepare_deep_sleep()` | With LVGL flushes blocked, send display-off and Sleep In, stop the backlight low, set LCD SPI safe levels, and hold them through deep sleep. | -## Gotcha: `esp_codec_dev_close()` only suspends if the codec layer was opened +The Wi-Fi and Bluetooth LE stacks belong to their individual demo pages and are +already stopped before the Low Power page starts. A product application with +long-lived radio services must stop those services before the LCD step. -The trap that cost the most debugging. `esp_codec_dev_close()` calls -`es8311_enable(false)` — which is what actually runs `es8311_suspend()` and powers -the chip down — **only** when the codec-dev layer's `output_opened`/`input_opened` -is true. Otherwise it falls straight through to cleanup and does nothing. +Peripheral register failures are logged but do not prevent the remaining +shutdown steps or deep sleep. Once I2S/I2C pins have been released, the path is +terminal: if deep-sleep entry unexpectedly returns, restart instead of trying to +resume partially detached buses. -Your own `s_opened` flag mirrors that: it is only true after a -`bsp_audio_set_format()` succeeds. So if the device **never plays any audio before -timing out into deep sleep**, `s_opened == false`, the close is skipped, and the -chip sits in the `es8311_open` configuration state — configured but **not** -powered down. The fix is to guarantee the suspend sequence runs on every path: +## Why `esp_codec_dev_close()` is insufficient -```c -esp_err_t bsp_audio_sleep(void) { - if (!s_dev) return ESP_ERR_INVALID_STATE; - if (!s_opened) { - bsp_audio_set_format(16000, 16, 1); // silent open — no sound, just takes the codec-dev layer open - } - esp_codec_dev_close(s_dev); // now really runs es8311_suspend() - s_opened = false; - return ESP_OK; -} -``` +`esp_codec_dev_close()` only invokes the ES8311 disable path when the codec-dev +input or output was opened. A boot that never played or recorded audio can skip +that path even though the ES8311 control interface and I2S channels were already +initialized. -The added `set_format` is silent (it never writes PCM), only completes the -codec-dev `open` path so the subsequent `close` triggers the suspend. A `s_dev` -that exists but was never opened is exactly the case that silently leaked. +The BSP therefore writes the suspend registers through the independent control +interface rather than performing a silent default-format open. It also sets +REG45 to `0x01` to disable the internal BCLK/LRCK pull-ups, reads back registers +`0x00`, `0x01`, `0x0D`, `0x0E`, `0x12`, and `0x45`, and retries the full sequence +once after 5 ms. This works whether or not PCM was previously opened. -## The MCU side is already handled — don't redo it +REG0E is written as `0xFF`, but only bits 6:0 are checked: mask `0x7F`, expected +value `0x7F`. A readback of either `0x7F` or `0xFF` passes. Comparing bit 7 would +falsely reject a successful suspend on hardware where it reads as zero. The +other five registers retain full-byte checks, and I2C errors or mismatches in +checked bits still trigger retry and failure. The Low Power demo cancels light +sleep on a real suspend failure and attempts audio recovery; deep sleep logs +the failure and continues shutting down. -`esp_deep_sleep_start()` automatically calls `esp_sleep_isolate_digital_gpio()` -on this platform (ESP32-C3 does **not** define `SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP`, -so the `#if !SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP` branch always runs). That -floats every un-held digital GPIO — including the I2S, I2C, and SPI pins — and -disables their internal pull-ups/pull-downs. So there is no MCU-side leakage path -to chase; the residual draw is purely the peripherals on the rail (and, outside -the chip, the external PA and the 3.3 V regulator, which are out of software reach). +## MCU pins still need an explicit terminal state + +ESP-IDF isolates unheld digital GPIOs while entering deep sleep, but explicit +pin release is still useful before entry: it stops I2S clocks immediately, +removes MCU internal I2C pulls after the last transaction, and makes the +transition contract testable. External I2C pull-ups remain a hardware load. + +LCD pins are the exception to floating: CS is held high, while SCLK, MOSI, DC, +and backlight are held low. On deep-sleep wake, `bsp_display_init()` releases the +global and per-pin holds before SPI and LEDC take ownership. ## What software cannot fix -The board's power amplifier uses `BSP_I2S_PA_CTRL = -1`, meaning the PA enable pin -is **not** wired to the MCU — it is hardware always-on. Powering it off requires a -board change (wire the enable pin, or put the PA on a switchable rail). Similarly, -the 3.3 V rail's own regulator quiescent current and cell self-discharge are not -software-addressable. If standby is still high after all four calls, the remaining -draw is almost certainly these hardware constants. +`BSP_I2S_PA_CTRL = -1` means the amplifier enable is not wired to the MCU. The +amplifier's standby current, regulator quiescent current, external pull-up +current, and battery self-discharge cannot be removed by these APIs. If measured +standby draw is still high after register readback passes, isolate these hardware +loads individually. -## A real wake-from-sleep pitfall that overlaps this work +## Wake and recovery boundary -While here, note the related wakeup gotcha recorded separately in -[`display-refresh-and-deep-sleep.md`](display-refresh-and-deep-sleep.md): the -wake-source argument is a **pin bitmask**, not a pin number. It is easy to re-verify -both together — after these shutdown calls, wake on GPIO0 low and confirm the app -re-initializes the peripherals it just shut down. +The upstream Low Power demo uses RTC timer wake only because the shared ADC +button node has no confirmed deep-sleep wake contract in this repository. Deep +sleep restarts the application; normal BSP initialization releases LCD holds and +reinitializes display, audio, I2S, and I2C. Light sleep must not call any of the +terminal pin-release or LCD-hold interfaces and instead resumes audio with +`bsp_audio_wake()`. diff --git a/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.zh_CN.md b/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.zh_CN.md index 002877e..20194cf 100644 --- a/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.zh_CN.md +++ b/docs/reference/shinku-chen/deep-sleep-peripheral-power-off.zh_CN.md @@ -4,75 +4,74 @@ # 深睡前关闭板载外设 -在「音效钥匙扣」v1.4.0 固件、voice-keychain 版本(提交 `ce9b13d`)发布后沉淀。 -这些是通用、上游受益的经验,适用于任何 AI Passport 应用,而非 fork 专属定制。 +本参考最初沉淀自「音效钥匙扣」v1.4.0 固件的 voice-keychain 版本 +(提交 `ce9b13d`)。原真机测试确认固件可在空闲五分钟后休眠、按键唤醒, +且 codec/面板/电量计的深睡功耗下降,但没有测量具体待机电流。 -> **验证状态。** 以下均已在本项目「音效钥匙扣」固件上真机验证:空闲 5 分钟入睡、 -> 任意按键可唤醒、codec/面板/电量计在深睡时电流下降。待机电流数值未用万用表实测, -> 故“量级”描述请视为相对大小,不是确切读数。 +上游 BSP 现在采用了比该历史固件更严格的关闭契约。其自动化契约与 ESP-IDF +编译已检查,实际电流改善幅度仍需在目标板上测量。 -## 为什么要关外设 +## 为什么必须关闭外设 -`esp_deep_sleep_start()` 只把 MCU 核心断电,但挂在常通 3.3 V 轨上的**外设并不会** -被切断——它们仍在耗电。若目标是极低待机,每个可关的外设都必须在芯片入睡前被 -点名进入自己的低功耗态。MCU 侧有框架代劳,外设侧没有。 +`esp_deep_sleep_start()` 会关闭 MCU 核心,但常通 3.3 V 电源轨上的器件仍然 +供电。MCU 入睡前,每个可控外设都必须进入自己的低功耗状态。软件 suspend +可减少工作模块和信号泄漏,但不会切断电源轨。 -## 四条关机调用,按顺序 +## 当前终端关闭顺序 -在**配好 GPIO 唤醒源之后**、`esp_deep_sleep_start()` 之前调用这些: +配置唤醒源并停止页面持有的异步工作后,在 `esp_deep_sleep_start()` 前按 +以下顺序执行: -| 外设 | 函数 | 做了什么 | -|---|---|---| -| LCD 面板 | `bsp_display_sleep()` | `esp_lcd_panel_disp_on_off(panel, false)`(0x28 DISPOFF)再 `esp_lcd_panel_disp_sleep(panel, true)`(0x10 面板睡眠)。**黑屏并不等于下电**——就算背光灭、DISP 关,面板控制器仍在耗电。 | -| 背光 | `bsp_display_backlight(0)` | 把 LEDC 占空比归零。深睡本就会把该未被 hold 的引脚浮空,LED 反正灭,但先归零更明确。 | -| 音频 codec | `bsp_audio_sleep()` | 关闭 codec,内部走 `es8311_suspend()`——写 16 个寄存器停掉 ADC/DAC、门控时钟、禁用 PA。 | -| 电量计 | `bsp_battery_sleep()` | 让 CW2017 进睡眠:写 CONFIG 0x30(重启)再 0xF0(睡眠)。 | +| 顺序 | 接口 | 结果 | +| ---: | --- | --- | +| 1 | `bsp_battery_sleep()` | 写入 CW2017 CONFIG 睡眠值,等待 5 ms 后回读;写入/回读不符时重试一次。 | +| 2 | `bsp_audio_sleep()` | 直接执行完整 ES8311 suspend 序列,校验六个关键寄存器,失败重试一次,并显式停止两条 I2S channel。 | +| 3 | `bsp_audio_prepare_deep_sleep()` | 将 MCLK、BCLK、WS、DOUT 和 DIN 设为关闭内部上下拉的输入。 | +| 4 | `bsp_i2c_prepare_deep_sleep()` | 两个共享总线外设都完成后,将 SDA/SCL 设为关闭内部上下拉的输入。 | +| 5 | `bsp_display_prepare_deep_sleep()` | 阻止 LVGL flush 后,发送关闭显示和 Sleep In,将背光停在低电平,设置 LCD SPI 安全电平并在深睡期间保持。 | -## 坑:`esp_codec_dev_close()` 只在 codec 层「被打开过」时才真正 suspend +Wi-Fi 和 Bluetooth LE 协议栈由各自 demo 页持有,进入 Low Power 页前已经 +停止。若产品应用让无线服务长期存活,必须在 LCD 步骤前另行停止它们。 -最花调试时间的一个坑。真正执行 `es8311_suspend()`、把芯片下电的是 -`es8311_enable(false)`,而 `esp_codec_dev_close()` **只在** codec-dev 层的 -`output_opened`/`input_opened` 为 true 时才走到它;否则直接进 cleanup,什么都不做。 +外设寄存器失败会记录日志,但不会阻止后续关闭步骤和 deep sleep。I2S/I2C +引脚释放后已进入终端路径;若 deep-sleep 入口意外返回,应重启,不应尝试恢复 +已部分脱离的总线。 -你自己维护的 `s_opened` 正好镜像这一点:它只在 `bsp_audio_set_format()` 成功后 -才为 true。所以如果设备**开机后从未播放任何音频就超时深睡**,`s_opened == false`, -close 被跳过,芯片停在 `es8311_open` 的配置态——配好寄存器了,但**没有下电**。 -修复是保证任何时序都走完 suspend 序列: +## 为什么 `esp_codec_dev_close()` 不够 -```c -esp_err_t bsp_audio_sleep(void) { - if (!s_dev) return ESP_ERR_INVALID_STATE; - if (!s_opened) { - bsp_audio_set_format(16000, 16, 1); // 无声打开——不发声,只是把 codec-dev 层走成 open - } - esp_codec_dev_close(s_dev); // 这次才真的跑 es8311_suspend() - s_opened = false; - return ESP_OK; -} -``` +`esp_codec_dev_close()` 只在 codec-dev 输入或输出曾被打开时才调用 ES8311 disable +路径。开机后从未播放或录音时,即使 ES8311 控制接口和 I2S channel 已初始化, +该路径也可能被跳过。 -多出来的 `set_format` 是无声的(从不写 PCM),只是补完 codec-dev 的 `open` 路径, -让随后的 `close` 真正触发 suspend。「`s_dev` 存在但从未 open 过」正是那个静默泄漏的场景。 +因此 BSP 不再做默认格式的无声 open,而是通过独立控制接口写入 suspend +寄存器。它还将 REG45 设为 `0x01` 以关闭 BCLK/LRCK 内部上拉,回读 `0x00`、 +`0x01`、`0x0D`、`0x0E`、`0x12` 和 `0x45`,并在 5 ms 后重试一次完整序列。 +无论之前是否打开 PCM,该路径都能执行。 -## MCU 侧已经代劳,无需再处理 +REG0E 写入值仍为 `0xFF`,但只校验 bit6:0:掩码和预期值均为 `0x7F`。 +读回 `0x7F` 或 `0xFF` 都通过。在 bit7 读为零的硬件上,比较该位会把成功的 +suspend 误判为失败。其余五个寄存器仍做完整字节校验,I2C 错误或参与校验的位 +不符仍触发重试和失败。真正 suspend 失败时,Low Power demo 会取消 light sleep +并尝试恢复音频;deep sleep 则记录失败并继续关闭流程。 -在此平台上 `esp_deep_sleep_start()` 会自动调用 `esp_sleep_isolate_digital_gpio()` -(ESP32-C3 **未定义** `SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP`, -所以 `#if !SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP` 分支一定会走)。它把每个 -未被 hold 的数字 GPIO——包括 I2S、I2C、SPI 引脚——全部浮空,并禁用其内部上/下拉。 -所以没有任何 MCU 侧漏电路径需要追;残余耗电纯粹来自轨上的外设(以及芯片之外、 -代码够不着的功放和 3.3 V 稳压器)。 +## MCU 引脚仍需明确的终端状态 -## 软件修不了的部分 +ESP-IDF 在进入 deep sleep 时会隔离未 hold 的数字 GPIO,但显式释放引脚仍有价值: +它可立即停止 I2S 时钟,在最后一笔事务后去掉 MCU 内部 I2C 上拉,并让过渡契约 +可自动检查。外部 I2C 上拉仍是硬件负载。 -本板功放用 `BSP_I2S_PA_CTRL = -1`,即 PA 使能脚**没有接到 MCU**——硬件常通。 -要断它只能改板(接使能脚,或把功放放到可切换的电源轨上)。同理,3.3 V 轨稳压器 -自身的静态电流和电池自放电也不是软件能插手的。四条调用全上待机仍偏高时,剩下的 -大头几乎可以肯定是这些硬件常量。 +LCD 引脚是不浮空的例外:CS 保持高电平,SCLK、MOSI、DC 和背光保持低电平。 +deep-sleep 唤醒后,`bsp_display_init()` 会在 SPI 和 LEDC 接管前解除全局及单引脚 hold。 -## 与本工作重叠的一个真实唤醒坑 +## 软件无法修复的部分 -顺带一提,相关的唤醒坑已单独记录在 -[`display-refresh-and-deep-sleep.zh_CN.md`](display-refresh-and-deep-sleep.zh_CN.md): -唤醒源参数是**引脚位掩码**,不是引脚号。两者可以一起复核——跑完这些关机调用后, -用 GPIO0 低电平唤醒,确认应用会重新初始化它刚关掉的外设。 +`BSP_I2S_PA_CTRL = -1` 表示功放使能脚没有接到 MCU。功放待机电流、稳压器静态 +电流、外部上拉电流和电池自放电都无法由这些 API 消除。寄存器回读通过后若待机 +电流仍偏高,应逐一隔离并测量这些硬件负载。 + +## 唤醒与恢复边界 + +上游 Low Power demo 只使用 RTC 定时器唤醒,因为本仓库尚未定义共享 ADC 按键 +节点的可靠 deep-sleep 唤醒契约。deep sleep 会重启应用;正常 BSP 初始化将解除 LCD +hold,并重新初始化显示、音频、I2S 和 I2C。light sleep 不得调用任何终端引脚释放 +或 LCD hold 接口,而应使用 `bsp_audio_wake()` 恢复音频。 diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index bfc7673..d39c848 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,5 +1,6 @@ idf_component_register( SRCS "main.c" + "demo_navigation.c" "ui_pixel.c" "ui_pixel_math.c" "demo_display.c" diff --git a/main/demo.h b/main/demo.h index f5891fb..a9258d9 100644 --- a/main/demo.h +++ b/main/demo.h @@ -1,14 +1,16 @@ // main/demo.h —— 每个演示页实现的统一接口。 -// 新增一个演示页 = 实现这三个函数 + 在 main.c 的 DEMOS[] 里加一行。 +// 新增演示页 = 实现 enter/exit/key,慢服务按需实现 start/stop,再注册到 DEMOS[]。 #pragma once #include "bsp_button.h" typedef struct { const char *name; - void (*enter)(void); // 建自己的屏并载入 - void (*exit)(void); // 删屏、停定时器、释放资源 - void (*key)(bsp_btn_t btn, bsp_btn_ev_t ev); // 收按键(长按确定已被 main 拦截) + void (*enter)(void); // 持 LVGL 锁创建并载入页面 + void (*exit)(void); // lifecycle stop 成功后,持 LVGL 锁删除页面 + void (*key)(bsp_btn_t btn, bsp_btn_ev_t ev); // lifecycle task 调用;函数自行缩短 LVGL 锁范围 + esp_err_t (*start)(void); // 可选:页面创建后,不持 LVGL 锁启动慢服务 + esp_err_t (*stop)(void); // 可选:删页面前,不持 LVGL 锁停止 producer } demo_entry_t; // 各演示页(定义在各自的 .c 里) @@ -20,15 +22,19 @@ void demo_button_key(bsp_btn_t btn, bsp_btn_ev_t ev); void demo_audio_enter(void); void demo_audio_exit(void); void demo_audio_key(bsp_btn_t btn, bsp_btn_ev_t ev); +esp_err_t demo_audio_start(void); esp_err_t demo_audio_stop(void); void demo_battery_enter(void); void demo_battery_exit(void); void demo_battery_key(bsp_btn_t btn, bsp_btn_ev_t ev); void demo_wifi_enter(void); void demo_wifi_exit(void); void demo_wifi_key(bsp_btn_t btn, bsp_btn_ev_t ev); +esp_err_t demo_wifi_start(void); esp_err_t demo_wifi_stop(void); void demo_ble_enter(void); void demo_ble_exit(void); void demo_ble_key(bsp_btn_t btn, bsp_btn_ev_t ev); +esp_err_t demo_ble_start(void); esp_err_t demo_ble_stop(void); void demo_low_power_enter(void); void demo_low_power_exit(void); void demo_low_power_key(bsp_btn_t btn, bsp_btn_ev_t ev); +esp_err_t demo_low_power_start(void); esp_err_t demo_low_power_stop(void); diff --git a/main/demo_audio.c b/main/demo_audio.c index e4659ff..fc70c3e 100644 --- a/main/demo_audio.c +++ b/main/demo_audio.c @@ -1,11 +1,15 @@ // main/demo_audio.c —— 播 1kHz 方波 / 录 3 秒后回放。 // 音频收发会阻塞较久,故放到独立任务里跑,不占用按键回调与 LVGL 任务。 +// Continuous BGM + UI/NVS needs feed-latency and Flash/cache checks; a tone alone +// does not validate this. See docs/hardware-design/AI_HARDWARE_DEVELOPMENT_GUIDE.md +// section 8.1 before reusing this demo for continuous playback. #include "demo.h" #include "bsp_audio.h" #include "bsp_display.h" // bsp_lvgl_lock / bsp_lvgl_unlock(音频任务里操作 LVGL 要加锁) #include "ui_pixel.h" #include "lvgl.h" #include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" #include "freertos/task.h" #include "esp_log.h" #include @@ -18,10 +22,18 @@ static const char *TAG = "demo_audio"; #define TONE_MS 1000 #define RECORD_SEC 3 #define CHUNK_SAMPLES 512 // 每次收发的采样数,控制临时缓冲大小 +#define AUDIO_STOP_TIMEOUT_MS 2000 + +typedef enum { + AUDIO_COMMAND_TONE = 1, + AUDIO_COMMAND_RECORD, + AUDIO_COMMAND_STOP, +} audio_command_t; static lv_obj_t *s_scr, *s_status, *s_mascot; static TaskHandle_t s_task; -static volatile int s_req; // 1=播音 2=录音回放 0=空闲 +static SemaphoreHandle_t s_stopped; +static volatile bool s_cancel; // LVGL 对象只能在持锁时操作;本函数从音频任务调用,故内部加锁。 static void set_status(const char *text) { @@ -41,17 +53,20 @@ static void play_tone(void) { const int period = SAMPLE_RATE / TONE_HZ; // 每个方波周期的采样数 int total = SAMPLE_RATE * TONE_MS / 1000; int phase = 0; - while (total > 0) { + while (total > 0 && !s_cancel) { int n = total < CHUNK_SAMPLES ? total : CHUNK_SAMPLES; for (int i = 0; i < n; i++) { buf[i] = (phase < period / 2) ? 6000 : -6000; if (++phase >= period) phase = 0; } - bsp_audio_write(buf, (size_t)n * sizeof(int16_t)); + if (bsp_audio_write(buf, (size_t)n * sizeof(int16_t)) != ESP_OK) { + set_status("playback failed"); + break; + } total -= n; } free(buf); - set_status("done. OK: tone UP: record"); + if (!s_cancel && total == 0) set_status("done. OK: tone UP: record"); } static void record_and_play(void) { @@ -69,29 +84,41 @@ static void record_and_play(void) { set_status("recording 3s... speak now"); size_t got = 0; - while (got < total) { + while (got < total && !s_cancel) { size_t n = (total - got) < CHUNK_SAMPLES ? (total - got) : CHUNK_SAMPLES; if (bsp_audio_read(rec + got, n * sizeof(int16_t)) != ESP_OK) break; got += n; } - set_status("playing back..."); - bsp_audio_set_volume(80); - for (size_t off = 0; off < got; off += CHUNK_SAMPLES) { - size_t n = (got - off) < CHUNK_SAMPLES ? (got - off) : CHUNK_SAMPLES; - bsp_audio_write(rec + off, n * sizeof(int16_t)); + if (!s_cancel) { + set_status("playing back..."); + bsp_audio_set_volume(80); + } + size_t played = 0; + while (played < got && !s_cancel) { + size_t n = (got - played) < CHUNK_SAMPLES ? (got - played) : CHUNK_SAMPLES; + if (bsp_audio_write(rec + played, n * sizeof(int16_t)) != ESP_OK) { + set_status("playback failed"); + break; + } + played += n; } free(rec); - set_status("done. OK: tone UP: record"); + if (!s_cancel && played == got) set_status("done. OK: tone UP: record"); } static void audio_task(void *arg) { (void)arg; for (;;) { - if (s_req == 1) { s_req = 0; play_tone(); } - else if (s_req == 2) { s_req = 0; record_and_play(); } - else vTaskDelay(pdMS_TO_TICKS(50)); + uint32_t command = 0; + if (xTaskNotifyWait(0, UINT32_MAX, &command, portMAX_DELAY) != pdTRUE) continue; + if (command == AUDIO_COMMAND_STOP) break; + if (command == AUDIO_COMMAND_TONE) play_tone(); + else if (command == AUDIO_COMMAND_RECORD) record_and_play(); } + if (s_stopped) xSemaphoreGive(s_stopped); + s_task = NULL; + vTaskDelete(NULL); } void demo_audio_enter(void) { @@ -116,20 +143,66 @@ void demo_audio_enter(void) { s_mascot = ui_pixel_mascot_create(s_scr, 101, 238); - s_req = 0; - if (!s_task) xTaskCreate(audio_task, "demo_audio", 4096, NULL, 4, &s_task); lv_screen_load(s_scr); } +esp_err_t demo_audio_start(void) { + if (s_task) return ESP_OK; + if (s_stopped) { + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + } + s_stopped = xSemaphoreCreateBinary(); + if (!s_stopped) { + set_status("Cannot create audio worker"); + return ESP_ERR_NO_MEM; + } + s_cancel = false; + if (xTaskCreate(audio_task, "demo_audio", 4096, NULL, 4, &s_task) != pdPASS) { + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + set_status("Cannot create audio worker"); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +esp_err_t demo_audio_stop(void) { + TaskHandle_t task = s_task; + if (!task) { + if (s_stopped) { + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + } + return ESP_OK; + } + + s_cancel = true; + xTaskNotify(task, AUDIO_COMMAND_STOP, eSetValueWithOverwrite); + if (!s_stopped || + xSemaphoreTake(s_stopped, pdMS_TO_TICKS(AUDIO_STOP_TIMEOUT_MS)) != pdTRUE) { + set_status("Audio stop timed out; retry"); + return ESP_ERR_TIMEOUT; + } + s_task = NULL; + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + return ESP_OK; +} + void demo_audio_exit(void) { - s_req = 0; - if (s_task) { vTaskDelete(s_task); s_task = NULL; } if (s_scr) { lv_obj_delete(s_scr); s_scr = NULL; s_status = s_mascot = NULL; } } void demo_audio_key(bsp_btn_t btn, bsp_btn_ev_t ev) { - if (ev != BSP_BTN_CLICK) return; - if (btn == BSP_BTN_OK) s_req = 1; - if (btn == BSP_BTN_UP) s_req = 2; - if (btn == BSP_BTN_OK || btn == BSP_BTN_UP) ui_pixel_mascot_jump(s_mascot); + if (ev != BSP_BTN_CLICK || !s_task || s_cancel) return; + uint32_t command = 0; + if (btn == BSP_BTN_OK) command = AUDIO_COMMAND_TONE; + else if (btn == BSP_BTN_UP) command = AUDIO_COMMAND_RECORD; + if (!command) return; + + xTaskNotify(s_task, command, eSetValueWithOverwrite); + if (!bsp_lvgl_lock(250)) return; + if (s_mascot) ui_pixel_mascot_jump(s_mascot); + bsp_lvgl_unlock(); } diff --git a/main/demo_ble.c b/main/demo_ble.c index 9e564ab..2c1b3ca 100644 --- a/main/demo_ble.c +++ b/main/demo_ble.c @@ -19,6 +19,8 @@ static const char *TAG = "demo_ble"; static const char *DEVICE_NAME = "FoloPassport"; +#define BLE_STOP_TIMEOUT_MS 2000 + typedef enum { BLE_DEMO_OFF = 0, BLE_DEMO_STARTING, @@ -35,6 +37,8 @@ static volatile int s_error; static uint8_t s_addr_type; static bool s_initialized; static bool s_start_requested; +static bool s_stop_in_progress; +static bool s_host_done; static int gap_event(struct ble_gap_event *event, void *arg); @@ -95,7 +99,7 @@ static void host_task(void *arg) nimble_port_freertos_deinit(); } -static esp_err_t ble_start(void) +esp_err_t demo_ble_start(void) { if (s_initialized) { s_error = ESP_ERR_INVALID_STATE; @@ -104,6 +108,8 @@ static esp_err_t ble_start(void) } s_state = BLE_DEMO_STARTING; + s_stop_in_progress = false; + s_host_done = false; esp_err_t err = demo_radio_nvs_prepare(); if (err != ESP_OK) { s_error = err; @@ -147,28 +153,50 @@ static esp_err_t ble_start(void) return ESP_OK; } -static void ble_stop(void) +esp_err_t demo_ble_stop(void) { s_start_requested = false; - if (!s_initialized) return; + if (!s_initialized) return ESP_OK; - ble_gap_adv_stop(); - int rc = nimble_port_stop(); - if (rc == 0 && s_host_stopped) { - // host callback 不访问 LVGL;即使页面 exit 持有 LVGL 锁也不会形成锁环。 - xSemaphoreTake(s_host_stopped, portMAX_DELAY); + if (!s_stop_in_progress) { + (void)ble_gap_adv_stop(); + int rc = nimble_port_stop(); + if (rc != 0) { + ESP_LOGE(TAG, "nimble_port_stop 失败: %d", rc); + s_error = rc; + s_state = BLE_DEMO_FAILED; + return ESP_FAIL; + } + s_stop_in_progress = true; } - if (rc == 0) { - nimble_port_deinit(); - s_initialized = false; - } else { - ESP_LOGE(TAG, "nimble_port_stop 失败: %d", rc); + + if (!s_host_done) { + if (!s_host_stopped || + xSemaphoreTake(s_host_stopped, pdMS_TO_TICKS(BLE_STOP_TIMEOUT_MS)) != pdTRUE) { + ESP_LOGE(TAG, "等待 NimBLE host 停止超时"); + s_error = ESP_ERR_TIMEOUT; + s_state = BLE_DEMO_FAILED; + return ESP_ERR_TIMEOUT; + } + s_host_done = true; } - if (!s_initialized && s_host_stopped) { + + esp_err_t err = nimble_port_deinit(); + if (err != ESP_OK) { + ESP_LOGE(TAG, "nimble_port_deinit 失败: %s", esp_err_to_name(err)); + s_error = err; + s_state = BLE_DEMO_FAILED; + return err; + } + s_initialized = false; + s_stop_in_progress = false; + s_host_done = false; + if (s_host_stopped) { vSemaphoreDelete(s_host_stopped); s_host_stopped = NULL; } s_state = BLE_DEMO_OFF; + return ESP_OK; } static void tick(lv_timer_t *timer) @@ -203,7 +231,7 @@ void demo_ble_enter(void) ui_pixel_mascot_create(s_scr, 101, 244); s_timer = lv_timer_create(tick, 100, NULL); lv_screen_load(s_scr); - ble_start(); + s_state = BLE_DEMO_STARTING; } void demo_ble_exit(void) @@ -212,7 +240,6 @@ void demo_ble_exit(void) lv_timer_delete(s_timer); s_timer = NULL; } - ble_stop(); if (s_scr) { lv_obj_delete(s_scr); s_scr = NULL; @@ -222,7 +249,8 @@ void demo_ble_exit(void) void demo_ble_key(bsp_btn_t btn, bsp_btn_ev_t ev) { - if (btn != BSP_BTN_OK || ev != BSP_BTN_CLICK || !s_initialized) return; + if (btn != BSP_BTN_OK || ev != BSP_BTN_CLICK || + !s_initialized || s_state != BLE_DEMO_ADVERTISING) return; ble_gap_adv_stop(); int rc = advertise(); if (rc != 0) { diff --git a/main/demo_button.c b/main/demo_button.c index 85b9065..3d9b01a 100644 --- a/main/demo_button.c +++ b/main/demo_button.c @@ -2,6 +2,7 @@ // 电压显示是本页的核心:换了分压/上拉阻值的开发者靠它重标 BSP_BTN_MV_TABLE。 #include "demo.h" #include "bsp_button.h" +#include "bsp_display.h" #include "ui_pixel.h" #include "lvgl.h" #include @@ -69,7 +70,11 @@ void demo_button_exit(void) { } void demo_button_key(bsp_btn_t btn, bsp_btn_ev_t ev) { + if ((unsigned)btn >= sizeof(BTN_NAME) / sizeof(BTN_NAME[0]) || + (unsigned)ev >= sizeof(EV_NAME) / sizeof(EV_NAME[0])) return; char line[32]; snprintf(line, sizeof(line), "%s: %s", BTN_NAME[btn], EV_NAME[ev]); + if (!bsp_lvgl_lock(250)) return; log_push(line); + bsp_lvgl_unlock(); } diff --git a/main/demo_display.c b/main/demo_display.c index 136dbc9..e5081ce 100644 --- a/main/demo_display.c +++ b/main/demo_display.c @@ -51,6 +51,7 @@ void demo_display_exit(void) { void demo_display_key(bsp_btn_t btn, bsp_btn_ev_t ev) { if (ev != BSP_BTN_CLICK) return; + if (!bsp_lvgl_lock(250)) return; if (btn == BSP_BTN_OK) { s_color_idx = (s_color_idx + 1) % COLOR_COUNT; ui_pixel_mascot_jump(s_mascot); @@ -60,4 +61,5 @@ void demo_display_key(bsp_btn_t btn, bsp_btn_ev_t ev) { bsp_display_backlight(BL_LEVELS[s_bl_idx]); } refresh(); + bsp_lvgl_unlock(); } diff --git a/main/demo_low_power.c b/main/demo_low_power.c index 3ab1615..32ce4f7 100644 --- a/main/demo_low_power.c +++ b/main/demo_low_power.c @@ -1,15 +1,22 @@ // main/demo_low_power.c —— light/deep sleep + RTC timer 唤醒验证。 +// 两种模式入睡前均 suspend ES8311;light sleep 返回后显式恢复。 +// deep sleep 还会按 CW2017 -> ES8311 -> I2S -> 共享 I2C -> LCD 顺序停止外设。 // 不使用按键唤醒:仓库尚无板级唤醒电路证据。 #include "demo.h" +#include "bsp_audio.h" +#include "bsp_battery.h" #include "bsp_display.h" +#include "bsp_i2c.h" #include "ui_pixel.h" #include "esp_attr.h" #include "esp_log.h" #include "esp_err.h" #include "esp_sleep.h" +#include "esp_system.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" #include "freertos/task.h" #include "lvgl.h" #include @@ -20,10 +27,12 @@ static const char *TAG = "demo_power"; #define LIGHT_SLEEP_TIME_US (2ULL * 1000ULL * 1000ULL) #define DEEP_SLEEP_TIME_US (5ULL * 1000ULL * 1000ULL) #define DEEP_SLEEP_MAGIC 0x464F4C4FUL +#define SLEEP_STOP_TIMEOUT_MS 3000 typedef enum { SLEEP_COMMAND_LIGHT = 1, SLEEP_COMMAND_DEEP, + SLEEP_COMMAND_STOP, } sleep_command_t; static lv_obj_t *s_scr; @@ -31,11 +40,21 @@ static lv_obj_t *s_status; static lv_obj_t *s_mode_cards[2]; static lv_obj_t *s_mascot; static TaskHandle_t s_task; +static SemaphoreHandle_t s_stopped; static volatile bool s_busy; +static volatile bool s_stop_requested; static int s_selected; static RTC_DATA_ATTR uint32_t s_deep_sleep_magic; static RTC_DATA_ATTR uint32_t s_deep_sleep_count; +static void log_deep_sleep_warning(const char *step, esp_err_t error) +{ + if (error != ESP_OK) { + ESP_LOGW(TAG, "deep sleep 继续:%s 失败: %s", step, + esp_err_to_name(error)); + } +} + static void menu_refresh(void) { for (int i = 0; i < 2; i++) { @@ -56,34 +75,81 @@ static void sleep_task(void *arg) for (;;) { uint32_t command = 0; xTaskNotifyWait(0, UINT32_MAX, &command, portMAX_DELAY); - if (!s_scr) continue; + if (command == SLEEP_COMMAND_STOP || s_stop_requested) break; s_busy = true; if (command == SLEEP_COMMAND_DEEP) { set_status("DEEP SLEEP: 5 SEC\nApplication will restart"); vTaskDelay(pdMS_TO_TICKS(250)); + if (s_stop_requested) { + s_busy = false; + break; + } esp_err_t err = esp_sleep_enable_timer_wakeup(DEEP_SLEEP_TIME_US); if (err == ESP_OK) { + // CW2017 与 ES8311 共用 I2C,必须先完成电量计写入/回读。 + log_deep_sleep_warning("CW2017 suspend", bsp_battery_sleep()); + log_deep_sleep_warning("ES8311 suspend", bsp_audio_sleep()); + // 即使 codec 寄存器操作失败,也继续停时钟并释放引脚。 + log_deep_sleep_warning("I2S pin release", + bsp_audio_prepare_deep_sleep()); + log_deep_sleep_warning("shared I2C pin release", + bsp_i2c_prepare_deep_sleep()); + + // Wi-Fi/BLE 只由各自 demo 页持有;进入本页前已经停止并释放。 + // 加锁等待当前 flush 完成,然后阻止 LVGL 在 LCD 关闭后再刷屏。 + if (!bsp_lvgl_lock(1000)) { + ESP_LOGE(TAG, "deep sleep 前无法停止 LVGL 刷屏,重启恢复外设"); + esp_restart(); + } + log_deep_sleep_warning("ST7789 suspend", + bsp_display_prepare_deep_sleep()); + if (s_deep_sleep_magic != DEEP_SLEEP_MAGIC) s_deep_sleep_count = 0; s_deep_sleep_magic = DEEP_SLEEP_MAGIC; s_deep_sleep_count++; - bsp_display_backlight(0); esp_deep_sleep_start(); + // 从 deep-sleep 准备接口返回后总线已不可在本次运行中恢复。 + ESP_LOGE(TAG, "esp_deep_sleep_start 意外返回,重启恢复外设"); + esp_restart(); } + esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER); char text[96]; snprintf(text, sizeof(text), "Deep sleep failed:\n%s", esp_err_to_name(err)); set_status(text); - ESP_LOGE(TAG, "deep sleep 失败: %s", esp_err_to_name(err)); + ESP_LOGE(TAG, "Deep sleep 失败: %s", esp_err_to_name(err)); } else { + const char *failure = "Light sleep"; + bool audio_suspend_attempted = false; set_status("LIGHT SLEEP: 2 SEC\nTimer wakeup"); vTaskDelay(pdMS_TO_TICKS(150)); - bsp_display_backlight(0); - + if (s_stop_requested) { + s_busy = false; + break; + } esp_err_t err = esp_sleep_enable_timer_wakeup(LIGHT_SLEEP_TIME_US); + if (err == ESP_OK) { + audio_suspend_attempted = true; + err = bsp_audio_sleep(); + failure = "Audio suspend"; + } + if (err == ESP_OK) bsp_display_backlight(0); int64_t before = esp_timer_get_time(); - if (err == ESP_OK) err = esp_light_sleep_start(); + if (err == ESP_OK) { + failure = "Light sleep"; + err = esp_light_sleep_start(); + } int64_t slept_ms = (esp_timer_get_time() - before) / 1000; esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER); + // bsp_audio_sleep() 可能在已停 I2S 后报寄存器校验失败, + // 因此只要尝试过 suspend,未进入 light sleep 也必须恢复。 + if (audio_suspend_attempted) { + esp_err_t wake_err = bsp_audio_wake(); + if (err == ESP_OK && wake_err != ESP_OK) { + err = wake_err; + failure = "Audio resume"; + } + } bsp_display_backlight(100); char text[128]; @@ -91,13 +157,17 @@ static void sleep_task(void *arg) snprintf(text, sizeof(text), "LIGHT WAKE: TIMER\nSlept: %lld ms", (long long)slept_ms); } else { - snprintf(text, sizeof(text), "Light sleep failed:\n%s", esp_err_to_name(err)); - ESP_LOGE(TAG, "light sleep 失败: %s", esp_err_to_name(err)); + snprintf(text, sizeof(text), "%s failed:\n%s", failure, esp_err_to_name(err)); + ESP_LOGE(TAG, "%s 失败: %s", failure, esp_err_to_name(err)); } set_status(text); } s_busy = false; } + s_busy = false; + if (s_stopped) xSemaphoreGive(s_stopped); + s_task = NULL; + vTaskDelete(NULL); } void demo_low_power_enter(void) @@ -135,19 +205,60 @@ void demo_low_power_enter(void) menu_refresh(); s_mascot = ui_pixel_mascot_create(s_scr, 101, 246); s_busy = false; - if (!s_task && xTaskCreate(sleep_task, "demo_sleep", 3072, NULL, 4, &s_task) != pdPASS) { - lv_label_set_text(s_status, "Cannot create\nsleep worker"); - ESP_LOGE(TAG, "创建 light-sleep 任务失败"); - } lv_screen_load(s_scr); } +esp_err_t demo_low_power_start(void) +{ + if (s_task) return ESP_OK; + if (s_stopped) { + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + } + s_stopped = xSemaphoreCreateBinary(); + if (!s_stopped) { + set_status("Cannot create\nsleep worker"); + return ESP_ERR_NO_MEM; + } + s_stop_requested = false; + if (xTaskCreate(sleep_task, "demo_sleep", 3072, NULL, 4, &s_task) != pdPASS) { + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + set_status("Cannot create\nsleep worker"); + ESP_LOGE(TAG, "创建 light-sleep 任务失败"); + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +esp_err_t demo_low_power_stop(void) +{ + TaskHandle_t task = s_task; + if (!task) { + if (s_stopped) { + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + } + return ESP_OK; + } + + s_stop_requested = true; + xTaskNotify(task, SLEEP_COMMAND_STOP, eSetValueWithOverwrite); + if (!s_stopped || + xSemaphoreTake(s_stopped, pdMS_TO_TICKS(SLEEP_STOP_TIMEOUT_MS)) != pdTRUE) { + set_status("Sleep stop timed out; retry"); + return ESP_ERR_TIMEOUT; + } + s_task = NULL; + vSemaphoreDelete(s_stopped); + s_stopped = NULL; + bsp_display_backlight(100); + esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER); + return ESP_OK; +} + void demo_low_power_exit(void) { - if (s_task) { - vTaskDelete(s_task); - s_task = NULL; - } s_busy = false; bsp_display_backlight(100); esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_TIMER); @@ -164,9 +275,11 @@ void demo_low_power_key(bsp_btn_t btn, bsp_btn_ev_t ev) { if (ev != BSP_BTN_CLICK || s_busy || !s_task) return; if (btn == BSP_BTN_UP || btn == BSP_BTN_DOWN) { + if (!bsp_lvgl_lock(250)) return; s_selected = (s_selected + 1) % 2; menu_refresh(); ui_pixel_mascot_jump(s_mascot); + bsp_lvgl_unlock(); } else if (btn == BSP_BTN_OK) { uint32_t command = s_selected == 0 ? SLEEP_COMMAND_LIGHT : SLEEP_COMMAND_DEEP; xTaskNotify(s_task, command, eSetValueWithOverwrite); diff --git a/main/demo_navigation.c b/main/demo_navigation.c new file mode 100644 index 0000000..3a6435c --- /dev/null +++ b/main/demo_navigation.c @@ -0,0 +1,40 @@ +#include "demo_navigation.h" + +void demo_navigation_init(demo_navigation_t *navigation, size_t count) { + navigation->selected = 0; + navigation->active = -1; + navigation->count = count; +} + +demo_nav_result_t demo_navigation_handle(demo_navigation_t *navigation, + demo_nav_input_t input, + bool selected_available) { + demo_nav_result_t result = { .action = DEMO_NAV_ACTION_NONE, .index = 0 }; + if (!navigation || navigation->count == 0) return result; + + if (navigation->active >= 0) { + result.index = (size_t)navigation->active; + result.action = input == DEMO_NAV_INPUT_OK_LONG + ? DEMO_NAV_ACTION_EXIT + : DEMO_NAV_ACTION_FORWARD; + return result; + } + + if (input == DEMO_NAV_INPUT_UP_CLICK) { + navigation->selected = (navigation->selected + navigation->count - 1) + % navigation->count; + result.action = DEMO_NAV_ACTION_REFRESH; + } else if (input == DEMO_NAV_INPUT_DOWN_CLICK) { + navigation->selected = (navigation->selected + 1) % navigation->count; + result.action = DEMO_NAV_ACTION_REFRESH; + } else if (input == DEMO_NAV_INPUT_OK_CLICK && selected_available) { + navigation->active = (int)navigation->selected; + result.action = DEMO_NAV_ACTION_ENTER; + } + result.index = navigation->selected; + return result; +} + +void demo_navigation_complete_exit(demo_navigation_t *navigation) { + if (navigation) navigation->active = -1; +} diff --git a/main/demo_navigation.h b/main/demo_navigation.h new file mode 100644 index 0000000..d679197 --- /dev/null +++ b/main/demo_navigation.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +typedef enum { + DEMO_NAV_INPUT_OTHER = 0, + DEMO_NAV_INPUT_UP_CLICK, + DEMO_NAV_INPUT_DOWN_CLICK, + DEMO_NAV_INPUT_OK_CLICK, + DEMO_NAV_INPUT_OK_LONG, +} demo_nav_input_t; + +typedef enum { + DEMO_NAV_ACTION_NONE = 0, + DEMO_NAV_ACTION_REFRESH, + DEMO_NAV_ACTION_ENTER, + DEMO_NAV_ACTION_EXIT, + DEMO_NAV_ACTION_FORWARD, +} demo_nav_action_t; + +typedef struct { + size_t selected; + int active; + size_t count; +} demo_navigation_t; + +typedef struct { + demo_nav_action_t action; + size_t index; +} demo_nav_result_t; + +void demo_navigation_init(demo_navigation_t *navigation, size_t count); +demo_nav_result_t demo_navigation_handle(demo_navigation_t *navigation, + demo_nav_input_t input, + bool selected_available); +void demo_navigation_complete_exit(demo_navigation_t *navigation); diff --git a/main/demo_wifi.c b/main/demo_wifi.c index 7735ef1..d0a89ce 100644 --- a/main/demo_wifi.c +++ b/main/demo_wifi.c @@ -1,6 +1,7 @@ // main/demo_wifi.c —— STA 模式扫描附近 AP,不连接网络、不保存凭证。 #include "demo.h" #include "demo_radio.h" +#include "bsp_display.h" #include "ui_pixel.h" #include "esp_event.h" @@ -59,7 +60,9 @@ static esp_err_t start_scan(void) return err; } -static esp_err_t wifi_start(void) +static void wifi_stack_stop(void); + +esp_err_t demo_wifi_start(void) { s_state = WIFI_DEMO_STARTING; esp_err_t err = demo_radio_nvs_prepare(); @@ -91,9 +94,12 @@ static esp_err_t wifi_start(void) if (err != ESP_OK) goto fail; s_wifi_started = true; - return start_scan(); + err = start_scan(); + if (err != ESP_OK) goto fail; + return ESP_OK; fail: + wifi_stack_stop(); s_error = err; s_state = WIFI_DEMO_FAILED; ESP_LOGE(TAG, "Wi-Fi 初始化失败: %s", esp_err_to_name(err)); @@ -153,7 +159,7 @@ static void tick(lv_timer_t *timer) } } -static void wifi_stop(void) +static void wifi_stack_stop(void) { if (s_wifi_started) { esp_wifi_scan_stop(); @@ -176,6 +182,12 @@ static void wifi_stop(void) s_state = WIFI_DEMO_OFF; } +esp_err_t demo_wifi_stop(void) +{ + wifi_stack_stop(); + return ESP_OK; +} + void demo_wifi_enter(void) { s_scr = ui_pixel_screen_create("WI-FI SCAN"); @@ -197,7 +209,7 @@ void demo_wifi_enter(void) ui_pixel_mascot_create(s_scr, 101, 246); s_timer = lv_timer_create(tick, 100, NULL); lv_screen_load(s_scr); - wifi_start(); + s_state = WIFI_DEMO_STARTING; } void demo_wifi_exit(void) @@ -206,7 +218,6 @@ void demo_wifi_exit(void) lv_timer_delete(s_timer); s_timer = NULL; } - wifi_stop(); if (s_scr) { lv_obj_delete(s_scr); s_scr = NULL; @@ -217,6 +228,8 @@ void demo_wifi_exit(void) void demo_wifi_key(bsp_btn_t btn, bsp_btn_ev_t ev) { if (btn != BSP_BTN_OK || ev != BSP_BTN_CLICK || s_state != WIFI_DEMO_OFF) return; + if (!bsp_lvgl_lock(250)) return; lv_label_set_text(s_results, "RSSI SSID CHANNEL"); - start_scan(); + bsp_lvgl_unlock(); + (void)start_scan(); } diff --git a/main/main.c b/main/main.c index 4624bde..e05aad2 100644 --- a/main/main.c +++ b/main/main.c @@ -11,23 +11,40 @@ #include "bsp_battery.h" #include "bsp_pins.h" // 错误日志里要打印 BSP_LCD_* 引脚号 #include "demo.h" +#include "demo_navigation.h" #include "ui_pixel.h" #include "lvgl.h" #include "esp_log.h" #include "esp_sleep.h" +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "freertos/task.h" static const char *TAG = "main"; static const demo_entry_t DEMOS[] = { - { "Display", demo_display_enter, demo_display_exit, demo_display_key }, - { "Button", demo_button_enter, demo_button_exit, demo_button_key }, - { "Audio", demo_audio_enter, demo_audio_exit, demo_audio_key }, - { "Battery", demo_battery_enter, demo_battery_exit, demo_battery_key }, - { "Wi-Fi", demo_wifi_enter, demo_wifi_exit, demo_wifi_key }, - { "BLE", demo_ble_enter, demo_ble_exit, demo_ble_key }, - { "Low Power", demo_low_power_enter, demo_low_power_exit, demo_low_power_key }, + { .name = "Display", .enter = demo_display_enter, .exit = demo_display_exit, + .key = demo_display_key }, + { .name = "Button", .enter = demo_button_enter, .exit = demo_button_exit, + .key = demo_button_key }, + { .name = "Audio", .enter = demo_audio_enter, .exit = demo_audio_exit, + .key = demo_audio_key, .start = demo_audio_start, .stop = demo_audio_stop }, + { .name = "Battery", .enter = demo_battery_enter, .exit = demo_battery_exit, + .key = demo_battery_key }, + { .name = "Wi-Fi", .enter = demo_wifi_enter, .exit = demo_wifi_exit, + .key = demo_wifi_key, .start = demo_wifi_start, .stop = demo_wifi_stop }, + { .name = "BLE", .enter = demo_ble_enter, .exit = demo_ble_exit, + .key = demo_ble_key, .start = demo_ble_start, .stop = demo_ble_stop }, + { .name = "Low Power", .enter = demo_low_power_enter, .exit = demo_low_power_exit, + .key = demo_low_power_key, .start = demo_low_power_start, .stop = demo_low_power_stop }, }; #define DEMO_COUNT (sizeof(DEMOS) / sizeof(DEMOS[0])) +#define INPUT_QUEUE_DEPTH 8 + +typedef struct { + bsp_btn_t btn; + bsp_btn_ev_t event; +} input_event_t; // 各外设初始化结果:失败的项在菜单里标 [FAIL] 且不允许进入。 static bool s_ok[DEMO_COUNT]; @@ -36,15 +53,17 @@ static lv_obj_t *s_menu_scr; static lv_obj_t *s_cards[DEMO_COUNT]; static lv_obj_t *s_rows[DEMO_COUNT]; static lv_obj_t *s_mascot; -static int s_sel; // 当前选中项 -static int s_active = -1; // 当前所在演示页;-1 = 在菜单 +static demo_navigation_t s_navigation; +static QueueHandle_t s_input_queue; +static TaskHandle_t s_input_task; +static volatile bool s_input_ready; static void menu_refresh(void) { for (size_t i = 0; i < DEMO_COUNT; i++) { lv_label_set_text_fmt(s_rows[i], "%s%s", DEMOS[i].name, s_ok[i] ? "" : " [FAIL]"); - ui_pixel_set_selected(s_cards[i], (int)i == s_sel, s_ok[i]); + ui_pixel_set_selected(s_cards[i], i == s_navigation.selected, s_ok[i]); lv_obj_set_style_text_color(s_rows[i], s_ok[i] ? lv_color_hex(UI_INK) : lv_color_hex(0x7A2020), 0); } @@ -70,39 +89,107 @@ static void menu_build(void) { } static void enter_menu(void) { - s_active = -1; menu_build(); } -// 按键回调运行在 button 组件的任务里,操作 LVGL 必须加锁。 -static void on_key(bsp_btn_t btn, bsp_btn_ev_t ev, void *user) { - (void)user; - if (!bsp_lvgl_lock(500)) return; +static demo_nav_input_t navigation_input(bsp_btn_t btn, bsp_btn_ev_t event) { + if (event == BSP_BTN_LONG && btn == BSP_BTN_OK) return DEMO_NAV_INPUT_OK_LONG; + if (event != BSP_BTN_CLICK) return DEMO_NAV_INPUT_OTHER; + if (btn == BSP_BTN_UP) return DEMO_NAV_INPUT_UP_CLICK; + if (btn == BSP_BTN_DOWN) return DEMO_NAV_INPUT_DOWN_CLICK; + if (btn == BSP_BTN_OK) return DEMO_NAV_INPUT_OK_CLICK; + return DEMO_NAV_INPUT_OTHER; +} - if (s_active >= 0) { - if (btn == BSP_BTN_OK && ev == BSP_BTN_LONG) { // 统一返回 - DEMOS[s_active].exit(); +static void process_input(const input_event_t *input) { + demo_nav_input_t nav_input = navigation_input(input->btn, input->event); + + if (s_navigation.active >= 0) { + demo_nav_result_t result = demo_navigation_handle(&s_navigation, nav_input, true); + const demo_entry_t *demo = &DEMOS[result.index]; + if (result.action == DEMO_NAV_ACTION_EXIT) { + esp_err_t e = demo->stop ? demo->stop() : ESP_OK; + if (e != ESP_OK) { + ESP_LOGE(TAG, "%s 页面停止失败: %s", demo->name, esp_err_to_name(e)); + return; + } + if (!bsp_lvgl_lock(500)) return; + demo->exit(); + demo_navigation_complete_exit(&s_navigation); enter_menu(); - } else { - DEMOS[s_active].key(btn, ev); + bsp_lvgl_unlock(); + } else if (result.action == DEMO_NAV_ACTION_FORWARD) { + demo->key(input->btn, input->event); } - } else if (ev == BSP_BTN_CLICK) { - if (btn == BSP_BTN_UP) { s_sel = (s_sel + DEMO_COUNT - 1) % DEMO_COUNT; menu_refresh(); } - if (btn == BSP_BTN_DOWN) { s_sel = (s_sel + 1) % DEMO_COUNT; menu_refresh(); } - if (btn == BSP_BTN_OK && s_ok[s_sel]) { - s_active = s_sel; - ui_pixel_mascot_jump(s_mascot); - lv_obj_delete(s_menu_scr); - s_menu_scr = NULL; - s_mascot = NULL; - DEMOS[s_active].enter(); - } else if (btn == BSP_BTN_UP || btn == BSP_BTN_DOWN) { - ui_pixel_mascot_jump(s_mascot); + return; + } + + if (nav_input == DEMO_NAV_INPUT_OTHER || nav_input == DEMO_NAV_INPUT_OK_LONG) return; + if (!bsp_lvgl_lock(500)) return; + demo_nav_result_t result = demo_navigation_handle( + &s_navigation, nav_input, s_ok[s_navigation.selected]); + if (result.action == DEMO_NAV_ACTION_REFRESH) { + menu_refresh(); + ui_pixel_mascot_jump(s_mascot); + } else if (result.action == DEMO_NAV_ACTION_ENTER) { + const demo_entry_t *demo = &DEMOS[result.index]; + ui_pixel_mascot_jump(s_mascot); + lv_obj_delete(s_menu_scr); + s_menu_scr = NULL; + s_mascot = NULL; + demo->enter(); + bsp_lvgl_unlock(); + + esp_err_t e = demo->start ? demo->start() : ESP_OK; + if (e != ESP_OK) { + ESP_LOGE(TAG, "%s 页面启动失败: %s", demo->name, esp_err_to_name(e)); } + return; } bsp_lvgl_unlock(); } +static void input_task(void *arg) { + (void)arg; + input_event_t input; + for (;;) { + if (xQueueReceive(s_input_queue, &input, portMAX_DELAY) == pdTRUE) { + process_input(&input); + } + } +} + +static esp_err_t input_dispatch_init(void) { + s_input_queue = xQueueCreate(INPUT_QUEUE_DEPTH, sizeof(input_event_t)); + if (!s_input_queue) return ESP_ERR_NO_MEM; + if (xTaskCreate(input_task, "demo_input", 4096, NULL, 5, &s_input_task) != pdPASS) { + vQueueDelete(s_input_queue); + s_input_queue = NULL; + return ESP_ERR_NO_MEM; + } + return ESP_OK; +} + +static void input_dispatch_deinit(void) { + s_input_ready = false; + if (s_input_task) { + vTaskDelete(s_input_task); + s_input_task = NULL; + } + if (s_input_queue) { + vQueueDelete(s_input_queue); + s_input_queue = NULL; + } +} + +// button callbacks run on the shared esp_timer task; enqueue only and return immediately. +static void on_key(bsp_btn_t btn, bsp_btn_ev_t ev, void *user) { + (void)user; + if (!s_input_ready || !s_input_queue) return; + const input_event_t input = { .btn = btn, .event = ev }; + (void)xQueueSend(s_input_queue, &input, 0); +} + void app_main(void) { ESP_LOGI(TAG, "FoloToy AI Passport BSP demo 启动"); esp_sleep_wakeup_cause_t wakeup = esp_sleep_get_wakeup_cause(); @@ -123,16 +210,32 @@ void app_main(void) { } bsp_display_backlight(100); + demo_navigation_init(&s_navigation, DEMO_COUNT); + // 其余外设单项失败不阻塞:菜单里标 [FAIL],其他项照常可测。 s_ok[0] = true; // Display 已确认可用 - s_ok[1] = (bsp_button_init(on_key, NULL) == ESP_OK); + esp_err_t input_err = input_dispatch_init(); + esp_err_t button_err = input_err == ESP_OK + ? bsp_button_init(on_key, NULL) + : ESP_ERR_INVALID_STATE; + s_ok[1] = input_err == ESP_OK && button_err == ESP_OK; + if (input_err != ESP_OK) { + ESP_LOGE(TAG, "按键事件任务创建失败: %s", esp_err_to_name(input_err)); + } else if (button_err != ESP_OK) { + ESP_LOGE(TAG, "按键初始化失败: %s", esp_err_to_name(button_err)); + input_dispatch_deinit(); + } s_ok[2] = (bsp_audio_init() == ESP_OK); s_ok[3] = (bsp_battery_init() == ESP_OK); s_ok[4] = true; // 页面内按需初始化并显示错误 s_ok[5] = true; s_ok[6] = true; - if (bsp_lvgl_lock(1000)) { enter_menu(); bsp_lvgl_unlock(); } + if (bsp_lvgl_lock(1000)) { + enter_menu(); + bsp_lvgl_unlock(); + s_input_ready = true; + } ESP_LOGI(TAG, "就绪:Display=%d Button=%d Audio=%d Battery=%d", s_ok[0], s_ok[1], s_ok[2], s_ok[3]); diff --git a/partitions.csv b/partitions.csv index da606af..40335b2 100644 --- a/partitions.csv +++ b/partitions.csv @@ -1,5 +1,4 @@ # Name, Type, SubType, Offset, Size, Flags nvs, data, nvs, 0x9000, 0x6000, phy_init, data, phy, 0xf000, 0x1000, -factory, app, factory, 0x10000, 0x300000, -cardid, data, nvs, 0x356000, 0x4000, +factory, app, factory, 0x10000, 0x7f0000, diff --git a/sdkconfig.defaults b/sdkconfig.defaults index e3d392b..3e2fcf6 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -7,8 +7,7 @@ CONFIG_IDF_TARGET="esp32c3" CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y # 固定 8MB 镜像头,关闭 detect,便于 idf.py merge-bin。 CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE=n -# 3 MB 应用上限与固定保护分区保持一致。分区表保留 -# cardid@0x356000,二创不得移动或覆盖。 +# 默认模板只保留 NVS、PHY data 和占用剩余空间的 factory app;用户可按需修改。 CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" diff --git a/skills/experience-pr/SKILL.md b/skills/experience-pr/SKILL.md index 7adc343..04ec9a8 100644 --- a/skills/experience-pr/SKILL.md +++ b/skills/experience-pr/SKILL.md @@ -147,8 +147,9 @@ developer's current branch. Report the result as `Build`, `Host tests`, `Device tests`, and `Unverified` separately. A docs-only change has no firmware or host-test work, so report -those as NOT RUN and note the reason. Update `docs/CHANGELOG.md` only if the -change affects user-visible behavior, compatibility, or the release workflow. +those as NOT RUN and note the reason. An experience pull request leaves the +paired changelog files unchanged; describe any user-visible or release-flow +impact in the pull-request body for the release maintainer to aggregate later. ## What this skill does not do diff --git a/skills/experience-pr/SKILL.zh_CN.md b/skills/experience-pr/SKILL.zh_CN.md index dfc89cc..088bd06 100644 --- a/skills/experience-pr/SKILL.zh_CN.md +++ b/skills/experience-pr/SKILL.zh_CN.md @@ -109,8 +109,8 @@ comm -23 \ ## 交付上报 按 `Build`、`Host tests`、`Device tests`、`Unverified` 分别上报。纯文档变更没有固件或 -host-test 工作,因此这些上报为 NOT RUN 并说明原因。仅当变更影响用户可见行为、兼容性或 -发布流程时更新 `docs/CHANGELOG.md`。 +host-test 工作,因此这些上报为 NOT RUN 并说明原因。经验 PR 不修改中英文变更日志;用户可见或 +发布流程影响写入 PR 正文,后续由发布负责人统一汇总。 ## 本 skill 不做的事 diff --git a/tests/test_bsp_display_rounding.c b/tests/test_bsp_display_rounding.c new file mode 100644 index 0000000..9991ad7 --- /dev/null +++ b/tests/test_bsp_display_rounding.c @@ -0,0 +1,26 @@ +#include + +#include "bsp_display_rounding.h" + +int main(void) +{ + const int width = 240; + const int height = 320; + const int radius = 30; + + assert(bsp_display_pixel_outside_rounded_rect(0, 0, width, height, radius)); + assert(bsp_display_pixel_outside_rounded_rect(29, 0, width, height, radius)); + assert(!bsp_display_pixel_outside_rounded_rect(30, 0, width, height, radius)); + assert(!bsp_display_pixel_outside_rounded_rect(9, 9, width, height, radius)); + assert(bsp_display_pixel_outside_rounded_rect(8, 8, width, height, radius)); + + assert(bsp_display_pixel_outside_rounded_rect(239, 0, width, height, radius)); + assert(!bsp_display_pixel_outside_rounded_rect(209, 0, width, height, radius)); + assert(bsp_display_pixel_outside_rounded_rect(0, 319, width, height, radius)); + assert(!bsp_display_pixel_outside_rounded_rect(30, 319, width, height, radius)); + assert(!bsp_display_pixel_outside_rounded_rect(120, 160, width, height, radius)); + + assert(!bsp_display_pixel_outside_rounded_rect(0, 0, width, height, 0)); + assert(bsp_display_pixel_outside_rounded_rect(-1, 0, width, height, radius)); + return 0; +} diff --git a/tests/test_bsp_es8311_sleep_check.c b/tests/test_bsp_es8311_sleep_check.c new file mode 100644 index 0000000..272188c --- /dev/null +++ b/tests/test_bsp_es8311_sleep_check.c @@ -0,0 +1,30 @@ +#include "bsp_es8311_sleep_check.h" + +#include + +int main(void) +{ + const uint8_t registers[] = {0x00, 0x01, 0x0D, 0x0E, 0x12, 0x45}; + const uint8_t values[] = {0x1F, 0x00, 0xFC, 0x7F, 0x02, 0x01}; + assert(bsp_es8311_sleep_check_count == sizeof(registers)); + + for (size_t i = 0; i < bsp_es8311_sleep_check_count; i++) { + const bsp_es8311_reg_check_t *check = &bsp_es8311_sleep_checks[i]; + assert(check->reg == registers[i]); + + // Exercise the production table/predicate over every possible readback. + // Only REG0E may accept two values; all other registers stay exact. + for (unsigned actual = 0; actual <= UINT8_MAX; actual++) { + bool expected = actual == values[i] || + (registers[i] == 0x0E && actual == 0xFF); + assert(bsp_es8311_sleep_check_matches(check, (uint8_t)actual) == expected); + } + } + + // A set bit outside the mask in an expected value is ignored as well. + const bsp_es8311_reg_check_t unmasked_expected = {0x0E, 0xFF, 0x7F}; + assert(bsp_es8311_sleep_check_matches(&unmasked_expected, 0x7F)); + assert(bsp_es8311_sleep_check_matches(&unmasked_expected, 0xFF)); + assert(!bsp_es8311_sleep_check_matches(&unmasked_expected, 0x7E)); + return 0; +} diff --git a/tests/test_check_repo.py b/tests/test_check_repo.py new file mode 100644 index 0000000..fb70691 --- /dev/null +++ b/tests/test_check_repo.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Host tests for bounded third-party documentation exemptions.""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("check_repo", ROOT / "tools" / "check_repo.py") +assert SPEC and SPEC.loader +CHECKS = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(CHECKS) + +UPSTREAM_DOC = "# Upstream\n\n[Guide](upstream-only.md)\n" + + +class VendoredDocumentationTest(unittest.TestCase): + def setUp(self) -> None: + temporary = tempfile.TemporaryDirectory(prefix="ai-passport-doc-tests-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + root_patch = patch.object(CHECKS, "ROOT", self.root) + root_patch.start() + self.addCleanup(root_patch.stop) + self.vendor = self.root / "components" / "vendor_audio" + self.vendor.mkdir(parents=True) + config_patch = patch.object(CHECKS, "VENDORED_DOC_ROOTS", ("components/vendor_audio",)) + config_patch.start() + self.addCleanup(config_patch.stop) + + def document(self, name: str, content: str = UPSTREAM_DOC) -> Path: + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + return path + + def roots(self) -> tuple[Path, ...]: + errors: list[str] = [] + roots = CHECKS.vendored_document_roots(errors) + self.assertEqual(errors, []) + return roots + + def symlink(self, link: Path, target: Path, *, directory: bool = False) -> None: + try: + link.symlink_to(target, target_is_directory=directory) + except NotImplementedError: + self.skipTest("This platform does not support symlinks") + except OSError as error: + if getattr(error, "winerror", None) != 1314: + raise + self.skipTest("Windows symlink tests require Developer Mode or elevation") + + def document_errors(self, files: list[Path]) -> list[str]: + errors: list[str] = [] + roots = self.roots() + CHECKS.check_markdown_links(files, errors, roots) + CHECKS.check_document_languages(files, errors, roots) + return errors + + def test_empty_registry_keeps_upstream_documents_checked(self) -> None: + path = self.document("components/vendor_audio/README.md") + with patch.object(CHECKS, "VENDORED_DOC_ROOTS", ()): + errors = self.document_errors([path]) + self.assertEqual(len(errors), 2) + self.assertTrue(any("missing link target" in error for error in errors)) + self.assertTrue(any("missing Simplified Chinese peer" in error for error in errors)) + + def test_explicit_root_exempts_nested_links_and_language_rules(self) -> None: + files = [ + self.document("components/vendor_audio/README.md"), + self.document("components/vendor_audio/docs/manual.md", "# 上游文档\n"), + self.document("components/vendor_audio/docs/other.zh_CN.md", "# 上游中文\n"), + ] + self.assertEqual(self.document_errors(files), []) + + def test_first_party_and_similar_prefixes_remain_checked(self) -> None: + for name in ( + "docs/README.md", + "components/vendor_audio_extra/README.md", + "components/vendor_audio.md", + "components/other/vendor_audio/README.md", + "components/vendor_audio2/README.md", + ): + with self.subTest(name=name): + errors = self.document_errors([self.document(name)]) + self.assertEqual(len(errors), 2) + self.assertTrue(all(name in error for error in errors)) + + def test_valid_first_party_pair_and_links_still_pass(self) -> None: + files = [ + self.document("docs/guide.md", "[简体中文](guide.zh_CN.md)\n# Guide\n"), + self.document("docs/guide.zh_CN.md", "[English](guide.md)\n# 指南\n"), + ] + self.assertEqual(self.document_errors(files), []) + + def test_invalid_root_registrations_fail_closed(self) -> None: + file_path = self.document("components/vendor_audio/README.md") + for name in ( + "", ".", "..", "/", str(self.vendor), "../outside", + "components/..", "components/./vendor_audio", "components//vendor_audio", + "components/vendor_audio/", "components\\vendor_audio", "C:/vendor_audio", + "components/missing", str(file_path.relative_to(self.root)), 1, + ): + with self.subTest(name=name), patch.object(CHECKS, "VENDORED_DOC_ROOTS", (name,)): + errors: list[str] = [] + self.assertEqual(CHECKS.vendored_document_roots(errors), ()) + self.assertEqual(len(errors), 1) + self.assertIn("invalid VENDORED_DOC_ROOTS entry", errors[0]) + + def test_registered_root_cannot_be_a_symlink_or_use_symlink_parent(self) -> None: + self.symlink(self.root / "alias", self.root / "components", directory=True) + self.symlink(self.root / "outside", self.root.parent, directory=True) + for name in ("alias/vendor_audio", "outside"): + with self.subTest(name=name), patch.object(CHECKS, "VENDORED_DOC_ROOTS", (name,)): + errors: list[str] = [] + self.assertEqual(CHECKS.vendored_document_roots(errors), ()) + self.assertTrue(errors) + + def test_vendored_symlinks_into_first_party_remain_checked(self) -> None: + target = self.document("docs/guide.md") + linked_file = self.vendor / "guide.md" + self.symlink(linked_file, target) + linked_directory = self.vendor / "project_docs" + self.symlink(linked_directory, target.parent, directory=True) + for path in (linked_file, linked_directory / "guide.md"): + with self.subTest(path=path): + self.assertFalse(CHECKS.is_vendored_document(path, self.roots())) + self.assertEqual(len(self.document_errors([path])), 2) + + def test_symlink_outside_repository_is_not_exempt_and_does_not_crash(self) -> None: + with tempfile.TemporaryDirectory(prefix="ai-passport-doc-external-") as external: + target = Path(external) / "guide.md" + target.write_text(UPSTREAM_DOC, encoding="utf-8") + link = self.vendor / "guide.md" + self.symlink(link, target) + self.assertEqual(len(self.document_errors([link])), 2) + + def test_first_party_symlink_into_vendored_directory_remains_checked(self) -> None: + target = self.document("components/vendor_audio/README.md") + link = self.root / "README.md" + self.symlink(link, target) + self.assertEqual(len(self.document_errors([link])), 2) + + def test_main_keeps_security_and_conflict_checks_for_vendored_text(self) -> None: + # Assemble deliberately synthetic fixtures so the test source itself is clean. + samples = { + "token.md": "ghp_" + "x" * 24, + "access.md": "AKIA" + "0" * 16, + "key.md": "-----BEGIN " + "PRIVATE KEY-----", + "device.md": "https://ai-passport.folotoy.cn/" + "trae/?s=" + "synthetic&k=synthetic", + "conflict.md": "<" * 7 + " HEAD\n", + } + files = [ + self.document("components/vendor_audio/" + name, UPSTREAM_DOC + sample) + for name, sample in samples.items() + ] + with ( + patch.object(CHECKS, "git_files", return_value=files), + patch.object(CHECKS, "check_required_files"), + patch.object(CHECKS, "check_action_pins"), + patch.object(CHECKS, "check_issue_forms"), + contextlib.redirect_stderr(io.StringIO()) as output, + ): + self.assertEqual(CHECKS.text_files(), files) + self.assertEqual(CHECKS.main(), 1) + errors = output.getvalue().splitlines() + self.assertEqual(len(errors), 5) + for expected in ( + "possible GitHub token", "possible AWS access key", "possible private key", + "possible unsanitized device QR link", "unresolved merge conflict marker", + ): + self.assertTrue(any(expected in error for error in errors), errors) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_deep_sleep_contract.py b/tests/test_deep_sleep_contract.py new file mode 100644 index 0000000..0dcd3aa --- /dev/null +++ b/tests/test_deep_sleep_contract.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Static contracts for the terminal deep-sleep shutdown path.""" + +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[1] + + +def read(relative_path: str) -> str: + return (ROOT / relative_path).read_text(encoding="utf-8") + + +def initializer(source: str, symbol: str) -> str: + match = re.search(rf"\b{re.escape(symbol)}\s*\[\]\s*=\s*\{{", source) + if not match: + raise AssertionError(f"initializer not found: {symbol}") + end = source.find("};", match.end()) + if end < 0: + raise AssertionError(f"initializer is unterminated: {symbol}") + return source[match.end():end] + + +def function_body(source: str, name: str) -> str: + match = re.search(rf"\b{re.escape(name)}\s*\([^;]*?\)\s*\{{", source) + if not match: + raise AssertionError(f"function not found: {name}") + start = match.end() - 1 + depth = 0 + for index in range(start, len(source)): + if source[index] == "{": + depth += 1 + elif source[index] == "}": + depth -= 1 + if depth == 0: + return source[start + 1:index] + raise AssertionError(f"function is unterminated: {name}") + + +def register_pairs(block: str) -> list[tuple[int, int]]: + return [ + (int(reg, 16), int(value, 16)) + for reg, value in re.findall(r"\{\s*0x([0-9A-Fa-f]{2})\s*,\s*0x([0-9A-Fa-f]{2})\s*\}", block) + ] + + +class DeepSleepContractTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.audio = read("components/bsp/src/bsp_audio.c") + cls.battery = read("components/bsp/src/bsp_battery.c") + cls.display = read("components/bsp/src/bsp_display.c") + cls.i2c = read("components/bsp/src/bsp_i2c.c") + cls.demo = read("main/demo_low_power.c") + + def test_es8311_force_sleep_sequence_is_complete_and_ordered(self) -> None: + expected = [ + (0x32, 0x00), (0x17, 0x00), (0x0E, 0xFF), (0x12, 0x02), + (0x14, 0x00), (0x0D, 0xFA), (0x15, 0x00), (0x02, 0x10), + (0x00, 0x00), (0x00, 0x1F), (0x01, 0x30), (0x01, 0x00), + (0x45, 0x01), (0x0D, 0xFC), (0x02, 0x00), + ] + actual = register_pairs(initializer(self.audio, "s_es8311_sleep_sequence")) + self.assertEqual(actual, expected) + + def test_es8311_critical_registers_are_read_back(self) -> None: + # The C host test exhausts all readback values against the actual policy. + # This integration contract makes sure the driver uses it, and that an + # I2C read failure cannot pass even when the output byte matches. + body = function_body(self.audio, "es8311_force_sleep_once") + self.assertIn("s_ctrl->write_reg", body) + self.assertIn("s_ctrl->read_reg", body) + self.assertIn("i < bsp_es8311_sleep_check_count", body) + self.assertIn("&bsp_es8311_sleep_checks[i]", body) + self.assertRegex( + body, + r"read_result == ESP_CODEC_DEV_OK\s*&&\s*" + r"bsp_es8311_sleep_check_matches\(item, actual\)", + ) + + def test_es8311_force_sleep_retries_once_after_five_ms(self) -> None: + self.assertRegex(self.audio, r"#define\s+ES8311_SLEEP_ATTEMPTS\s+2\b") + self.assertRegex(self.audio, r"#define\s+ES8311_SLEEP_RETRY_MS\s+5\b") + body = function_body(self.audio, "es8311_force_sleep") + self.assertIn("attempt <= ES8311_SLEEP_ATTEMPTS", body) + self.assertIn("pdMS_TO_TICKS(ES8311_SLEEP_RETRY_MS)", body) + + def test_audio_suspend_does_not_require_a_silent_open(self) -> None: + body = function_body(self.audio, "bsp_audio_sleep") + self.assertIn("es8311_force_sleep()", body) + self.assertIn("audio_disable_i2s_channels()", body) + self.assertNotIn("bsp_audio_set_format", body) + + def test_i2s_pins_are_released_only_by_deep_sleep_api(self) -> None: + body = function_body(self.audio, "bsp_audio_prepare_deep_sleep") + for pin in ("BSP_I2S_MCLK", "BSP_I2S_BCLK", "BSP_I2S_WS", + "BSP_I2S_DOUT", "BSP_I2S_DIN"): + self.assertIn(pin, body) + self.assertIn("GPIO_MODE_INPUT", body) + self.assertIn("GPIO_PULLUP_DISABLE", body) + self.assertIn("GPIO_PULLDOWN_DISABLE", body) + + def test_cw2017_sleep_is_verified_and_retried(self) -> None: + body = function_body(self.battery, "bsp_battery_sleep") + self.assertIn("attempt <= 2", body) + self.assertIn("cw_write(CW_REG_CONFIG, CW_CONFIG_SLEEP)", body) + self.assertIn("pdMS_TO_TICKS(5)", body) + self.assertIn("cw_read(CW_REG_CONFIG, &actual, 1)", body) + self.assertIn("actual == CW_CONFIG_SLEEP", body) + + def test_shared_i2c_is_released_after_device_transactions(self) -> None: + body = function_body(self.i2c, "bsp_i2c_prepare_deep_sleep") + self.assertIn("BSP_I2C_SDA", body) + self.assertIn("BSP_I2C_SCL", body) + self.assertIn("GPIO_MODE_INPUT", body) + self.assertIn("GPIO_PULLUP_DISABLE", body) + self.assertIn("GPIO_PULLDOWN_DISABLE", body) + + def test_lcd_safe_levels_and_holds_are_configured(self) -> None: + pins = initializer(self.display, "s_deep_sleep_pins") + levels = initializer(self.display, "s_deep_sleep_levels") + self.assertRegex(pins, r"BSP_LCD_CS.*BSP_LCD_SCLK.*BSP_LCD_MOSI.*BSP_LCD_DC.*BSP_LCD_BL") + self.assertRegex(levels, r"1\s*,\s*0\s*,\s*0\s*,\s*0\s*,\s*0") + body = function_body(self.display, "bsp_display_prepare_deep_sleep") + self.assertIn("esp_lcd_panel_disp_on_off(s_panel, false)", body) + self.assertIn("esp_lcd_panel_disp_sleep(s_panel, true)", body) + self.assertIn("ledc_stop", body) + self.assertIn("gpio_hold_en", body) + self.assertIn("gpio_deep_sleep_hold_en", body) + + def test_lcd_holds_are_released_before_spi_initialization(self) -> None: + release = function_body(self.display, "display_release_deep_sleep_holds") + self.assertIn("gpio_deep_sleep_hold_dis", release) + self.assertIn("gpio_hold_dis", release) + init = function_body(self.display, "bsp_display_init") + self.assertLess(init.index("display_release_deep_sleep_holds()"), + init.index("spi_bus_initialize")) + + def test_terminal_shutdown_order_precedes_deep_sleep(self) -> None: + body = function_body(self.demo, "sleep_task") + calls = [ + "bsp_battery_sleep()", + "bsp_audio_sleep()", + "bsp_audio_prepare_deep_sleep()", + "bsp_i2c_prepare_deep_sleep()", + "bsp_display_prepare_deep_sleep()", + "esp_deep_sleep_start()", + ] + positions = [body.index(call) for call in calls] + self.assertEqual(positions, sorted(positions)) + self.assertLess(body.index("bsp_lvgl_lock(1000)"), + body.index("bsp_display_prepare_deep_sleep()")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_demo_navigation.c b/tests/test_demo_navigation.c new file mode 100644 index 0000000..243944f --- /dev/null +++ b/tests/test_demo_navigation.c @@ -0,0 +1,38 @@ +#include + +#include "demo_navigation.h" + +int main(void) { + demo_navigation_t navigation; + demo_navigation_init(&navigation, 3); + + demo_nav_result_t result = demo_navigation_handle( + &navigation, DEMO_NAV_INPUT_UP_CLICK, true); + assert(result.action == DEMO_NAV_ACTION_REFRESH); + assert(navigation.selected == 2); + + result = demo_navigation_handle(&navigation, DEMO_NAV_INPUT_OK_CLICK, false); + assert(result.action == DEMO_NAV_ACTION_NONE); + assert(navigation.active == -1); + + result = demo_navigation_handle(&navigation, DEMO_NAV_INPUT_DOWN_CLICK, true); + assert(result.action == DEMO_NAV_ACTION_REFRESH); + assert(navigation.selected == 0); + + result = demo_navigation_handle(&navigation, DEMO_NAV_INPUT_OK_CLICK, true); + assert(result.action == DEMO_NAV_ACTION_ENTER); + assert(result.index == 0); + assert(navigation.active == 0); + + result = demo_navigation_handle(&navigation, DEMO_NAV_INPUT_OTHER, true); + assert(result.action == DEMO_NAV_ACTION_FORWARD); + assert(result.index == 0); + + result = demo_navigation_handle(&navigation, DEMO_NAV_INPUT_OK_LONG, true); + assert(result.action == DEMO_NAV_ACTION_EXIT); + assert(navigation.active == 0); + + demo_navigation_complete_exit(&navigation); + assert(navigation.active == -1); + return 0; +} diff --git a/tests/test_verify_firmware.py b/tests/test_verify_firmware.py index ceee714..0679f59 100644 --- a/tests/test_verify_firmware.py +++ b/tests/test_verify_firmware.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Host tests for the protected firmware-layout parser.""" +"""Host tests for the configurable firmware-layout parser and verifier.""" from __future__ import annotations @@ -22,13 +22,18 @@ sys.modules[SPEC.name] = VERIFY SPEC.loader.exec_module(VERIFY) -def sample_table() -> bytes: - entries = ( - (1, 2, 0x9000, 0x6000, "nvs"), - (1, 1, 0xF000, 0x1000, "phy_init"), - (0, 0, 0x10000, 0x300000, "factory"), - (1, 2, 0x356000, 0x4000, "cardid"), - ) +DEFAULT_TABLE_OFFSET = 0x8000 +DEFAULT_APP_OFFSET = 0x10000 +DEFAULT_APP_SIZE = VERIFY.FLASH_SIZE - DEFAULT_APP_OFFSET + + +def sample_table(entries: tuple[tuple[int, int, int, int, str], ...] | None = None) -> bytes: + if entries is None: + entries = ( + (1, 2, 0x9000, 0x6000, "nvs"), + (1, 1, 0xF000, 0x1000, "phy_init"), + (0, 0, DEFAULT_APP_OFFSET, DEFAULT_APP_SIZE, "factory"), + ) raw = bytearray(b"\xff" * VERIFY.PARTITION_TABLE_SIZE) for index, (kind, subtype, offset, size, label) in enumerate(entries): VERIFY.ENTRY.pack_into( @@ -48,12 +53,25 @@ def sample_table() -> bytes: return bytes(raw) +def merged_with_table( + table: bytes | None = None, + table_offset: int = DEFAULT_TABLE_OFFSET, + app_offset: int = DEFAULT_APP_OFFSET, +) -> bytearray: + merged = bytearray(b"\xff" * (max(table_offset + VERIFY.PARTITION_TABLE_SIZE, app_offset) + 1)) + merged[ + table_offset : table_offset + VERIFY.PARTITION_TABLE_SIZE + ] = table or sample_table() + merged[app_offset] = 0xE9 + return merged + + class PartitionParserTest(unittest.TestCase): - def test_parses_protected_layout_and_md5(self) -> None: + def test_parses_minimal_layout_and_md5(self) -> None: partitions, found_md5 = VERIFY.parse_partition_table(sample_table()) self.assertTrue(found_md5) - self.assertEqual(partitions[-1].label, "cardid") - self.assertEqual(partitions[-1].offset, VERIFY.CARDID_OFFSET) + self.assertEqual([item.label for item in partitions], ["nvs", "phy_init", "factory"]) + self.assertEqual(partitions[-1].size, DEFAULT_APP_SIZE) def test_rejects_bad_md5(self) -> None: raw = bytearray(sample_table()) @@ -62,19 +80,88 @@ class PartitionParserTest(unittest.TestCase): VERIFY.parse_partition_table(bytes(raw)) -class ProtectedLayoutTest(unittest.TestCase): - def test_layout_verification_accepts_current_partition_table(self) -> None: - merged = bytearray(b"\xff" * (0x10000 + 1)) - merged[ - VERIFY.PARTITION_TABLE_OFFSET : - VERIFY.PARTITION_TABLE_OFFSET + VERIFY.PARTITION_TABLE_SIZE - ] = sample_table() - merged[0x10000] = 0xE9 - +class FirmwareLayoutTest(unittest.TestCase): + def verify( + self, + merged: bytes, + app_size: int = 1, + table_offset: int = DEFAULT_TABLE_OFFSET, + app_offset: int = DEFAULT_APP_OFFSET, + ) -> None: with tempfile.TemporaryDirectory() as directory: build_dir = Path(directory) - (build_dir / "FoloToy-AI-Passport.bin").write_bytes(b"\xe9") - VERIFY.verify_protected_layout(bytes(merged), build_dir) + with (build_dir / "FoloToy-AI-Passport.bin").open("wb") as app_file: + app_file.write(b"\xe9") + app_file.truncate(app_size) + VERIFY.verify_firmware_layout(merged, build_dir, table_offset, app_offset) + + def test_layout_verification_accepts_current_partition_table(self) -> None: + self.verify(bytes(merged_with_table())) + + def test_accepts_custom_data_partition(self) -> None: + entries = ( + (1, 2, 0x9000, 0x6000, "nvs"), + (1, 1, 0xF000, 0x1000, "phy_init"), + (0, 0, DEFAULT_APP_OFFSET, 0x300000, "factory"), + (1, 2, 0x310000, 0x4000, "unused"), + ) + self.verify(bytes(merged_with_table(sample_table(entries)))) + + def test_rejects_overlapping_partitions(self) -> None: + entries = ( + (1, 2, 0x9000, 0x6000, "nvs"), + (1, 1, 0xE000, 0x2000, "phy_init"), + (0, 0, DEFAULT_APP_OFFSET, DEFAULT_APP_SIZE, "factory"), + ) + with self.assertRaisesRegex(ValueError, "overlap"): + self.verify(bytes(merged_with_table(sample_table(entries)))) + + def test_accepts_moved_app_partition(self) -> None: + app_offset = 0x20000 + entries = ( + (1, 2, 0x9000, 0x6000, "nvs"), + (1, 1, 0xF000, 0x1000, "phy_init"), + (0, 0, app_offset, VERIFY.FLASH_SIZE - app_offset, "factory"), + ) + merged = merged_with_table(sample_table(entries), app_offset=app_offset) + self.verify(bytes(merged), app_offset=app_offset) + + def test_rejects_oversized_application(self) -> None: + with self.assertRaisesRegex(ValueError, "application .* partition limit"): + self.verify(bytes(merged_with_table()), DEFAULT_APP_SIZE + 1) + + def test_rejects_missing_application_image(self) -> None: + merged = merged_with_table() + merged[DEFAULT_APP_OFFSET] = 0xFF + with self.assertRaisesRegex(ValueError, "no ESP application image"): + self.verify(bytes(merged)) + + def test_rejects_app_offset_without_matching_partition(self) -> None: + app_offset = 0x20000 + merged = merged_with_table(app_offset=app_offset) + with self.assertRaisesRegex(ValueError, "match exactly one app partition"): + self.verify(bytes(merged), app_offset=app_offset) + + def test_rejects_duplicate_partition_labels(self) -> None: + entries = ( + (1, 2, 0x9000, 0x6000, "data"), + (1, 1, 0xF000, 0x1000, "data"), + (0, 0, DEFAULT_APP_OFFSET, DEFAULT_APP_SIZE, "factory"), + ) + with self.assertRaisesRegex(ValueError, "labels must be unique"): + self.verify(bytes(merged_with_table(sample_table(entries)))) + + +class FlashArgsTest(unittest.TestCase): + def test_parses_configured_image_offsets(self) -> None: + offsets = VERIFY.parse_flash_args( + "--flash_mode dio --flash_size 8MB\n" + "0x0 bootloader/bootloader.bin\n" + "0x18000 FoloToy-AI-Passport.bin\n" + "0x9000 partition_table/partition-table.bin\n" + ) + self.assertEqual(offsets["FoloToy-AI-Passport.bin"], 0x18000) + self.assertEqual(offsets["partition_table/partition-table.bin"], 0x9000) if __name__ == "__main__": diff --git a/tools/check_repo.py b/tools/check_repo.py index 13315d5..ad4240d 100755 --- a/tools/check_repo.py +++ b/tools/check_repo.py @@ -27,6 +27,49 @@ ROOT_MARKDOWN_ALLOWLIST = { "README.md", "README.zh_CN.md", } +# Register only concrete, vendored component directories, e.g. "components/foo". +# These exemptions never change the input to sensitive-content/conflict checks. +VENDORED_DOC_ROOTS: tuple[str, ...] = () + + +def vendored_document_roots(errors: list[str]) -> tuple[Path, ...]: + """Validate explicit repository-relative directories; reject symlink roots.""" + roots: list[Path] = [] + for name in VENDORED_DOC_ROOTS: + if ( + not isinstance(name, str) + or not name + or "\\" in name + or "\x00" in name + or re.match(r"^[A-Za-z]:", name) + or any(part in ("", ".", "..") for part in name.split("/")) + ): + errors.append(f"invalid VENDORED_DOC_ROOTS entry {name!r}: use a repository-relative directory") + continue + path = ROOT / name + try: + resolved = path.resolve(strict=True) + except (OSError, RuntimeError): + errors.append(f"invalid VENDORED_DOC_ROOTS entry {name!r}: directory does not resolve") + continue + if resolved != path or not resolved.is_relative_to(ROOT) or not resolved.is_dir(): + errors.append(f"invalid VENDORED_DOC_ROOTS entry {name!r}: require a real directory without symlinks") + continue + roots.append(resolved) + return tuple(roots) + + +def is_vendored_document(path: Path, roots: tuple[Path, ...]) -> bool: + """Require both the file's listed path and its target to stay in one root.""" + for root in roots: + if not path.is_relative_to(root): + continue + try: + if path.resolve().is_relative_to(root): + return True + except (OSError, RuntimeError): + return False + return False def git_files() -> list[Path]: @@ -86,9 +129,11 @@ def check_required_files(errors: list[str]) -> None: ) -def check_markdown_links(files: list[Path], errors: list[str]) -> None: +def check_markdown_links( + files: list[Path], errors: list[str], vendored_roots: tuple[Path, ...] = () +) -> None: for path in files: - if path.suffix.lower() != ".md": + if path.suffix.lower() != ".md" or is_vendored_document(path, vendored_roots): continue text = path.read_text(encoding="utf-8") for raw_target in MARKDOWN_LINK_RE.findall(text): @@ -101,9 +146,14 @@ def check_markdown_links(files: list[Path], errors: list[str]) -> None: errors.append(f"{path.relative_to(ROOT)}: missing link target {target}") -def check_document_languages(files: list[Path], errors: list[str]) -> None: +def check_document_languages( + files: list[Path], errors: list[str], vendored_roots: tuple[Path, ...] = () +) -> None: """Require an English default and a linked Simplified Chinese peer.""" - markdown = {path.resolve() for path in files if path.suffix.lower() == ".md"} + markdown = { + path for path in files + if path.suffix.lower() == ".md" and not is_vendored_document(path, vendored_roots) + } for path in sorted(markdown): name = path.name @@ -112,7 +162,7 @@ def check_document_languages(files: list[Path], errors: list[str]) -> None: if name.endswith(".zh_CN.md"): default_name = f"{name[:-len('.zh_CN.md')]}.md" - default_path = path.with_name(default_name).resolve() + default_path = path.with_name(default_name) if default_path not in markdown: errors.append( f"{path.relative_to(ROOT)}: missing English default {default_name}" @@ -124,7 +174,7 @@ def check_document_languages(files: list[Path], errors: list[str]) -> None: continue chinese_name = f"{path.stem}.zh_CN.md" - chinese_path = path.with_name(chinese_name).resolve() + chinese_path = path.with_name(chinese_name) if chinese_path not in markdown: errors.append( f"{path.relative_to(ROOT)}: missing Simplified Chinese peer {chinese_name}" @@ -195,10 +245,11 @@ def check_conflict_markers(files: list[Path], errors: list[str]) -> None: def main() -> int: errors: list[str] = [] + vendored_roots = vendored_document_roots(errors) files = text_files() check_required_files(errors) - check_markdown_links(files, errors) - check_document_languages(files, errors) + check_markdown_links(files, errors, vendored_roots) + check_document_languages(files, errors, vendored_roots) check_action_pins(errors) check_issue_forms(errors) check_sensitive_content(files, errors) diff --git a/tools/validate.sh b/tools/validate.sh index 07217f4..e865a67 100755 --- a/tools/validate.sh +++ b/tools/validate.sh @@ -28,7 +28,21 @@ run_static_checks() { tests/test_ui_pixel_math.c main/ui_pixel_math.c \ -o "${test_dir}/test_ui_pixel_math" "${test_dir}/test_ui_pixel_math" - python3 tests/test_verify_firmware.py + "${CC:-cc}" -std=c11 -Wall -Wextra -Werror -Imain \ + tests/test_demo_navigation.c main/demo_navigation.c \ + -o "${test_dir}/test_demo_navigation" + "${test_dir}/test_demo_navigation" + "${CC:-cc}" -std=c11 -Wall -Wextra -Werror -Icomponents/bsp/src \ + tests/test_bsp_display_rounding.c components/bsp/src/bsp_display_rounding.c \ + -o "${test_dir}/test_bsp_display_rounding" + "${test_dir}/test_bsp_display_rounding" + "${CC:-cc}" -std=c11 -Wall -Wextra -Werror -Icomponents/bsp/src \ + tests/test_bsp_es8311_sleep_check.c components/bsp/src/bsp_es8311_sleep_check.c \ + -o "${test_dir}/test_bsp_es8311_sleep_check" + "${test_dir}/test_bsp_es8311_sleep_check" + PYTHONDONTWRITEBYTECODE=1 python3 tests/test_deep_sleep_contract.py + PYTHONDONTWRITEBYTECODE=1 python3 tests/test_check_repo.py + PYTHONDONTWRITEBYTECODE=1 python3 tests/test_verify_firmware.py rm -rf "${test_dir}" echo "Host tests: PASS" } diff --git a/tools/verify_firmware.py b/tools/verify_firmware.py index 0297fb0..ac436e8 100755 --- a/tools/verify_firmware.py +++ b/tools/verify_firmware.py @@ -4,24 +4,22 @@ from __future__ import annotations import hashlib +import shlex import struct import sys from dataclasses import dataclass from pathlib import Path -EXPECTED_IMAGES = ( - (0x0000, "bootloader/bootloader.bin"), - (0x8000, "partition_table/partition-table.bin"), - (0x10000, "FoloToy-AI-Passport.bin"), +REQUIRED_IMAGES = ( + "bootloader/bootloader.bin", + "partition_table/partition-table.bin", + "FoloToy-AI-Passport.bin", ) FLASH_SIZE = 8 * 1024 * 1024 -PARTITION_TABLE_OFFSET = 0x8000 PARTITION_TABLE_SIZE = 0xC00 -APP_MAX_SIZE = 0x300000 -CARDID_OFFSET = 0x356000 -CARDID_SIZE = 0x4000 +PARTITION_TABLE_SECTOR_SIZE = 0x1000 ENTRY = struct.Struct(" tuple[list[Partition], bool]: +def parse_partition_table( + raw: bytes, minimum_partition_offset: int = 0x9000 +) -> tuple[list[Partition], bool]: """Parse an ESP-IDF table and verify its optional MD5 marker.""" if len(raw) < PARTITION_TABLE_SIZE: raise ValueError("partition table is truncated") @@ -61,7 +61,12 @@ def parse_partition_table(raw: bytes) -> tuple[list[Partition], bool]: _, kind, subtype, offset, size, label_raw, _ = ENTRY.unpack_from(raw, cursor) label = label_raw.split(b"\0", 1)[0].decode("ascii", "strict") - if not label or not size or offset < 0x9000 or offset + size > FLASH_SIZE: + if ( + not label + or not size + or offset < minimum_partition_offset + or offset + size > FLASH_SIZE + ): raise ValueError(f"invalid partition bounds for {label!r}") partitions.append(Partition(kind, subtype, offset, size, label)) @@ -70,49 +75,68 @@ def parse_partition_table(raw: bytes) -> tuple[list[Partition], bool]: return partitions, found_md5 -def verify_protected_layout(merged: bytes, build_dir: Path) -> None: - """Enforce the protected partition and merged-artifact layout.""" +def parse_flash_args(raw: str) -> dict[str, int]: + """Return image paths and offsets from ESP-IDF's line-oriented flash_args.""" + images: dict[str, int] = {} + for line in raw.splitlines(): + fields = shlex.split(line) + if len(fields) != 2: + continue + try: + offset = int(fields[0], 0) + except ValueError: + continue + if fields[1] in images: + raise ValueError(f"duplicate image in flash_args: {fields[1]}") + images[fields[1]] = offset + return images + + +def verify_firmware_layout( + merged: bytes, build_dir: Path, partition_table_offset: int, app_offset: int +) -> None: + """Validate the configured partition table and its application image.""" table = merged[ - PARTITION_TABLE_OFFSET : PARTITION_TABLE_OFFSET + PARTITION_TABLE_SIZE + partition_table_offset : partition_table_offset + PARTITION_TABLE_SIZE ] - partitions, found_md5 = parse_partition_table(table) + partitions, found_md5 = parse_partition_table( + table, partition_table_offset + PARTITION_TABLE_SECTOR_SIZE + ) if not found_md5: raise ValueError("partition table has no MD5 marker") - by_label = {item.label: item for item in partitions} - expected = { - "factory": Partition(0, 0, 0x10000, APP_MAX_SIZE, "factory"), - "cardid": Partition(1, 2, CARDID_OFFSET, CARDID_SIZE, "cardid"), - } - for label, wanted in expected.items(): - if by_label.get(label) != wanted: - raise ValueError(f"partition {label!r} must remain {wanted}, got {by_label.get(label)}") + labels = [item.label for item in partitions] + if len(labels) != len(set(labels)): + raise ValueError("partition labels must be unique") ordered = sorted(partitions, key=lambda item: item.offset) for left, right in zip(ordered, ordered[1:]): if left.end > right.offset: raise ValueError(f"partitions {left.label!r} and {right.label!r} overlap") - for item in partitions: - if item.label != "cardid" and item.offset < CARDID_OFFSET + CARDID_SIZE and CARDID_OFFSET < item.end: - raise ValueError(f"partition {item.label!r} overlaps protected cardid") + matching_apps = [ + item for item in partitions if item.kind == 0 and item.offset == app_offset + ] + if len(matching_apps) != 1: + raise ValueError( + f"application offset 0x{app_offset:x} must match exactly one app partition" + ) + app_partition = matching_apps[0] app_path = build_dir / "FoloToy-AI-Passport.bin" app_size = app_path.stat().st_size - if app_size > APP_MAX_SIZE: - raise ValueError(f"application is {app_size} bytes; limit is {APP_MAX_SIZE}") - if len(merged) <= 0x10000 or merged[0x10000] != 0xE9: - raise ValueError("merged artifact has no ESP application image at 0x10000") + if app_size > app_partition.size: + raise ValueError( + f"application is {app_size} bytes; partition limit is {app_partition.size}" + ) + if len(merged) <= app_offset or merged[app_offset] != 0xE9: + raise ValueError( + f"merged artifact has no ESP application image at 0x{app_offset:x}" + ) - # A derivative may add resource partitions after cardid. The merged file is - # still acceptable only if the protected cardid region contains padding, - # never real device identity data. - payload = merged[ - CARDID_OFFSET : min(len(merged), CARDID_OFFSET + CARDID_SIZE) - ] - if any(byte != 0xFF for byte in payload): - raise ValueError("merged artifact contains forbidden cardid payload bytes") - - print(f"Protected firmware layout: PASS (app {app_size} / {APP_MAX_SIZE} bytes)") + print( + f"Firmware layout: PASS (app {app_size} / {app_partition.size} bytes " + f"in {app_partition.label!r} at 0x{app_offset:x})" + ) def main() -> int: @@ -129,8 +153,20 @@ def main() -> int: print("ERROR: flash_args does not select the required 8 MB flash size", file=sys.stderr) return 1 + try: + image_offsets = parse_flash_args(flash_args) + missing = [name for name in REQUIRED_IMAGES if name not in image_offsets] + if missing: + raise ValueError(f"flash_args is missing required images: {missing}") + if image_offsets["bootloader/bootloader.bin"] != 0: + raise ValueError("the merged bootloader must start at 0x0") + except ValueError as error: + print(f"ERROR: {error}", file=sys.stderr) + return 1 + merged = merged_path.read_bytes() - for offset, relative_name in EXPECTED_IMAGES: + for relative_name in REQUIRED_IMAGES: + offset = image_offsets[relative_name] image_path = build_dir / relative_name if not image_path.is_file(): print(f"ERROR: missing image {image_path}", file=sys.stderr) @@ -146,7 +182,12 @@ def main() -> int: return 1 try: - verify_protected_layout(merged, build_dir) + verify_firmware_layout( + merged, + build_dir, + image_offsets["partition_table/partition-table.bin"], + image_offsets["FoloToy-AI-Passport.bin"], + ) except (OSError, UnicodeDecodeError, ValueError) as error: print(f"ERROR: {error}", file=sys.stderr) return 1