Initial commit: KnobOS firmware 0.1.8

main
mula.liu 2026-11-13 20:41:23 +08:00
commit 3524ccaf56
117 changed files with 146034 additions and 0 deletions

55
.gitignore vendored 100644
View File

@ -0,0 +1,55 @@
# ============================================================
# KnobOS 固件仓库 .gitignore
# 原则:只收「人写的源码 + 生成后不能再生的资源」,
# 编译产物、缓存、系统垃圾一律不入库。
# ============================================================
# ---------- Arduino 编译产物 ----------
# build.sh 用 --build-path build/.cache 做增量编译,
# --output-dir build 导出 bin/elf/map/partition 表;两者都是纯产物,体积上百 MB
build/
build_slave/
# 中断过的缓存现场(build.sh clean 会把旧缓存挪成 .cache.broken-<时间>)
build*.broken-*
*.broken-*
# ---------- 固件二进制 ----------
# release/ 里是历史版本的 .bin(每个 ~2.7MB)。
# 想给仓库瘦身就不入库,用 git tag + 服务端/Release 附件分发;
# 要让历史固件跟着仓库走的话,把下面一行注释掉即可。
release/*.bin
# ---------- 串口调试/截图临时产物 ----------
*.log
shots/
screenshot*.png
serial_*.txt
# ---------- Python 工具(tools/*.py)----------
__pycache__/
*.py[cod]
.venv/
venv/
# ---------- 编辑器 / IDE ----------
.vscode/
.idea/
*.swp
*.swo
*~
# ---------- macOS ----------
.DS_Store
._*
.Spotlight-V100
.Trashes
.fseventsd
# ============================================================
# 注意:以下文件是「生成物」但故意保留入库,别加进忽略列表
# - src/assets/lv_font_*.c 由 tools/gen_font.sh 生成,但 build.sh 只做
# 字符集覆盖校验、不会重新生成;不入库则新克隆编不过
# (单个 media_16 就有 3.4MB,属必要成本)
# - src/assets/icons.c tools/gen_icons.py 生成,情况同上
# ============================================================

208
ARCHITECTURE.md 100644
View File

@ -0,0 +1,208 @@
# knob_os 架构
自研固件,跑在 JC3636K518C_I_W(ESP32-S3R8 / 16MB Flash / 8MB PSRAM / 1.85" 360×360 圆屏 / TF 卡)。
Flash 布局是 **app0 / app1 两个对等的 7.5MB 槽**(`partitions.csv`),互为 OTA 回滚目标;原厂固件不再占槽,整片备份在 `00-固件库/设备原机备份/`。
> 怎么改代码(分层规则、UI/交互规范、字体图标、串口调试、发版与坑)见 [`doc/开发规范.md`](doc/开发规范.md);
> 升级流程见 [`doc/固件更新.md`](doc/固件更新.md);扫码登录见 [`doc/扫码登录.md`](doc/扫码登录.md)。
> 本文只写**结构**:有哪些层、有哪些模块、它们之间怎么连。
>
> 最后核对:2026-11-06(固件 0.1.5)
---
## 1. 分层
```
┌──────────────────────────────────────────────────────────┐
│ apps/ 业务应用(时钟/相册/音乐/星盘/我的/天气/设置) │ 只管"这个应用做什么"
├──────────────────────────────────────────────────────────┤
│ ui/ 主题、圆环控件、导航外壳、模态 │ 只管"长什么样、怎么进怎么出"
├──────────────────────────────────────────────────────────┤
│ core/ App 基类、注册表、表驱动设置 │ 只管"框架规则"
├──────────────────────────────────────────────────────────┤
│ hal/ 屏幕、触摸、编码器、SD、电池、触感 │ 只管"硬件怎么用"
├──────────────────────────────────────────────────────────┤
│ services/ WiFi、平台、天气、星盘、媒体同步、OTA、串口 │ 后台能力,不碰 UI
└──────────────────────────────────────────────────────────┘
```
依赖方向严格单向:`apps → ui → core → hal`;`services` 可被 apps/ui 调用,但**不反向依赖 ui**。
换屏幕只改 `hal`,换风格只改 `ui`,加应用不用碰框架。
主循环只有一个任务(20KB 栈,见 `knob_os.ino` 的 `knobTask`):`displayLoop → shell.loop → 各 service.loop`,
LVGL 非线程安全,所有 UI 操作都在这一个任务里。
---
## 2. 目录
```
knob_os/
├── knob_os.ino 入口:初始化 → 注册应用 → 主循环
├── lv_conf.h LVGL 配置(96KB 堆、字体、缓冲区 40 行)
├── partitions.csv 双槽分区表(nvs/otadata/app0/app1/coredump)
├── build.sh 一键编译(lv_conf 同步 → 字体检查 → 增量编译)
├── slave_audio/ 副控 sketch(UART 收码流 → minimp3 → I2S)
├── doc/ 界面索引 / 开发规范 / 固件更新 / 扫码登录
├── tools/ gen_font.sh · collect_chars.py · gen_icons.py · qr_dump/qr_verify · flash_slave.sh
└── src/
├── config/ BoardPins.h(引脚唯一真源)· AppConfig.h(品牌/版本/常量)
├── core/ App.h · AppManager · Settings(表驱动)· Log
├── hal/ Display · Encoder · Storage · Power · Haptic · bidi_switch_knob
├── ui/ Theme · Widgets · Launcher · Shell · Splash
│ BindScreen · NetWizard · ServerEditor · QrScreen/QrCode
│ OtaPanel · SyncPrompt
├── apps/ ClockApp · GalleryApp · MusicApp · AstroApp · UserApp · WeatherApp · SettingsApp
├── services/ NetService · PlatformService · WebPortal(+web_ui.h)
│ WeatherService · AstroService · MusicLibrary · MediaSync
│ OtaService · LinkService · AudioLink · RemoteDebug
└── assets/ lv_font_cjk_16/24 · lv_font_media_16/24 · lv_font_num_64 · lv_font_zodiac_26 · icons.c
```
`assets/` 里的字体与图标都是脚本生成的,不要手改。
---
## 3. 导航模型
```
┌──────────────┐
上划 │ 一级菜单 │ N 个应用沿圆周均分(当前 7 个)
┌──────────────► │ (Launcher) │ 旋钮选 · 点击进 · 下滑取消
│ └──────┬───────┘
│ │ 点击图标
┌──┴────────┐ ▼
│ 应用全屏 │ ◄────────────┘
│ (App) │ 内置模态:绑定页 / 二维码 / OTA 进度 / 同步进度
└──┬────────┘
│ 下滑
▼
┌──────────────┐
│ 应用设置层 │ 全屏升起,中心聚焦轮盘;只显示本应用的设置项
└──────────────┘
```
| 操作 | 结果 |
|---|---|
| 上划 | 打开一级菜单(当前应用高亮) |
| 一级菜单里旋钮 | 环形切换,中心盘显示应用名 + `序号/总数`(扇区里只有图标) |
| 点击图标 | 进入应用 |
| 一级菜单里下滑 | 取消,回原应用 |
| 应用内下滑 | 升起该应用的设置层(设置应用例外:整页就是设置) |
| 设置层旋钮 | 中心聚焦轮盘:旋到中心即选中;滑轨行只能手指拖值 |
| 任意位置长按 | 回桌面(`sys.boot` 指定的应用,默认时钟) |
| 未配网开机 | 进配网向导(热点名/密码/网址 + 重新配网按钮) |
| 未绑定进入需账号的功能 | 升起绑定页(6 位码上屏) |
Shell 用"容器 + 隐藏"而不是销毁重建:每个应用只 `build()` 一次,切走时 `HIDDEN`——番茄钟切到相册再回来,计时不会断。
---
## 4. 服务层
| 服务 | 职责 | 状态 |
|---|---|---|
| `NetService` | STA 优先、15s 超时回落 SoftAP、mDNS、SNTP、`requestAp/requestStopAp` 请求队列 | 完成 |
| `PlatformService` | 设备身份(chip_id + token)、配对状态机、资料同步、校时、带鉴权的 GET/POST | 完成 |
| `WeatherService` | 平台 `/weather`(服务端聚合和风 + Redis),未绑定不请求 | 完成 |
| `AstroService` | 平台 `/astro`:太阳/月亮星座 + 当月运势,NVS 兜底 | 完成 |
| `MediaSync` | 平台清单 diff、下载、CRC 校验、事务性写卡、同步回报 | 完成(真机端到端待测) |
| `MusicLibrary` | 后台扫卡、ID3v2.2/2.3/2.4 解析(标题/歌手/APIC 封面/时长估算) | 完成 |
| `OtaService` | 查/下/校验/切槽/上报 + 开机尝试计数回滚 | 完成 |
| `AudioLink` | TF 卡 MP3 码流封帧推给副控(UART1 921600 + 流控) | 完成,待真机联调 |
| `LinkService` | 与副控的控制指令通道 + 回包记录 | 通道完成,协议待对齐 |
| `WebPortal` | 内置配网页(单页 PROGMEM)+ 14 个 API | 完成 |
### 4.1 与平台(nex_buddy)的联动
设备只跟自己配的服务端说话,第三方 Key 一概不进固件。
| 用途 | 接口 | 说明 |
|---|---|---|
| 取配对码 | `POST /device/v1/pair/code` | 上报 chip_id/model/版本,拿 6 位码 + `server_time` |
| 查绑定状态 | `GET /device/v1/pair/status` | 只在绑定页内每 5s,不是全局轮询 |
| 换长期 token | `POST /device/v1/pair/claim` | token 存 NVS `pf.token` |
| 资料同步 | `GET /device/v1/profile` | 昵称、星座名;401 = 被吊销 → 回未绑定 |
| 天气 | `GET /device/v1/weather` | 服务端按常住地→出生地选城市;503 = 服务端没配和风 Host |
| 星盘 | `GET /device/v1/astro?lang=` | 太阳/月亮星座 + 当月运势 |
| 校时/心跳 | `GET /device/v1/ping` | 响应带带偏移的 `ts`,顺带刷新 `last_active_at` |
| 扫码取票 | `POST /device/v1/web-login/ticket` | 返回 10 位码 + 二维码 URL |
| 媒体探测 | `GET /device/v1/media/pending` | 有没有变化(seq/rev) |
| 媒体清单 | `GET /device/v1/media/manifest` | 全量清单 + crc32 + rev |
| 媒体下载 | `GET /device/v1/media/{id}/file` | 只放行绑定用户自己的库 |
| 同步回报 | `POST /device/v1/media/report` | synced/deleted + rev |
| 固件检查 | `GET /device/v1/firmware/check?current=` | 指定的目标版本优先,否则同通道更新版本 |
| 固件下载/上报 | `GET /firmware/{id}/download`、`POST /firmware/report` | 只写非运行槽;稳定 60s 后报 success |
实现要点:
- token 形如 `<device_id>:<secret>`,请求头 `Authorization: Bearer <token>` 原样带出去;
- 网络全在后台任务里跑,结果写静态结构由 `loop()` 合并;NVS 与 LVGL 一律主线程;
- 绑定页是模态的:进入相册/音乐/天气时未绑定就升起,点击换码、下滑收起,开着时旋钮与其它手势吞掉。
### 4.2 音频链路(为什么音乐要绕到副控)
主控 I2S 一根线都没接到 DAC;PCM5100 挂在副控的 `GPIO25(BCK)/26(DIN)/27(LRCK)`(`XSMT=GPIO32` 拉高才出声)。
所以"主控解码"这条路不成立:
```
TF 卡 MP3 ──SDMMC──> 主控 AudioLink ──UART1 921600──> 副控 slave_audio
├─ minimp3 软解
└─ I2S 25/26/27 ─> PCM5100
```
帧格式(两边严格一致,改一处必须改两处):
```
AA 55 | cmd | len_lo len_hi | payload | crc8 crc8: poly 0x07, init 0x00
主控→副控 01 START / 02 DATA(≤512B) / 03 END / 04 PAUSE / 05 VOL / 06 STOP
副控→主控 30 STATUS payload=[state, freeKbHi, freeKbLo, 0] 每 250ms 一次
```
流控:副控 64KB 环形缓冲,状态帧上报剩余空间;主控只在 ≥6KB 时继续塞。欠载时副控补静音帧拖住 I2S 时钟,避免"咔"声。
---
## 5. Web 门户 API(`http://nexbuddy.local` / 未配网 `192.168.4.1`)
| 接口 | 说明 |
|---|---|
| `GET /api/status` | 版本、模式、IP、RSSI、电量、TF、天气、分区、当前应用 |
| `GET /api/settings` / `POST /api/setting` | 全部设置项(类型/范围/单位/选项)/ 改一项 |
| `GET /api/files?path=` / `POST /api/cd` | 列目录 / 锁定上传目标目录 |
| `POST /api/upload` / `GET /api/download` / `POST /api/delete` | TF 卡文件读写删 |
| `GET /api/wifi/scan` / `POST /api/wifi` | 扫描热点 / 配网 |
| `POST /api/server/test` | 校验服务端地址并请求 `/healthz` |
| `POST /api/reset` / `POST /api/reboot` | 恢复默认 / 重启 |
| `POST /api/boot/rollback` | 切到另一个槽并重启(另一槽无镜像 → 409) |
---
## 6. 资源预算
| 项目 | 占用 | 上限 |
|---|---|---|
| Flash(app bin) | ≈2.6 MB | 7.5 MB(单槽) |
| 静态 RAM | ≈180 KB | 320 KB |
| LVGL 堆 | 96 KB | — |
| 图片解码缓冲 | 253 KB + 320 KB | 走 PSRAM(8 MB) |
| LVGL 绘制缓冲 | 360×40×2 ≈ 28 KB | 内部 RAM(`LV_BUF_ROWS 40`) |
中文字体是 Flash 大头(UI 子集 ×2 档 + 媒体字体 2500 字 ≈ 900 KB)。
`collect_chars.py` 只收字符串字面量、跳过注释与网页,所以体积可控。
---
## 7. 边界(刻意没做的)
| 项 | 现状 | 后续 |
|---|---|---|
| 音频发声 | 副控解码出声,副控需单独烧一次 | 真机联调:解出第一声后,进度换成副控回报的真实值 |
| 音频格式 | 只解析 MP3 帧头估时长;WAV/FLAC/M4A 能列出但无时长 | 按扩展名补解析 |
| 副控 OTA | 无远程升级通道(主控控制不了副控 EN/IO0) | 只 USB 烧(`tools/flash_slave.sh`) |
| 蓝牙音箱 | 主控只有 BLE,A2DP 需副控重写 | 单独立项(M6) |
| 主题色切换 | 立即生效但已有控件不重建,需重进应用 | accent 变化时重建当前应用 |
| 文本类设置 | 服务端地址/城市等在配网页改,设备端只读 | 设备端九宫格输入法(工作量大) |
| 上传时 UI | multipart 写卡期间 loop 被占,界面卡一下 | 分块让出 CPU 或切"传输中"界面 |
| 天气设置 | 天气应用没有设置项(城市/单位由账号与接口决定) | — |

95
README.md 100644
View File

@ -0,0 +1,95 @@
# knob_os · 设备固件
跑在 JC3636K518 旋钮屏(ESP32-S3R8 / 1.85" 360×360 圆屏 / TF 卡)上的自研固件。
固件占 **app0 / app1 两个对等 7.5MB 槽**,OTA 在两者之间来回写、互为回滚;原厂固件不再占槽(整片备份在 `00-固件库/设备原机备份/`)。
| 想看什么 | 去哪 |
|---|---|
| 结构:分层、模块、导航、与平台联动 | [`ARCHITECTURE.md`](ARCHITECTURE.md) |
| 怎么改:代码/UI/交互/字体/串口/发版/坑 | [`doc/开发规范.md`](doc/开发规范.md) |
| 升级(双槽 / 回滚 / 服务端契约 / 发版) | [`doc/固件更新.md`](doc/固件更新.md) |
| 扫码登录(设备出码 → 手机免密进网页) | [`doc/扫码登录.md`](doc/扫码登录.md) |
| 界面截图索引 | [`doc/界面一览.md`](doc/界面一览.md) |
| 硬件引脚与整机备份 | [`../README.md`](../README.md) |
---
## 能做什么
| 应用 | 内容 |
|---|---|
| 时钟(默认桌面) | 大号时间 + 秒进度环;旋钮设定番茄钟分钟数,点击开始/暂停,长按归零;工作/短休/长休自动接力 |
| 相册 | 读 TF 卡 `/pic/*.jpg`,旋钮或左右滑切换,定时轮播,圆形裁切 + 页码胶囊 |
| 音乐 | 本地唱片机:扫 `/music`,解析 ID3 标题/歌手/封面,中央黑胶旋转;旋钮切歌、点击盘心播放/暂停;发声走副控(主控无 DAC) |
| 星盘 | 太阳/月亮星座 + 本月运势(平台 `/astro`),旋钮翻页,运势页可滚 |
| 我的 | 昵称/太阳星座/常住地/生日与时区(只读);**转旋钮 = 拉一次资料**,**长按屏幕 = 开/关管理二维码** |
| 天气 | 平台 `/weather`(服务端聚合和风 + 缓存);温度/体感/湿度/风力,环按湿度填充 |
| 设置 | 网络 / 固件 / 系统 / 账号 / 关于;全屏中心聚焦轮盘 |
交互:上划进一级菜单(7 个扇区,只放图标,中心盘显示应用名与 `序号/总数`)→ 旋钮切换、点击进入 →
应用内下滑打开该应用的设置层 → 长按回桌面。旋钮是主要输入,触摸只做点按与滑动。
**绑定**:相册/音乐/天气进入时未绑定会自动升起绑定页,6 位码上屏,网页输码即可;绑定后换长期 token 存 NVS。
**配网**:未配网时开热点 `nex_buddy` / `12345678`,屏幕给出热点名、密码与网址,手机连上会自动弹配置页(captive portal)。
**扫码登录**:「我的」页长按屏幕出二维码(底部 1/3 遮罩层写着这行提示),手机扫码免密进个人页(票据 5 分钟、一码一用)。
---
## 编译与烧录
```bash
cd 01-开发工作区/新项目/knob_os
bash build.sh # → build/knob_os.ino.bin
bash ../../工具脚本/flash_app.sh build/knob_os.ino.bin /dev/cu.usbmodemXXXX app0
python3 ../../工具脚本/bootctl.py set app1 # 手动切槽(一般由 OTA 自己切)
```
`flash_app.sh` 把 **分区表 + 目标槽 + otadata** 一起写,槽偏移从 `partitions.csv` 现读,`nvs` 不动
(烧完不用重新配网/绑定);写入前校验体积(7.5MB/槽)与镜像头 `0xE9`。
发版(编译 → 上传 → 发布)用 `工具脚本/release.sh`,详见 [`doc/固件更新.md`](doc/固件更新.md) §6。
改了中文文案要重新生成字体子集,否则新字是方框:
```bash
bash tools/gen_font.sh
```
`build.sh` 会先跑 `tools/collect_chars.py --check` 把这件事拦在编译前。
---
## 串口调试
115200,固件内置命令通道(截屏、切应用、注入旋钮、下发 WiFi/服务端地址、OTA 联调…)。
完整命令表见 [`doc/开发规范.md`](doc/开发规范.md) §9,最常用的几个:
| 键 | 作用 |
|---|---|
| `s` | 截一帧发回主机(存 PNG) |
| `1`–`7` | 直接切到第 N 个应用 |
| `u` / `d` / `c` | 开一级菜单 / 开设置层 / 全关 |
| `+` / `-` | 凭空拧一格旋钮 |
| `N` / `V` / `?` | 网络状态 / 槽位与升级状态 / 当前应用与剩余堆 |
---
## 环境
```
arduino-cli 1.5.1 · esp32:esp32@3.0.7
lvgl 8.4.0 · ESP32_Display_Panel 0.2.2 · ESP32_IO_Expander 0.1.0
esp-lib-utils 0.2.2 · JPEGDEC 1.8.5 · ArduinoJson 7.4.3
```
FQBN:
```
esp32:esp32:esp32s3:FlashSize=16M,PSRAM=opi,CDCOnBoot=cdc,USBMode=hwcdc,PartitionScheme=app3M_fat9M_16MB,UploadSpeed=921600
```
> 分区表用根目录 `partitions.csv` 覆盖(不是 FQBN 里那个官方 `app3M_fat9M_16MB`);
> `build.sh` 还会把 `upload.maximum_size` 覆盖成 7864320,否则 arduino-cli 按 3MB 校验会误报超限。
> 库版本别随手升级:Display_Panel 0.2.2 是下划线类名,且必须配 IO_Expander 0.1.0。

57
build.sh 100644
View File

@ -0,0 +1,57 @@
#!/bin/bash
# build.sh —— 编译 nex_buddy
#
# 用法:./build.sh 编译并导出 bin 到 build/
# ./build.sh clean 清缓存后重编
#
# 为什么要有这个脚本:Arduino 编译需要两个环境前提
# 1. lv_conf.h 必须放在 libraries 根目录(lvgl 的头文件按 ../../lv_conf.h 找它)
# 2. 引脚与库版本要固定,避免换机器后行为不一致
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
AC="${ARDUINO_CLI:-$HERE/../../工具/arduino-cli}"
LIBS="${ARDUINO_LIBS:-$HOME/Documents/Arduino/libraries}"
FQBN="esp32:esp32:esp32s3:FlashSize=16M,PSRAM=opi,CDCOnBoot=cdc,USBMode=hwcdc,PartitionScheme=app3M_fat9M_16MB,UploadSpeed=921600"
# 同步 lv_conf.h
if ! cmp -s "$HERE/lv_conf.h" "$LIBS/lv_conf.h" 2>/dev/null; then
echo ">> sync lv_conf.h -> $LIBS"
cp "$HERE/lv_conf.h" "$LIBS/lv_conf.h"
fi
CLEAN=""
CACHE="$HERE/build/.cache"
if [ "${1:-}" = "clean" ]; then
CLEAN="--clean"
# 不能 rm -rf:safe-delete 策略会拦下整条命令(报 SAFE_DELETE_BULK_CONFIRM_REQUIRED),
# build.sh 又是 set -e,直接整轮编译失败。挪走等效,而且留了一份现场。
if [ -d "$CACHE" ]; then
mv "$CACHE" "$CACHE.broken-$(date +%H%M%S)"
echo ">> 旧缓存已挪到 $(basename "$CACHE").broken-*"
fi
fi
# 字体子集一致性检查:新增中文文案后如果忘了重跑 tools/gen_font.sh,
# 新字在屏幕上会显示成方框,而且不会有任何报错——所以在这里拦一下。
python3 "$HERE/tools/collect_chars.py" "$HERE" --check || true
mkdir -p "$HERE/build" "$CACHE"
echo ">> compiling ($FQBN)"
# --build-path 打开增量编译:不改库和 lv_conf 时,第二次起只重编改过的那几个 .cpp,
# 从 8 分钟降到几十秒。不给它的话 arduino-cli 每次都从零编,改一行字也要等 8 分钟。
# --build-property upload.maximum_size:arduino-cli 的容量校验默认取 board 选项里的 3MB,
# 而实际分区表(根目录 partitions.csv)是 7.5MB 槽。不显式覆盖的话,固件一旦超过 3MB
# 就会报 "text section exceeds available space",等于新分区白改。7864320 = 0x780000。
"$AC" compile $CLEAN --build-path "$CACHE" --output-dir "$HERE/build" --fqbn "$FQBN" \
--build-property "upload.maximum_size=7864320" "$HERE"
BIN="$HERE/build/knob_os.ino.bin"
if [ -f "$BIN" ]; then
SIZE=$(stat -f%z "$BIN" 2>/dev/null || stat -c%s "$BIN")
echo
echo ">> 产物: $BIN"
# 槽位大小来自根目录 partitions.csv(app0/app1 各 0x780000 = 7.5MB)
echo ">> 大小: $SIZE 字节 ($(awk "BEGIN{printf \"%.2f\", $SIZE/1048576}") MB / 槽位 7.5 MB)"
echo ">> 烧录: ../../工具脚本/flash_app.sh \"$BIN\" /dev/cu.usbmodemXXXX app0"
fi

View File

@ -0,0 +1,121 @@
# 双分区(app0 原厂 / app1 自研)验证报告
> **历史文档(2026-11-03)。** 当时用的是原厂分区表 `app3M_fat9M_16MB`,app0 保持原厂固件不动,
> 自研固件进 app1(0x310000,≤3MB),靠 otadata 切换。
> 现行方案已改为自定义分区表,app0/app1 **两个 7.5MB 对等槽**,`knob_os` 就装在 app0,
> 偏移从 `knob_os/partitions.csv` 读(原来的 `flash_app1.sh` 写死 0x310000,因此废弃)。
> 现行流程见 `新项目/knob_os/doc/固件更新.md`;本文只作为"双槽 + otadata 切换可行"的验证记录保留。
验证日期:2026-11-03 | 设备:ESP32-S3R8(MAC `44:bd:8d:6e:a0:a0`,16MB Flash)
结论:**双分区可用,原厂固件零改动、字节级未变,可随时来回切。**
---
## 一、结论速览
| 验证项 | 结果 |
|---|---|
| 自研固件能否从 app1(0x310000) 启动 | ✅ 启动成功,`esp_ota_get_running_partition()` 返回 `app1 @0x310000` |
| 固件内命令切回原厂 | ✅ 发送 `f` → `esp_ota_set_boot_partition(ota_0)` → 重启进原厂 |
| 电脑侧命令切到 app1 | ✅ `bootctl.py set app1`(写 otadata)→ 重启进自研 |
| 原厂分区是否被改动 | ✅ app0 3MB SHA256 与备份**完全一致**(0 个差异块) |
| 兜底:擦除 otadata | ✅ 自动回落 app0 原厂,且原厂固件会自己重建 otadata |
| 固件体积 | 318 KB / 上限 3 MB(10%),余量充裕 |
---
## 二、分区布局(沿用原厂,未改分区表)
| 分区 | 类型 | 偏移 | 大小 | 用途 |
|---|---|---|---|---|
| `nvs` | data/nvs | 0x009000 | 20 KB | **原厂与自研共用**(WiFi 配置等) |
| `otadata` | data/ota | 0x00E000 | 8 KB | 启动分区选择(2 个扇区交替写) |
| `app0` | app/ota_0 | 0x010000 | 3 MB | 原厂固件(**只读,不碰**) |
| `app1` | app/ota_1 | 0x310000 | 3 MB | 自研固件(≤3MB) |
| `spiffs` | data/spiffs | 0x610000 | 9.875 MB | **原厂与自研共用** |
| `coredump` | data/coredump | 0xFF0000 | 64 KB | 崩溃转储 |
---
## 三、核心发现:otadata 的 CRC 算法不标准
这是这次踩的最深的一个坑,直接决定"能不能从电脑侧切分区"。
`otadata` 每条记录 32 字节:`ota_seq(4) + seq_label(20) + ota_state(4) + crc(4)`,
启动槽位 = `(ota_seq - 1) % 2`,即 `seq=1 → app0`、`seq=2 → app1`。
**标准 IDF 是对前 28 字节算 CRC;这台 bootloader 只对前 4 字节 `ota_seq` 算,且初值为 0。**
用出厂记录反推验证:`seq=1`、`crc=0x4743989A`
```python
zlib.crc32(struct.pack('<I', 1), 0xFFFFFFFF) == 0x4743989A # 命中
zlib.crc32(entry[:28]) # 0x8A6BBE7E 被拒绝
```
第一次按标准 28 字节写入,bootloader 直接打印
`E (27) boot: ota data partition invalid and no factory, will try all partitions`
然后回退 app0——所以前期"以为切过去了其实还在跑原厂"。
实现见 `01-开发工作区/工具脚本/bootctl.py`(`crc_of()`)。
---
## 四、编译环境(本机已装好)
| 组件 | 位置 / 版本 |
|---|---|
| arduino-cli | `01-开发工作区/工具/arduino-cli`(1.5.1,免安装静态二进制) |
| ESP32 core | `esp32:esp32@3.0.7` = **ESP-IDF v5.1.4**,与原厂 bootloader 同代 |
| 下载源 | GitHub 慢/断流时改走 `dl.espressif.cn/github_assets/...`(实测 5 MB/s vs 70 KB/s) |
编译命令(`FQBN` 与原机硬件一致:16MB Flash + OPI PSRAM + USB CDC):
```bash
cd "01-开发工作区/新项目/dual_boot_test"
"../../工具/arduino-cli" compile \
--fqbn "esp32:esp32:esp32s3:FlashSize=16M,PSRAM=opi,CDCOnBoot=cdc,USBMode=hwcdc,PartitionScheme=app3M_fat9M_16MB,UploadSpeed=921600" \
--output-dir build .
```
> 只取 `build/<sketch>.ino.bin` 烧到 0x310000,**不要烧 merged.bin / bootloader / partitions**(那是整机镜像,会覆盖原厂 bootloader 和分区表)。
---
## 五、日常操作三条命令
```bash
cd "01-开发工作区/工具脚本"
# 1) 编译好的固件烧到 app1 并切过去(自动校验大小/镜像头)
./flash_app1.sh ../新项目/dual_boot_test/build/dual_boot_test.ino.bin
# 2) 回原厂(下次启动生效)
python3 bootctl.py set app0
# 3) 再回自研
python3 bootctl.py set app1
# 保底:擦掉 otadata,必然回落原厂
python3 bootctl.py erase
```
设备在自研固件里时,也可以用串口单字符命令:`f` 回原厂、`a` 来自研、`r` 复位、`e` 打印分区信息。
---
## 六、后续开发必须注意的四件事
1. **app1 上限 3MB**。当前 LVGL 8.4 全量 + 中文字库大约 1.5~2MB,够用;超了要改分区表(那就动到原厂布局了)。
2. **`nvs` 和 `spiffs` 是和原厂共用的**。自研固件里写 NVS 键值、写 SPIFFS 文件,原厂固件都看得见,可能互相踩。建议自研数据统一放 NVS 的独立命名空间(如 `myapp`),SPIFFS 尽量只读。
3. **不要把 app0 当 OTA 目标**。自研固件里可以 `esp_ota_write` 到 app1 自身做升级,但绝不能对 ota_0 写——那就把原厂固件覆盖了,只能靠整片备份恢复。
4. **不要手拼 otadata 字节**,一律走 `bootctl.py` 或 IDF 的 `esp_ota_set_boot_partition()`。
---
## 七、附带确认的几件事
- **原厂固件自带 OTA 模块**:二进制里有 `Reboot to ota mode`、`Receive firmware Failed!`、`CURRENT FIRMWARE: VALID/PENDING_VERIFY`、`SET VALID` 等字符串,说明厂商本来就是按 OTA 架构做的(app0/app1 双分区不是闲置的)。
- **原厂固件启动时会写 otadata**:擦除后首次启动,它自动写入 `seq=1` 并标记 VALID——出厂那条记录的来历就是这个。
- **app 描述符不能用来区分固件**:用 arduino-esp32 3.0.7 预编译库编译出来的 app,描述符里的 `project=arduino-lib-builder`、`version=769c168`、`build=Oct 22 2024 21:30:13`、`idf=v5.1.4-972` 和原厂**完全一样**(都来自库的构建)。要区分只能看固件自己的 banner。
- **电池读数**:插 USB 时 `BATT_ADC` 读到 4620~4678 mV(×2 后),可作为"外部供电"判据;判据阈值取 4300 mV 合适。
- **原厂 Web API 实测可用**:设备联网后 `curl http://<设备IP>/getstatus` 返回 JSON(应用列表、音量 36、亮度 70、宿主 IP 等),二次开发时可以直接复用。

173
doc/固件更新.md 100644
View File

@ -0,0 +1,173 @@
# 固件更新(OTA)
> 固件不固定在某个槽、也不保留原厂固件:**app0 / app1 两个对等槽**,谁都可以被 OTA 覆盖,互为回滚目标。
> 服务端侧见 `服务平台/03-服务端开发文档.md` §7.3,管理端页面在 `/admin → 固件管理`。
> 最后核对:2026-11-06(固件 0.1.5)
---
## 1. 为什么是双槽
原来的做法是"原厂留 app0、自研固定 app1",回滚 = `bootctl.py set app0`。三个问题:
1. 只能回到原厂,回不到**上一个自研版本**;坏版本只能整机回厂;
2. app1 只有 3MB,固件已占 81%,再进功能就没余量;
3. 还占着 9.9MB `ffat`,而本项目一分没用(图片音乐都在 TF 卡)。
所以把 `ffat` 让给 app:**2 × 7.5MB**,两个槽都是自家固件。
## 2. 分区布局
见 [`../partitions.csv`](../partitions.csv):
| 分区 | 起始 | 大小 | 说明 |
|---|---|---|---|
| `nvs` | 0x9000 | 20KB | 配网、绑定 token、设置(**重分区时偏移不变,不会被刷掉**) |
| `otadata` | 0xE000 | 8KB | "下次启动哪个槽",OTA 与 bootctl 都写这里 |
| `app0` | 0x10000 | 7.5MB | ota_0 |
| `app1` | 0x790000 | 7.5MB | ota_1 |
| `coredump` | 0xF10000 | 64KB | 崩溃现场 |
尾部 0xE0000(896KB)暂不分配,留给以后可能塞进 flash 的静态资源。
## 3. 升级流程
```
设备 服务端
│ GET /device/v1/firmware/check?current=0.1.4&lang=zh
│ ──────────────────────────────────────────────►
│ {"update":false} 或 {update,version,size,sha256,url,mandatory,reason,notes}
│ ◄──────────────────────────────────────────────
│ GET <serverUrl>+<url>(Bearer)
│ ──────────────────────────────────────────────►
│ 边下边写"非运行槽":Update.write(4KB) + sha256 增量
│ 进度 → 全屏进度环(ui::OtaPanel)
│ sha256 不一致 → Update.abort(),另一个槽保持原样
│ 一致 → Update.end(true):写 otadata,下次启动进新槽
│ ESP.restart()
│ 稳定 60 秒且联网 → POST /device/v1/firmware/report {"status":"success"}
```
关键约束:**只写非运行槽**。任何时刻至少有一个槽是完整的、可启动的。
## 4. 回滚
### 4.1 不用 IDF 的 rollback API
`esp_ota_mark_app_valid_cancel_rollback()` 要求 `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y`,
Arduino 的 sdkconfig 默认关闭,调用直接返回 `ESP_ERR_OTA_INVALID_STATE`;改 sdkconfig 要自定义板级配置,代价大于自己数三次启动。
### 4.2 我们的办法:开机尝试计数
放在 `OtaService::begin()`(`setup()` 里紧跟 `settings.begin()`,早于任何 UI):
```
每次开机: NVS "ota/try" += 1
if try > 3 且另一个槽有镜像 → esp_ota_set_boot_partition(另一个槽) + 重启
稳定判定: 运行满 60 秒且已联网 → try = 0,记 good=版本 / goodslot=槽位
```
- 新固件连崩三次 → 自动回到上一个能跑的版本;
- "有镜像"靠读槽首字节判断:`0xE9` 才是 ESP 镜像魔数,空槽是 `0xFF`;
- 手动回滚:串口 `R`(设置页**不提供**回滚按钮——回退是启动失败时的自愈机制,不该让用户点)。
代价:坏固件要重启 3 次才回滚。另一个槽没有镜像时**不自动回滚**(切过去就是砖,宁可在坏固件里等人用 USB 救)。
## 5. 服务端契约
### 5.1 查询
```
GET /device/v1/firmware/check?current=<当前版本>&lang=<zh|en>
Authorization: Bearer <device token>
```
- `200 + {"update": false}`:已是最新(最常见);`204` / `404` 也当作无更新;
- 传 `current` 会顺手把设备版本写进库,管理端"谁在什么版本"由此而来;
- 选择顺序:**指定的目标版本优先**(可降级 = 回滚)→ 否则同机型同通道最新已发布且严格高于当前版本。
```json
{
"update": true, "version": "0.1.5", "size": 2690896, "sha256": "…",
"url": "/device/v1/firmware/<uuid>/download",
"mandatory": false, "reason": "newer", "notes": "修复天气页缺字"
}
```
`mandatory=true` 表示这是管理员指定的目标版本。**设备端目前只解析、不做强制安装**:仍需用户点「固件更新」那一行才下载。
### 5.2 下载
```
GET /device/v1/firmware/<uuid>/download
```
- 只有已发布的包能下;被指定了目标版本的设备即使包已下线也放行(否则管理员一点"下线",正在下载的设备就 404);
- 响应带 `X-Firmware-Version` / `X-Firmware-Sha256`,便于抓包核对;
- 整包顺序下载,**不做 Range/断点续传**(2.5MB,失败重来更简单)。
### 5.3 上报
```
POST /device/v1/firmware/report
{"version":"0.1.5","status":"success|failed","error":"","slot":"app1"}
```
| 时机 | status | 说明 |
|---|---|---|
| 升级后**稳定 60 秒且联网** | `success` | 清 `ota/pending`,服务端同步 `fw_version` + `boot_slot` |
| 下载/校验/写入失败 | `failed` | `error` 带原因,管理端"升级失败"列显示它 |
检查更新阶段的失败(没网、没绑定)不上报——那是噪音,不代表升级失败。
## 6. 发版
```bash
# 1. 改版本号(不改会被反复推同一版)
vim src/config/AppConfig.h # BRAND_VERSION "0.1.6"
# 2. 一条命令:编译 → 自检 → 上传 → 发布
bash ../../工具脚本/release.sh --notes "修了什么"
```
`release.sh` 做的事:从 `AppConfig.h` 读版本号(编的与传的必然一致)→ `build.sh` → 校验首字节 `0xE9` →
登录管理端 → 同名版本先删(允许覆盖重传)→ `POST /api/admin/firmwares` 上传并按 `publish` 发布 → 打印结果。
开关:`--no-publish`(先传不发)、`--beta`、`--skip-build`、`--server <url>`、`--channel`。
管理端固件页的三种动作,别混:
| 动作 | 作用 | 设备何时动 |
|---|---|---|
| **发布 / 下线** | 标记这个包能否被普通检查命中 | 设备下次「检查更新」时自取(自主升级的开关) |
| **批量升级** | 把所有低版本设备的目标版本写成这个包 | 等设备自己来问,服务端不推送 |
| **单台「选择版本」** | 只给这一台指定目标版本(允许降级 = 回滚) | 同上 |
## 7. 设备端怎么用
设置页「固件」组(紧跟网络组,不埋到"关于"里):
- `版本`:只显示版本号(槽位是开发期概念,排障看串口 `V`);
- `固件更新`:点一下 = 检查;已知有新版则直接装。这一行实时显示 `检查中 / 已是最新 / 0.1.6 / 42% / 即将重启 / 失败,重试`;
- 升级期间升起全屏进度环("正在写入新固件 · 请勿断电"),盖住所有页面。
串口:`V` 看槽位与状态、`C` 检查更新、`I` 装已知版本、`O <url>` 按 URL 直升级、`R` 手动回滚。
## 8. 本地联调(不经过平台)
```bash
cd 01-开发工作区/新项目/knob_os
mkdir -p /tmp/ota && cp build/knob_os.ino.bin /tmp/ota/next.bin
python3 ../../工具脚本/ota_serve.py /tmp/ota 8801 # 会打印可直接用的 O 命令
# 串口:O http://192.168.x.x:8801/next.bin
```
`O` 走与正式升级完全相同的下载/校验/切槽路径(只跳过"查版本"),这一步通过后,接服务端只剩 JSON 字段对齐。
## 9. 已知限制
1. **升级期间不能断电**:最多把目标槽写坏,当前槽仍可启动,但要重新升一次;
2. **没有断点续传**:弱信号下 2.5MB 可能两三分钟,超时阈值是"20 秒没有新字节";
3. **回滚靠计数**:如果坏固件只是"某个页面崩"却开得了机,60 秒已判定成功,得用 `R` 手动回;
4. **`mandatory` 未做强制安装**:指定版本仍需用户在设备上点「固件更新」;
5. **原厂固件不再占槽**:整片备份在 `00-固件库/设备原机备份/2026-11-03_ESP32-S3主控_16MB整片.bin`,要回去就整片写回。

View File

@ -0,0 +1,114 @@
# 固件逆向与二次开发评估
> **历史文档(2026-11-03 的评估)。** 文中"app1 空着 3MB 可用""自研固件进 app1"是基于**原厂分区表**的判断;
> 现行为自定义分区表,app0/app1 各 7.5MB,`knob_os` 跑在 app0。结论(原厂源码不在包里、技术栈同示例工程、
> 可复用资产清单)仍然有效,路线部分请看 `新项目/knob_os/doc/开发规范.md` 与 `doc/固件更新.md`。
日期:2026-11-03 | 依据:`00-固件库/设备原机备份/2026-11-03_ESP32-S3主控_16MB整片.bin`、原厂包、实测串口日志
---
## 一、结论先说
**原厂固件的源码不在资料包里**——包里只有两个 Arduino 示例(`ST77916_LVGL_DEMO`、`ST77916_LVGL_IMG_DEMO`),没有番茄钟/蓝牙音乐/AIDA64 那一套的实现代码。
但这不代表要从零开始,也不算坏消息:**原厂固件用的技术栈和示例是同一条线**,而且我从固件里挖出了不少可复用资产(见第三节)。
---
## 二、证据(固件里残留的构建信息)
| 线索 | 内容 |
|---|---|
| 源码路径字符串 | `src/mydriver/uart1.cpp`、`src/mydriver/idfknob/iot_knob.c`、`src/mydriver/screen_init/scr_st77916.h` |
| 关键巧合 | 这个 `scr_st77916.h` **和示例里的文件名完全相同** → 示例就是工厂驱动代码的对外版本 |
| 构建环境 | `C:/Users/Fei/.platformio/packages/framework-arduinoespressif32...` → **PlatformIO + Arduino 框架**(不是纯 IDF) |
| 显示库 | `ESP32_Display_Panel-0.2.2`(示例包内是 1.0.1,API 有差异) |
| 日志模块 | `[MAIN] [WIFI] [IO] [DAC] [FS] [FFT] [UART1] [HAPTIC] [OTA]` |
| 应用体积 | 1.97 MB,落在 3 MB 的 app0 分区里 |
模块划分(从日志推断):`MAIN`(总控/任务)、`WIFI`(配网+WebServer)、`IO`(TF卡/MJPEG/相册播放)、`DAC`(I2S 输出)、`FFT`(音谱)、`UART1`(与副控通信)、`HAPTIC`(震动)、`OTA`。
---
## 三、可复用的资产(已经拿到手的)
| 资产 | 位置 | 价值 |
|---|---|---|
| 屏幕驱动源码 `scr_st77916.h` | 示例目录 | 与工厂同源,ST77916 QSPI 初始化直接可用 |
| LVGL 8.4.0 + 转场/旋钮控件 | 示例 `knob.c`、`bidi_switch_knob.c` | 现成的旋钮交互 UI 组件 |
| **内嵌 Web 控制页源码** | `01-开发工作区/逆向资料/webui/`(本次提取) | 11.7 KB + 5.1 KB,HTML/JS/CSS 全明文 |
| **完整 HTTP API** | 见第四节 | 可被任何设备/脚本调用 |
| TF 卡素材包 | `02-原厂资料/.../TF卡`(351 MB) | 字体 bin、3 套主题时钟动画、mjpeg、图片、音乐 |
| 双分区空位 | app1(0x310000,3 MB,当前全空) | 原厂固件与自研固件可共存 |
| 副控固件 | ESP32-U4WDH | 蓝牙 A2DP + HID 音量现成可用,可不动 |
### HTTP API(从提取出的网页 JS 还原)
| 接口 | 说明 |
|---|---|
| `GET /getstatus` | 返回 JSON:`apps[]`、`Language`、`Mark`、`CityCode`、`WeatherApi`、`HostIP`、`vol`、`bri`、`PlayMode` |
| `GET /docmd?cmd=N` | 执行命令:`100+app.id` 切换功能页;`800+app.id` 设开机默认页 |
| `GET /save?hostip=` / `?volume=` / `?brightness=` / `?timestamp=` | 保存副屏主机 IP / 音量 / 亮度 / 校时 |
| `GET /saveweather?citycode=&apikey=` | 天气城市与 key(和风/高德/OpenWeather) |
| `GET /wifilist` | 扫描到的热点列表(JSON) |
| `GET /configwifi?ssid=&pwd=` | 配网 |
| `GET /` | 控制页;未配网时 `192.168.4.1` 进配网页 |
---
## 四、各功能能不能"保留",怎么做
| 功能 | 在哪颗芯片 | 能不能直接留 | 二次开发要做什么 | 难度 |
|---|---|---|---|---|
| 番茄闹钟(倒计时+震动) | S3 | ❌ 无源码 | LVGL 画界面 + 编码器/触摸事件 + DRV2605 震动;素材可复用 | ★ |
| 电子相框 / MJPEG 播放 | S3 | ❌ 无源码 | 示例 `ST77916_LVGL_IMG_DEMO` 已有读取+显示骨架,补播放列表/切换即可 | ★★ |
| TXT 阅读 | S3 | ❌ 无源码 | LVGL 文本 + TF 卡读文件 + 字体 bin(已给) | ★★ |
| 拾音音谱 | S3 | ❌ 无源码 | PDM 麦克风(GPIO45/46) + esp-dsp FFT + LVGL bar | ★★★ |
| AIDA64 副屏 | S3 + PC | ❌ 无源码 | 设备端做 HTTP client 拉 AIDA64 RemoteSensor 数据;`.rslcd` 皮肤已给 | ★★★ |
| 天气 | S3 | ❌ 无源码 | 和风/高德/OpenWeather HTTP + JSON | ★★ |
| **蓝牙音乐播放** | **副控 U4WDH** | ✅ 可整颗不动 | 保留副控固件就仍能放歌;S3 侧只发 UART 控制命令 | ★★★★(协议) |
| 电脑音量 HID | 副控 U4WDH | ✅ 同上 | 同上 | ★★★★ |
> 关键认知:**你看到的功能大半是两颗芯片协作的结果**。S3 负责界面,音频通路(A2DP 收流 → I2S → PCM5100A)在副控。想"保留蓝牙音乐"有两条路:
> - **保守**:副控固件一个字不改,自己在 S3 上把 `uart1.cpp` 那套协议摸出来(可挂逻辑分析仪抓 S3↔副控 TX/RX,或从副控固件的字符串反推);
> - **激进**:副控也自己重写(ESP32 A2DP sink 例子很多,20 行就能收流),但要重刷副控——已有 4 MB 整片备份,可回滚。
---
## 五、三条路线
### 路线 A:双分区共存(推荐)
原厂固件留在 `app0` 一动不动,自己的固件烧到 `app1`,用 otadata 切换启动哪个。
```
app0 0x010000 (3MB) 原厂固件(不碰)
app1 0x310000 (3MB) 你的固件(≤3MB)
otadata 0xe000 决定启动哪个
```
- 首次进入自研固件:写一条 otadata 记录(`seq=2, state=VALID`)。若 CRC 不被 bootloader 认,最坏结果是**继续启动原厂固件**,不会变砖。
- 自研固件里放一个"切回原厂"的入口(HTTP 接口或长按),内部调用 IDF 官方 `esp_ota_set_boot_partition()` —— 由 IDF 自己写 otadata,一定正确。
- 兜底恢复:`esptool erase-region 0xe000 0x2000` 擦掉 otadata → 必定回 `app0`。
- 代价:自研固件受 3 MB 限制(LVGL 项目通常 1.5~2 MB,够)。
### 路线 B:以示例为骨架全量重写
把 `ST77916_LVGL_DEMO` 改成自己的工程,一个个功能复刻。好处是代码 100% 自己的、结构清晰;坏处是要重做全部功能,且蓝牙音乐绕不开副控。
### 路线 C:逆向原厂固件
Arduino 静态链接、无符号表,只能拿到字符串和结构。除了已提取的 Web UI,其它(AIDA64 协议、UART 协议)逆向成本远高于重写,**不建议**。
---
## 六、马上可以做的三件事
1. 先把 Web UI/API 用起来:配网后 `http://<设备IP>/getstatus`,10 秒验证 API 是否如文档所述(不改任何东西)。
2. 搭路线 A 的骨架:一个能显示 UI + 读电量 + 提供"切回原厂"接口的最小工程,烧到 app1 验证双分区可行。
3. 决定副控策略(保留 / 重写),这决定了"蓝牙音乐"要花多少力气。
## 七、风险与边界
- 改分区表 = 破坏原厂启动路径,**不要动** `partitions` 表。
- app1 为空时不要写入错误 otadata 指向它(会启动失败并回滚,无害但会重启循环)。
- 副控重刷前务必确认 4 MB 备份可用(`restore_firmware.sh esp32`)。
- 原厂固件的 OTA 通道是私有协议(串口/网络包 + `OTA_x` 分区),不建议依赖它做升级。

296
doc/开发规范.md 100644
View File

@ -0,0 +1,296 @@
# 设备端开发规范(开发 / 设计 / 交付)
> 适用 `新项目/knob_os`。目标平台:JC3636K518C_I_W(ESP32-S3R8 / 16MB Flash / 8MB PSRAM / 1.85" 360×360 圆屏 / TF 卡 / 副控 ESP32-U4WDH)。
> 架构速览见 [`../ARCHITECTURE.md`](../ARCHITECTURE.md),OTA 细节见 [`固件更新.md`](固件更新.md),扫码登录见 [`扫码登录.md`](扫码登录.md),截图索引见 [`界面一览.md`](界面一览.md)。
>
> 本文写"必须怎么做"。规范与代码冲突时,以这里为准并顺手修代码或改本文——不要让两者长期不一致。
> 最后核对:2026-11-06(固件 0.1.5)
---
## 1. 分层与依赖
```
apps/ 业务应用(时钟/相册/音乐/星盘/我的/天气/设置) 只关心"这个应用做什么"
ui/ 主题 + 圆环控件 + 导航外壳 + 模态 只关心"长什么样、怎么进怎么出"
core/ App 基类 / 注册表 / 表驱动设置 只关心"框架规则"
hal/ 屏幕 / 触摸 / 编码器 / SD / 电池 / 触感 只关心"硬件怎么用"
services/ WiFi / 平台 / 天气 / 星盘 / 媒体同步 / OTA / 串口 后台能力,不碰 UI
config/ 引脚、常量、品牌与版本
assets/ 自动生成的字体与图标(不要手改)
```
**依赖方向单向**:`apps → ui → core → hal`;`services` 可被 `apps` 与 `ui` 调用,但**绝不反向依赖 `ui`**。
反过来就会出现"服务里弹 toast"这种耦合,网络层就没法在无屏状态下单独跑。
不允许的写法:
- `hal/` 里 include 任何 `ui/`、`apps/` 头文件;
- `services/` 里直接 `lv_*`(需要反馈就回传状态,由 UI 层决定怎么显示);
- `apps/` 里直接操作 WiFi/TLS(一律走 `svc::`)。
---
## 2. 文件与命名
| 位置 | 放什么 | 命名 |
|---|---|---|
| `src/apps/XxxApp.h/.cpp` | 一个应用,继承 `App` | 类名 `XxxApp`,全局实例 `apps::xxxApp` |
| `src/ui/` | 可复用控件、模态(BindScreen/NetWizard/QrScreen/OtaPanel/SyncPrompt/ServerEditor)、Shell/Launcher/Splash | 库式小写函数(`ui::toast`、`ui::bottomPanel`)或 `class Xxx` |
| `src/core/` | 框架(App/AppManager/Settings/Log) | |
| `src/hal/` | 硬件封装 | 函数式 `hal::xxx()` |
| `src/services/` | 后台服务 | 单例 `svc::xxx`,`begin()` + `loop()` 两段式 |
| `src/config/` | `BoardPins.h`(引脚唯一真源)、`AppConfig.h`(品牌/版本/常量) | |
| `src/assets/` | `lv_font_*.c`、`icons.c` | 由 `tools/` 生成,禁止手编辑 |
| `slave_audio/` | 副控独立 sketch | 与主控共用串口帧格式 |
| `tools/` | 生成与调试脚本 | |
约定:
- 命名空间:`apps::` / `ui::` / `hal::` / `svc::`;匿名命名空间放文件内静态函数。
- 成员变量前缀 `_`(`_list`、`_otaVal`),常量大写(`SCREEN_W`、`RING_OUTER`)。
- 每个文件顶部写"这个文件解决什么问题",注释解释**为什么**这么写,不复述代码。
- 大对象(JPEG 解码器、缓冲)必须 `static` 或堆分配:Arduino `loopTask` 只有 8KB 栈,主循环另起 20KB 任务。
---
## 3. 新增一个应用
```cpp
class MyApp : public App {
public:
const AppMeta& meta() const override {
static AppMeta m = {"myapp", "我的", LV_SYMBOL_STAR, &icon_myapp, 0xFF7A45, true, false};
return m; // id, 名称, 符号, 图标, 强调色, 有设置, 需绑定
}
void build(lv_obj_t* root) override; // 只调一次,建全部对象
void onEnter() override; // 每次进入:起定时器、拉数据
void onExit() override; // 每次离开:停定时器
void onTick(uint32_t nowMs) override; // ~20-30Hz,只做轻量刷新
bool onKnob(int32_t diff) override; // 返回 true = 已消费
void buildAppSettings(lv_obj_t* list) override; // 下拉设置层的内容
};
static MyApp myApp;
```
接入清单:
1. `knob_os.ino` 里 `appMgr.add(&apps::myApp);` —— **顺序即菜单顺序**,菜单按应用数量均分圆周;
2. 需要图标:在 `tools/gen_icons.py` 里加一条,跑一遍生成 `assets/icons.c`;
3. 需要设置项:在 `src/core/Settings.cpp` 的表里加一行(见 §4);
4. 有中文文案:跑 `bash tools/gen_font.sh`(`build.sh` 会先 `--check`,漏字会报警);
5. 要更新 `doc/界面一览.md` 的截图与说明。
`AppMeta` 的 `needBind=true` 时,未绑定进入会自动拉起绑定页(相册/音乐这样)。
---
## 4. 设置项规范(表驱动)
`src/core/Settings.cpp` 的一张表是**唯一真源**:设备设置页、应用设置层、配网页 `/api/settings`、NVS 持久化都读它。
```cpp
{"cle.work", "专注时长", "时钟", SType::INT, 25, 1, 90, 1, "min", nullptr, nullptr},
// key 名称 组 类型 默认 min max step 单位 枚举项 初始文本
```
规则:
- **key 用 `组.项` 三段内**,NVS 键上限 15 字符(`cle.work` = 8);
- 组名决定归属:`系统`/`时钟`/`相册`/`音乐`/`网络`/`账号`;设备设置页按组渲染,应用设置层按组过滤;
- `TEXT` 类型只在配网页改(圆屏没键盘),设备端展示只读文本;
- 新增 `INT`/`ENUM`/`BOOL` 自动获得滑块/选择器/开关,**不要手写控件**;
- 值的范围必须在表里给全(`min/max/step`),不要指望调用方自己夹;
- 改表就改了 NVS 布局:删 key 不会清旧值,改名等于新增(旧值成为孤儿,不影响运行);
- 只放"用户会调"的项。调试开关放编译期常量,不进设置表。
---
## 5. UI 设计规范
### 5.1 几何(全部以屏幕中心为原点,半径 180)
| 常量 | 值 | 用途 |
|---|---|---|
| `SCREEN_R` | 180 | 圆屏半径,改屏幕只改这一处 |
| `ARC_SIZE` / `SECTOR_W` | 358 / 115 | 一级菜单扇区:所在圆直径 358,径向厚度 115 |
| `ICON_R` / `ICON_SIZE` | 124 / 44 | 扇区图标中心半径与位图原始尺寸(**1:1 显示,不缩放**) |
| `HUB_R` | 56 | 中心信息盘(一级菜单唯一的文字:应用名 + `序号/总数`) |
| `RING_OUTER` / `RING_ICON` / `RING_CONTENT` | 168 / 112 / 104 | 外圈弧 / 图标环 / 内容安全区 |
| 底部信息面板 `bottomPanel()` | 360×96 | 常驻信息(歌名、页码、天气详情) |
| `toast()` | 360×44 | 唯一的浮层文字,自动消失 |
| 卡片安全尺寸 | 300×204 / 316×184(圆角 28) | 横向铺满的内容必须收进卡片,否则底部行被圆边切掉 |
内容控制在半径 150 内:越靠上下可用宽度越窄(y=±120 时只剩 ±134)。
### 5.2 视觉
| 规则 | 具体 |
|---|---|
| **只有一支强调色** | 环、按钮、选中态、成功态全用 `theme::accent()`;不按应用/天气分配第二种颜色 |
| **深色底** | 屏幕边缘融进外壳,视觉上"没有边框";不做浅色主题 |
| **环是有含义的** | 秒进度、倒计时、音量、湿度、播放进度才配外圈弧;无标签的装饰弧一律删(用户会读成"正在加载") |
| **主按钮满色** | `pillAction(Primary)`/`solidAction()` = 主色实心 + 白字;次要操作用 `Ghost` 线框 |
| **提示只在有反馈时出现** | 全屏唯一浮层是 `ui::toast()`;没有常驻说明、没有"下拉有设置"的小箭头 |
| **同步 = 扫圈 + 一句话** | `ringNew()` 平时隐藏 → `ringWorking()` 扫满 → `ringDone()` 淡出 + toast「已同步」 |
| **写卡类同步必须可感知** | 盖进度层(半透明 + 进度条 + `3/10 歌名`),期间屏蔽旋钮与点击;SD 锁只在单次 open/write/close 内持有 |
| **遮罩不吃点击** | 除二维码浮层外,浮层一律 `lv_obj_clear_flag(CLICKABLE)`;需要"点任意处关闭"的才显式可点 |
| **表盘不显示昵称** | 昵称属于「我的」页,压在时间下面会被误读成时区 |
| **图片页的进度环放黑边** | 相册的环压在照片上会被当成瑕疵 |
### 5.3 设置界面
- 全屏铺满,**不用卡片**;同一时刻只有一行在屏幕正中心(放大 + 主色药丸),前后各 2 行按距离缩小、变淡、渐隐;
- 旋钮上下切换,"旋到中心即选中"——**没有"先选中再调值"两态**;
- `INT` 滑轨行旋钮只负责把它转到中心,调值只能手指拖;
- 容器**不要**用 `ui::listColumn()`(轮盘布局与 LVGL 流式布局互斥),用 `ui::settingNavAttach()` 绑定;
- 分组标题不参与选中(进页面高亮第一条真设置)。
---
## 6. 交互规范
**旋钮 = 浏览;没有可浏览的东西时才用来刷新。点击 = 这一页的主操作。上滑 = 退出;下拉 = 设置(没有设置就什么也不发生);长按 = 回桌面。**
| 场景 | 旋钮 | 点击 | 上滑 | 下拉 | 长按 |
|---|---|---|---|---|---|
| 一级菜单 | 换扇区 | 进入应用 | — | 取消返回 | 回桌面 |
| 应用内 | 交给应用(翻页/切歌/调值) | 应用主操作 | 打开一级菜单 | 打开设置层 | 回桌面 |
| 设置层 | 转到中心 | 执行/切值 | 关闭 | 关闭 | 回桌面 |
| 「我的」页 | 拉一次资料 | —(点击不再出码) | 打开一级菜单 | 开二维码(无设置层) | 开/关二维码(0.1.8:点击改长按,页底 1/3 遮罩层写着这行提示) |
| 绑定页 | 吞掉 | 换一张码 | 吞掉 | 收起(先不绑) | — |
| 二维码浮层 | 吞掉 | 关闭 | — | — | — |
一致性细则:
- **顶部信息行同一基线**(时钟日期 / 天气城市 / 星盘月份 y≈68–72);底部辅助行统一 `BOTTOM_MID -64`;
- **未绑定三处同话术**:统一走 `PlatformService::stateHint()`(等待网络连接… / 正在连接服务端… / 设备未绑定 · 请先完成配对),别再各写各的;
- **不要长按绑开发动作**:出汗误压一次像出 bug(音乐原来的"长按重扫"已删);
- 应用要自己吃掉纵向手势时,重写 `allowShellSwipe()` 返回 `false`,否则用户滑一下列表就"退出"了。
---
## 7. 字体与图标
字体是**源码字面量子集**:`tools/collect_chars.py` 扫字符串字面量 → `lv_font_conv` 生成 6 个 `.c`:
| 字体 | 用途 |
|---|---|
| `FONT_TEXT` / `FONT_TITLE`(cjk 16/24) | 自己写的文案(源码里有的字) |
| `FONT_MEDIA` / `FONT_MEDIA_24`(media 16/24,2500 常用字) | **任何外部文本**:歌名、文件名、城市、天气描述、运势、昵称 |
| `lv_font_num_64` | 时钟等宽数字(防跳字) |
| `lv_font_zodiac_26` | ♈~♓ 十二个黄道符号 |
规则:
1. 自己写的文案改完就 `bash tools/gen_font.sh`;`build.sh` 的 `--check` 会在编译前拦漏字;
2. **外部文本必须用 `FONT_MEDIA` 且过 `ui::fitFont()`** —— 它逐码位查字形,没有就跳过(不换成 `?`);
3. 别混用:`FONT_TEXT` 连"东""阴"都没有,用错字体 `fitFont` 也救不了;
4. 标点整段带上(`0x2000–0x206F` / `0x3000–0x303F` / `0xFF01–0xFF5E`),否则歌名里的《》是空心方块;
5. 图标用 `tools/gen_icons.py` 按 8 倍超采样生成 44px TRUE_COLOR_ALPHA 位图,**不缩放**(`transform_zoom` 对这类位图不渲染);
6. 新增中文文案后忘了生成字体是最常见的"方框"来源,先查这里。
---
## 8. 网络与后台任务
- 所有网络在 `services/` 的后台任务里跑:单飞一个任务(如 `pf_http`),结果写静态结构,主线程在 `loop()` 里合并;**UI 线程不碰网络**;
- NVS 写入与 LVGL 操作一律在主线程;
- 401 = 设备被解绑/停用 → 清 token、置未绑定标记,由 UI 决定是否拉起绑定页;不要在服务里弹提示;
- 时间与时区一次拿全(`/device/v1/ping` 或 `pair/code` 返回带偏移的 ISO 时间),`settimeofday()` + 写 `TZ` 与 `sys.tz`;
- 重试要有上限与退避,失败给"原因"而不是静默;
- 服务端地址 `net.server` 只在配网页改;设备端只读展示。
---
## 9. 串口调试通道(115200)
固件内置一条命令通道(`services/RemoteDebug.cpp`),主机端脚本靠它做自动化:
| 键 | 作用 |
|---|---|
| `1`–`8` | 直接切到第 N 个应用(顺序 = 注册顺序:时钟/相册/音乐/星盘/我的/天气/设置) |
| `u` / `d` / `c` | 开一级菜单 / 开设置层 / 全部关闭 |
| `+` / `-` | 凭空拧一格旋钮 |
| `v` / `x` | 重播启动动画 / 关掉它 |
| `s` | 截一帧(`SHOT` 头 + RGB565 像素,高字节在前) |
| `g` / `S` | 打开配网向导 / 服务端地址编辑器 |
| `[` / `]` | 配网向导翻页 |
| `W ssid,pass` / `U http://host:port` | 下发 WiFi 凭据 / 服务端地址(写 NVS,调试用) |
| `A` / `M` | 强制开热点 / 用 NVS 里的账号回 STA |
| `N` / `K` | 打印网络状态 / 扫描周边 WiFi |
| `Q` | 开关扫码浮层(无触摸时验证) |
| `Y` | 强制同步媒体(等于点「同步」) |
| `m` / `p` / `D` | 列曲库 / 播放暂停 / 导出唱片画布 |
| `F <path> <bytes>` | 收文件到 TF 卡(主机端 `pushfile.py` 用) |
| `V` / `C` / `I` / `O url` / `R` | 槽位与升级状态 / 检查更新 / 安装已知版本 / 按 URL 直接升级 / 手动回滚 |
| `L` | 导出设置列表每一行的坐标(排布局问题) |
| `?` | 当前应用、菜单/设置层状态、剩余堆 |
> `W`/`U` 存在的理由:macOS 14+ 没有"定位服务"授权时主机连不上设备热点(`-3900`),串口是唯一不依赖点屏幕的配置通道;产品路径仍然是配网页。
截图闭环:`s` 出一帧 → 主机端脚本存 PNG → 与 `doc/shots/` 对比。像素是**高字节在前**,按小端读会得到花屏。
---
## 10. 交付规范
### 10.1 编译与烧录
```bash
cd 01-开发工作区/新项目/knob_os
bash build.sh # 字体检查 → 编译 → build/knob_os.ino.bin
bash build.sh clean # 改了 lv_conf.h / 库版本才需要(旧缓存会被挪成 .broken-*)
bash ../../工具脚本/flash_app.sh build/knob_os.ino.bin /dev/cu.usbmodemXXXX app0|app1
python3 ../../工具脚本/bootctl.py set app1 # 手动切槽(一般由 OTA 自己切)
```
- `flash_app.sh` 写**分区表 + 目标槽 + otadata**,不动 `nvs(0x9000)`,所以烧完不用重新配网/绑定;
- 槽偏移从 `partitions.csv` 现读,不写死;写入前校验体积(7.5MB)与镜像头 `0xE9`;
- 环境固定:`arduino-cli 1.5.1` + `esp32:esp32@3.0.7`,库版本见 `../README.md`;
- 副控固件在 `slave_audio/`,单独烧(`tools/build_slave.sh` / `tools/flash_slave.sh`,走 CH340C,需反插 Type-C)。
### 10.2 版本与发版
1. **改 `src/config/AppConfig.h` 的 `BRAND_VERSION`**(不改就会被反复推同一版);
2. `bash ../../工具脚本/release.sh --notes "改了什么"`:读版本号 → 编译 → 校验镜像头 → 登录 → 同名版本先删 → 上传并发布;
3. 常用开关:`--no-publish`(先传不发)、`--beta`、`--skip-build`、`--server <url>`;
4. 管理端「批量升级 / 单台指定」只在需要"钉版本/回滚"时用——**发布本身就够设备自主升级**。
### 10.3 交付检查单
一次固件改动完成,需要同时满足:
1. `bash build.sh` 通过(含字体 `--check`),产物首字节 `0xE9`;
2. 新增/修改的中文文案已跑 `tools/gen_font.sh`;新图标已跑 `tools/gen_icons.py`;
3. 串口 `s` 截图确认改动页面:480×480 内无裁切、无方块字、无残留提示;
4. 旋钮 / 点击 / 上滑 / 下拉 四类手势在该页都符合 §6 的映射,没有"点了没反应";
5. 涉及网络的:断网、401(解绑)两种异常下不卡死、不重启;
6. 涉及 flash/TF 的:断电重来能恢复(写 `.part`/临时文件再改名);
7. 版本号已改,`doc/` 里相关说明与 `doc/shots/` 截图同步;
8. 副控相关改动,必须主副控一起烧并在真机听声验证(见 §11 第 1 条)。
---
## 11. 已知坑(改之前先看)
| 现象 | 原因 | 正确做法 |
|---|---|---|
| 设置列表糊成一团 | LVGL 8 的 `lv_obj` 默认没有布局算法,子对象全在 (0,0) | 列表容器用 `ui::listColumn()`;设置层用 `settingNavAttach()`(它自己算位置,不用 listColumn) |
| 图标整块消失 | `transform_zoom` 对 `TRUE_COLOR_ALPHA` 位图不渲染 | 按目标尺寸生成位图,1:1 显示,动画只做透明度 |
| 照片颜色变粉紫蓝绿 | 本工程 `LV_COLOR_16_SWAP=1`(高字节在前) | `jpeg.setPixelType(RGB565_BIG_ENDIAN)`,且必须在 `openRAM()` **之后** |
| 一进相册就重启 | `JPEGDEC` 十几 KB,`loopTask` 栈只有 8KB | 解码器等大对象 `static`,主循环另起 20KB 任务 |
| 中文显示成方框 | 字体是子集,新增文案没重跑 `gen_font.sh` | 跑 `tools/gen_font.sh`,`build.sh` 会 `--check` |
| 歌名/城市出方块 | 外部文本用了 `FONT_TEXT` | 用 `FONT_MEDIA` + `ui::fitFont()` |
| 复用 `lv_img_dsc_t` 显示旧图 | LVGL 有图片缓存 | 换数据前 `lv_img_cache_invalidate_src(&dsc)` |
| 屏上出现 66 FPS 浮层 | `LV_USE_PERF_MONITOR 1` | 关掉 |
| 黑胶盘突兀亮斑 | `atan2f` 返回 [-180,180],`360-dd` 变负导致系数溢出 | 角度先归一到 [0,360),系数再 clamp |
| 串口传文件报 `PUT_ERR header` | 头是"路径 大小",路径里可能含空格 | 按**最后一个**空格切分 |
| 时钟外圈高亮环不动 | LVGL 8.4 `lv_arc_set_angles()` 末尾按内部 `value` 反算角度 | 进度走 `lv_arc_set_range()` + `lv_arc_set_value()` |
| 设置转到滑轨行"走不动" | 光标态与调值态共用一个 `selected` | 两个状态分开(`selected` / `editing`) |
| 点了配网就重启 | 在点击回调里直接 `WiFi.mode()` 拆掉 STA netif,撞上后台 TLS | 只发请求(`net.requestAp()`),真正切换在 `NetService::loop()`,用 `AP_STA` 叠加 |
| 同步 10MB 的音乐时整机卡死 | 整段下载持有 SD 锁 | 锁只在单次 open / 4KB write / close 内持有 |
| `display` 缓冲区吃掉 51KB 导致 20KB 任务栈申请失败 | `LV_BUF_ROWS 72` | 保持 `LV_BUF_ROWS 40`(360×40×2 ≈ 28KB) |
| `LONG_DOT` 把下一行压住 | LVGL 8 的 `LONG_DOT` 先换行再加省略号 | 给标签 `lv_obj_set_height(…, 20)` 限死一行 |
| 副控出声失败 | 主控没有 I2S 接 DAC;副控需重刷 `slave_audio` 且 `XSMT(GPIO32)` 拉高 | 先 `tools/flash_slave.sh`(含原厂 4MB 备份),串口看副控状态帧 |

139
doc/扫码登录.md 100644
View File

@ -0,0 +1,139 @@
# 扫码登录(设备 → Web 个人页)
在设备「我的」页**长按**屏幕(下滑也可以),屏幕上会出现一张二维码。手机扫码即可**免密登录**到
Web 端的个人页面,看到的是这台设备绑定的那个账号。
要解决的问题很具体:桌面设备上没有键盘,用户想改昵称/生日/常住地,得先在
手机浏览器里敲一遍邮箱和密码——而账号本来就已经在这台设备上了。
## 1. 交互
```
「我的」页(屏幕下方 1/3 遮罩层写着「长按生成管理二维码」)
├── 转动旋钮 → 拉一次资料(反馈环扫一圈 + 「已同步」)
└── 长按屏幕 → 二维码浮层开/关(下拉也能开)
├── 有码时点任意处 → 收起
└── 过期/出错时点 → 重新取票
```
> 0.1.8 起手势从「点击」改成「长按」:点击太容易误触(旋钮旁边落一次指就弹码),
> 而且和「转动 = 同步」这个手势挤在一起。长按 400ms 才出码。
- 二维码有效期 **5 分钟**,过期后码自动撤掉,卡片上写「二维码已过期 · 点击刷新」。
- 未绑定设备时长按只提示一句「先在配网页绑定设备」,不打开浮层。
- **首次取票会自动重试 3 次**(0.1.8):设备平时在 WiFi modem sleep 里,唤醒后第一条 TCP
连接很容易失败,旧代码一次不成就把「连不上服务端」顶到屏上。现在 `status<=0` 与 5xx
都算可重试,日志里有 `[QR] ticket attempt 1/3 failed`。二维码图像本身是设备本地
`QrCode.cpp` 编的(服务端只给票据 URL)。
- 二维码是**白底黑块**,不跟主题走:深色底上扫码器基本识别不出来。
- 浮层里不放提示带:屏幕上只有二维码本身,扫码时画面最干净(224px 正方形 + 10px 静区,居中,离圆边还有余量)。
## 2. 为什么是「一次性票据」而不是把 token 编进二维码
设备上那张码如果直接带长期 token,等于把账号凭证贴在屏幕上——被拍一张照片
就等于凭证泄露,而且没法回收。
所以走一次性票据:
| 环节 | 做法 |
|---|---|
| 设备取票 | `POST /device/v1/web-login/ticket`,带设备 Bearer;服务端生成 10 位码(大写字母+数字,去掉 0/O/1/I),写 Redis `wlogin:<code>`,TTL 300s |
| 手机换会话 | `POST /api/auth/qr-login {code}`,**取出即删**,然后按正常登录签一个会话 token |
| 同设备换码 | 发新码时删掉这台设备上一张码(`wlogin:dev:<device_id>` 存最新一张) |
结果:
- 码只能用一次,扫完即废;
- 屏幕上换过码,之前那张(哪怕被截图拍下)立刻失效;
- 泄露的最坏情况是「5 分钟内被人抢先扫一次」,而用户会立刻在设备上重开一张。
## 3. 接口
### 3.1 取票(设备端)
```
POST /device/v1/web-login/ticket
Authorization: Bearer <device token>
```
```json
{"code": "XRUSSFD7HZ", "url": "http://192.168.2.147:5173/qr?t=XRUSSFD7HZ", "expires_in": 300}
```
设备未绑定账号 → `409`;缺/错 token → `401`。
`url` 里的 Web 基地址按这个顺序取(`device_v1.py::_web_base`):
1. `.env` 的 `WEB_BASE_URL`(只有 Web 与 API 真不同域时才需要配);
2. 否则用**设备这次请求的 Host**——设备里配的「服务端地址」就是它,同域部署天然正确;
开发期直连 `:8000` 时会自动换成 `:5173`(`DEV_API_PORT` → `DEV_WEB_PORT`)。
原来是"管理端设置里填 Web 访问地址",已经去掉:设备请求的 Host 本来就是要拼的那个地址,
再配一份只会出现"配了没生效/配错域名"的问题。
### 3.2 换会话(Web 端)
```
POST /api/auth/qr-login
{"code": "XRUSSFD7HZ"}
```
成功返回与密码登录完全一样的结构(`token` + `user`);失败 `401`
(「二维码已失效,请在设备上重新打开」)。
## 4. Web 端落地页
路由 `/qr?t=<code>`(`web/src/pages/QrLogin.tsx`):
1. 读票据 → `api.qrLogin(code)`;
2. 成功:`auth.save(token, user)` → 600ms 后跳 `/`(个人页);
3. 失败:给「二维码不可用」+「用密码登录」的出口。
**注意**:React StrictMode 下 effect 会跑两遍,第二遍会拿着一张已经用掉的票
报 401,把成功状态覆盖成失败。所以用 `useRef` 保证只换一次。
## 5. 设备端实现
| 文件 | 作用 |
|---|---|
| `src/ui/QrCode.h/.cpp` | 自研二维码编码器:字节模式 + 纠错 M + 版本 1..7 |
| `src/ui/QrScreen.h/.cpp` | 浮层:取票(后台任务)、画布渲染、过期处理 |
| `src/apps/UserApp.cpp` | `onGesture(SwipeDown)` 打开浮层 |
### 5.1 为什么自己写编码器
设备上没有可用的二维码库,而屏上的码是**运行时才有**的(票据每次不同),
不能预先画成图片。需求范围很窄——几十字节的 URL、黑白模块矩阵——所以只实现
一条路径:字节模式、纠错 M、版本 1..7。这七档的纠错块都是等长的
(1/1/1/2/2/4/4 块),省掉混合块交织的分支,整个实现只有几百行。
**正确性验证**(`tools/qr_dump.cpp` + `tools/qr_verify.py`):
把自己的矩阵和 python `qrcode` 在**同版本、同掩码**下逐模块比对,
覆盖 v1/v3/v4/v5/v6/v7 全部一致;再把真机截图用 `jsQR` 解回来,
确认屏幕上的码扫得出原始 URL。
```bash
g++ -O2 -std=c++17 -o build/qr_dump tools/qr_dump.cpp src/ui/QrCode.cpp
python3 tools/qr_verify.py # 需要 pip install qrcode
```
### 5.2 渲染
- 画布 224×224(`LV_IMG_CF_TRUE_COLOR`),buffer 走 PSRAM,没有 PSRAM 时退回内部堆;
- 模块大小 `scale = 224 / side`(v3 是 6px/模块,v7 是 4px);
- 取票在独立的 FreeRTOS 任务里跑,结果写静态结构由 `loop()` 合并 ——
和 `OtaService` 同一套路,UI 线程不碰网络。
### 5.3 串口调试
| 命令 | 作用 |
|---|---|
| `Q` | 开关扫码浮层(无触摸时验证用) |
## 6. 已知限制
1. **Web 基地址跟着请求 Host 走**:局域网调试时由设备请求的 Host 推出 `:5173`;
生产部署若 Web 与 API 不同域,在 `.env` 里设 `WEB_BASE_URL=<对外域名>`。
设备里的「服务端地址」要指向最终部署的地址,二维码才打得开。
2. 票据 5 分钟内有效,过期需在设备上重开(点一下卡片即可)。
3. 扫码只完成「登录」,不做「授权某台设备」——设备与账号的绑定关系仍走
配对码流程(`/bind`)。

152
doc/界面一览.md 100644
View File

@ -0,0 +1,152 @@
# 界面一览
所有设备截图都是**实机**截的(串口 `s` 命令,见 [`开发规范.md`](开发规范.md) §9),不是效果图。
截图对应的设计规则(几何、强调色、底部面板、字体、手势映射)统一写在 [`开发规范.md`](开发规范.md) §5–§7,本文只做画面索引。
> 目录里还有一批历史截图(迭代过程),已移到 `shots/archive/`,不要引用。
> 最后核对:2026-11-11(固件 0.1.8)
---
## 设备
| 文件 | 画面 | 要点 |
|---|---|---|
| `shots/01-splash.png` | 启动动画 | 圆环走真实初始化进度(亮屏→挂载存储→连网→加载应用),完成后向外扩散淡出,约 2.5s |
| `shots/118-clock.png` | 桌面 · 时钟 | 大号等宽数字 + 秒进度环;顶部一行日期。没有 RTC,未对时前显示 `--:--`,不做假数据 |
| `shots/12-clock-set.png` | 时钟 · 番茄钟设定 | 时钟页直接拧旋钮进设定态,分钟数实时跟随,点击开始 |
| `shots/80-sheet-v7.png` | 时钟 · 设置层 | 应用内下拉升起的全屏设置层:中心聚焦轮盘,只有中心行放大实色,前后各 2 行缩小变淡;滑轨只认手指拖 |
| `shots/124-launcher.png` | 一级菜单 | 7 个扇区均分(时钟/相册/音乐/星盘/我的/天气/设置),**扇区里只有 44px 图标**,选中扇区染强调色;中心盘是唯一文字:应用名 + `1 / 7` |
| `shots/119-gallery.png` | 相册 | TF 卡 `/pic` 的 JPEG,圆形裁切铺满;顶部胶囊是文件名、底部胶囊是 `2 / 3`;不画外圈装饰弧 |
| `shots/120-music.png` | 音乐 · 唱片机 | ID3 标题/歌手/封面直接上屏;播放时黑胶(含封面)旋转;外圈弧 = 播放进度;点击盘心播放/暂停 |
| `shots/06b-music-nocover.png` | 音乐 · 无封面 | 无内嵌封面时退回黑胶 + 强调色厂标,不留空白 |
| `shots/87-music-sync.png` | 音乐 · 同步中 | 半透明遮罩 + 「正在同步音乐 / 3/10 歌名」+ 进度条,期间屏蔽旋钮与点击;写卡全程不碰 LVGL |
| `shots/97-music-mode.png` | 音乐 · 设置层 | 音量滑轨 + 播放模式(顺序/随机,`mus.mode`) |
| `shots/117-weather-fixed.png` | 天气 | 城市 + 图标 + 温度大字 + 底部信息面板(`多云 · 体感 18°` / `湿度 78% · 东南风 2 级`);温度下那行用 24px 媒体字体,风向含服务端文本、已过 `fitFont`;旋钮更新时扫圈 + 一句「已同步」 |
| `shots/81-weather-nosettings.png` | 天气 · 下拉 | 天气**没有设置项**(城市/单位由账号与接口决定),下拉不发生任何事 |
| `shots/150-user-hint.png` | 我的 | 昵称 → 太阳星座 → 常住地 → 生日 · 时区;底部 1/3 遮罩层写「长按生成管理二维码」;旋钮 = 拉一次资料,长按 = 开/关二维码(二维码打开时这层自动收起,否则会透在码下面) |
| `shots/116-astro-fixed.png` | 星盘 | 顶部 `2026 年 11 月`,两行「黄道符号 + 太阳 射手座」(24px)/「火 · 3.4°」;符号来自 `lv_font_zodiac_26`(♈~♓),不是图片也不是方块。实测踩过:24px 档字表只收「源码字面量 ∪ 服务端词表」,而服务端词表剔掉了常用字,`太阳 射手座` 会显示成 `太阳 手座` —— 已用 `tools/vocab24.txt` 补字 |
| `shots/121-astro-fortune.png` | 星盘 · 运势页 | 旋钮切到本月运势(可滚动),月份单独一行;正文来自服务端,已过 `fitFont` |
| `shots/123-settings.png` | 设置 | 分组:网络(WiFi/IP/服务端地址/配网向导)· 固件(版本/固件更新)· 系统 · 账号 · 关于;全屏轮盘,分组标题不参与选中 |
| `shots/110-wizard.png` | 配网向导 | 单页:当前 SSID / IP、热点名与密码、网址、「重新配网」;提交后按钮变「完成」,一点就关热点退出,不重启 |
| `shots/82-qr-final.png` | 我的 · 扫码登录 | 白底二维码落屏幕中心、10px 静区,浮层无提示条;票据 5 分钟、一码一用、换码即作废旧码(0.1.8 实机新图见 `shots/149-qr.png`) |
| `shots/148-bind-clean.png` | 绑定页(0.1.8) | 只剩三行:标题 / 六位码 / 倒计时。码下面那三行小字(服务端地址 · 设备号 / 点击换码 / 在网页端输入此码)全部删掉,出错时倒计时那行改成原因 |
## 配网页(`http://nexbuddy.local`,未配网 `192.168.4.1`)
| 文件 | 画面 |
|---|---|
| `shots/132-portal-0.1.7.png` | 概览:电量/温度/TF 卡/运行时长 + 网络 + 配网 + 服务端地址(含 `/healthz` 测试)+ 设备信息(底部**完成重启**) |
| `shots/web-2-settings.png` | 设置:配置项按分组渲染成滑块/开关/下拉/输入框,改完即写 NVS;维护区只有「恢复默认 / 重启」 |
> 网页只有「概览 / 设置」两个页签(文件页签已去掉,TF 卡用主机端脚本管理)。
> 配网点「连接」后自动弹窗:成功给新地址(热点留 60 秒供手机读取),失败给原因。
> **改服务端地址不再被冲掉**:`/api/status` 每 5 秒轮询一次,旧代码无条件把返回值写回
> 输入框,用户打字打到一半就被回滚成旧地址。现在只在非编辑态回填(`#srv-edit` 隐藏时)。
> 保存后会弹窗提供「立即重启」;收尾按钮是设备卡片底部的「**完成重启**」——整行大按钮、
> 不配说明文字(0.1.7 起从独立的「完成」卡片合并进设备卡片,不再单占一个面板)。
>
> **`confirm()` 在手机配网窗口里会被静默吞掉**(0.1.7 修):手机连热点时弹出的是系统
> captive portal 小浏览器,iOS/Android 会屏蔽原生 `alert/confirm`,点了按钮看着"完全没反应"。
> 现在所有确认框走页面自己的 `popup()`,重启流程改为:点「完成重启」→ 自绘确认框 →
> POST `/api/reboot` → 弹「正在重启」。
## 绑定状态是"问出来"的(0.1.6 起)
旧逻辑只看本地有没有 token:`!bound()` 就直接在屏上写「未绑定」。
服务端地址填错、服务端没起来时,这句话会一直挂着——**其实根本没问到服务端**,
用户会以为设备掉绑定或者坏了。
现在的三态(`PlatformService::serverOk()`:最近一次请求是否拿到 HTTP 应答,
地址一改就自动失效):
| 情形 | 屏上 |
|---|---|
| 没联网 | 等待网络连接… |
| 联网但服务端不可达 | 正在连接服务端…(**不弹绑定页,应用正常进入**) |
| 服务端确认没绑定 | 设备未绑定 · 请先完成配对(`needBind` 的模块弹绑定页) |
| 已绑定 | 正常显示资料;若服务端回 401 当场解绑 |
未绑定时设备本来不会向服务端发任何请求,所以加了一个 `/healthz` 探活(15 秒一次、不带 token),
否则"服务端可达"这个结论永远拿不到,界面只能一直停在"正在连接服务端"。
## 统一空态与取码自愈(0.1.7 起)
**1. 未绑定提示只有一套文案。** 以前「我的」写「未绑定 · 扫码进入网页」、星盘写「扫码进入网页完成绑定」、
天气写「未绑定」,同一个状态三种说法。现在统一走 `PlatformService::stateHint()`:
| `net.online()` | `serverOk()` | `bound()` | 屏上(所有模块一致) |
|---|---|---|---|
| false | — | — | `等待网络连接…` |
| true | false | — | `正在连接服务端…` |
| true | true | false | `设备未绑定 · 请先完成配对` |
**2. 强制绑定的范围**(`AppMeta.needBind`):只有**设置**和**时钟**不要求绑定;
相册、音乐、星盘、我的、天气都是 `needBind=true`,未绑定时进模块直接拉起绑定页
(下滑可"先不绑",此时页内显示上表文案)。0.1.7 把「星盘」「我的」从 false 改成了 true。
**3. 取码不再卡在「正在取码…」。** 两个原因,都修了:
- `dispatch()` 是单飞(同一时刻只有一个后台请求),撞上在飞的探活/资料请求时会**静默丢弃**
取码请求;而 `startPairing()` 已经把状态置成 `Asking` —— 没人补发,界面永远停在取码,
点屏幕也被 `Asking` 挡回去。现在 `dispatch()` 返回是否入队,`loop()` 里两条兜底:
`Asking` 超过 3 秒且没有请求在飞 → 重发;`Failed` 超过 8 秒 → 自动重新取码
(409「服务端认为已绑定」是致命错误,不重试,提示先去网页解绑)。
- 绑定页对 `Failed` 也显示「正在取码…」,看起来像卡死。0.1.7 失败态改说「点击重试」,
0.1.8 起干脆不写提示:正常只有倒计时,出错才在同一行写原因。
解绑后的完整链路(已实测):设备下次 `/profile` 收 401 → `unpair()` 清本地 token →
进任一 `needBind` 模块 → 绑定页自动取到新码,不需要人工点。
## 绑定页只剩一个主角(0.1.8 起)
旧版绑定页在六位码下面压着三行小字:`192.168.x.x:8100 · 设备 BD44`、
`剩 9:21 · 点击换码`、`在网页端输入此码`。一屏五个信息,扫码时反而找不到那六位数,
而且都是常驻说明——和「提示只在有反馈时出现」的原则相反。现在:
| 位置 | 内容 |
|---|---|
| 上缘 | `绑定设备` |
| 中心 | 六位码(FONT_NUM_L,隔一米能读) |
| 码下**唯一一行** | 平时 `剩 9:21`;取码失败时换成原因(如 `取码失败 HTTP 500` / `服务端显示已绑定,请先在网页解绑`) |
| 环 | 倒计时进度 |
手势没变:点屏幕 = 换一张码,下滑 = 先不绑(这两件事不再写在屏上)。
## 我的页:长按出码 + 首次取票自愈(0.1.8 起)
- **手势从「点击」改成「长按」**:点击太容易误触(旋钮旁边一次落指就弹码),
也容易和「转动 = 同步」混在一起。现在长按 400ms 才出码;下滑仍然能开(老习惯)。
- **页底 1/3 遮罩信息层**:与时钟专注模式、各模块设置层同一套外观,只写一行
`长按生成管理二维码`。手势变得不直观了,就得有一句话把它说清楚。
- **二维码是谁生成的**:票据 URL 由服务端 `POST /device/v1/web-login/ticket` 生成
(一码一用、5 分钟),二维码图像由设备本地 `QrCode.cpp` 编码上屏——不是服务端出的图。
- **首次取票经常报「连不上服务端」**:设备平时在 WiFi modem sleep 里,唤醒后第一条
TCP 连接很容易直接失败。旧代码一次不成就把错误顶到屏上,用户再点一次就好。
现在 `fetchTask` 自己重试 3 次(350ms 间隔,`status<=0` 与 5xx 都算可重试),
日志里能看到 `[QR] ticket attempt 1/3 failed (status=-1)`。
## 联网兜底(0.1.5 起)
以前连不上路由器时会出两个连锁故障,看起来像"设备坏了":
1. `esp_wifi` 的 `connect` 在**找不到目标 AP 时不会超时**,状态永远停在 `sta is connecting`,
之后任何 `WiFi.begin()` 都被底层拒绝(串口 `E wifi:sta is connecting, return error`);
2. 那个一直重连/扫频的 STA 和 softAP 抢同一个射频,热点信标被挤掉 ——
**扫描偶尔能看到 `nex_buddy`,但任何手机都关联不上**,连配网页都进不去。
现在的做法:
- 每次 `WiFi.begin()` 前先 `WiFi.disconnect(false,false)`,把卡死的状态打断;
- STA 看门狗:15 秒没连上就重连,3 次失败后切**纯 AP**(`WIFI_AP`,不留 STA),
射频全给热点,保证配网页永远能进;
- 纯 AP 期间每 5 分钟试一次 STA(`AP_RETRY_MS`),成功就自动收掉热点回 STA;
- 断开原因进日志:`[NET] sta disconnected, reason=N`。
`201` = 搜不到 AP(2.4G 关了/太远),`15/204/205` = 握手失败(密码变了 / 路由器要求 WPA3);
- 串口 `K` 可以让设备自己扫一遍周边 WiFi(只扫不连,不影响热点),
排查"到底是看不见还是连不上"最直接。
另外 `wx.interval` 之前**没有注册进设置表**,`getI()` 返回 0,天气退化成每个 loop 都请求一次
(串口每 200ms 一条 `[WX]`,等于拿设备刷自家服务端)。已注册该项(默认 30 min,隐藏不出现在界面)。

164
knob_os.ino 100644
View File

@ -0,0 +1,164 @@
// nex_buddy —— 圆环交互固件(自研,烧录在 app1)
//
// 主文件只做四件事:初始化硬件、注册应用与服务、驱动主循环、把启动过程演给人看。
// 分层:hal(硬件)/ core(框架)/ ui(圆环控件与导航)/ apps(业务)/ services(后台能力)
#include <Arduino.h>
#include <lvgl.h>
#include "src/config/AppConfig.h"
#include "src/core/Log.h"
#include "src/core/Settings.h"
#include "src/core/AppManager.h"
#include "src/hal/Display.h"
#include "src/hal/Storage.h"
#include "src/hal/Power.h"
#include "src/hal/Encoder.h"
#include "src/hal/Haptic.h"
#include "src/ui/Theme.h"
#include "src/ui/Shell.h"
#include "src/ui/Splash.h"
#include "src/apps/ClockApp.h"
#include "src/apps/GalleryApp.h"
#include "src/apps/MusicApp.h"
#include "src/apps/AstroApp.h"
#include "src/apps/UserApp.h"
#include "src/apps/WeatherApp.h"
#include "src/apps/SettingsApp.h"
#include "src/services/NetService.h"
#include "src/services/WebPortal.h"
#include "src/services/AstroService.h"
#include "src/services/WeatherService.h"
#include "src/services/PlatformService.h"
#include "src/services/OtaService.h"
#include "src/services/LinkService.h"
#include "src/services/AudioLink.h"
#include "src/services/MediaSync.h"
#include "src/services/RemoteDebug.h"
static void onSettingChanged(const char* key) {
if (strcmp(key, "sys.bright") == 0) {
hal::setBrightness((uint8_t)settings.getI(key));
} else if (strcmp(key, "sys.accent") == 0) {
theme::applyAccent((uint8_t)settings.getI(key));
lv_obj_invalidate(lv_scr_act());
} else if (strcmp(key, "sys.haptic") == 0) {
hal::hapticSetLevel((uint8_t)settings.getI(key));
} else if (strcmp(key, "sys.tz") == 0) {
svc::net.applyTz(); // 改时区立即生效,不用重启
}
}
// 背光从暗到亮,开机第一秒的观感差别很大
static void fadeBacklight(uint8_t target, uint32_t ms) {
uint32_t t0 = millis();
while (millis() - t0 < ms) {
float k = (float)(millis() - t0) / (float)ms;
uint8_t b = (uint8_t)(5 + (target - 5) * k);
hal::setBrightness(b);
lv_timer_handler();
delay(6);
}
hal::setBrightness(target);
}
// 主循环跑在独立任务里,而不是 Arduino 默认的 loop()。
// 原因:默认 loopTask 只给 8KB 栈,图片解码、TLS 握手这类操作会直接爆栈。
// 这里给 20KB,并且只在一个任务里碰 LVGL(LVGL 不是线程安全的)。
static void knobTask(void*) {
for (;;) {
hal::displayLoop();
ui::shell.loop(millis());
svc::link.loop();
svc::audioLink.loop();
svc::net.loop();
svc::platform.loop();
svc::mediaSync.loop(); // TF 卡媒体增量同步:到点自己派任务,不阻塞 UI
svc::astro.loop();
svc::weather.loop();
svc::ota.loop(); // 进度合并 + 到点重启;必须有人每帧推进
svc::webPortal.loop();
svc::remoteDbg.loop();
delay(3);
}
}
void setup() {
Serial.begin(115200);
delay(200);
LOGF("=== %s %s ===", KNOBOS_NAME, KNOBOS_VERSION);
settings.begin();
settings.onChange(onSettingChanged);
// 开机守卫要尽量早:升级后连崩三次固件,就在进任何 UI 之前切回上一个槽。
// 放在 settings.begin() 之后是因为它要读写 NVS。
svc::ota.begin();
// 屏幕初始化内部会调用 lv_init(),必须先于任何 LVGL 样式操作
if (!hal::displayBegin()) {
LOGF("FATAL: display init failed");
while (true) delay(1000);
}
theme::init(); // 依赖 lv_init() 建立的内存池
// ---- 启动动画:先亮屏,再逐步把真实初始化进度画出来 ----
ui::splash.build();
fadeBacklight((uint8_t)settings.getI("sys.bright"), 420);
ui::splash.step(8, "点亮屏幕", 60);
hal::storageBegin(); // 没插卡也继续跑
ui::splash.step(28, "挂载存储", 80);
hal::powerBegin();
hal::hapticBegin();
ui::splash.step(44, "检查电源", 90);
hal::encoderBegin(nullptr);
ui::splash.step(54, "读取旋钮", 70);
// 应用注册顺序 = 主菜单顺序 = 设置里"开机启动"的编号
appMgr.add(&apps::clockApp);
appMgr.add(&apps::galleryApp);
appMgr.add(&apps::musicApp);
appMgr.add(&apps::astroApp);
appMgr.add(&apps::userApp);
appMgr.add(&apps::weatherApp);
appMgr.add(&apps::settingsApp);
ui::splash.step(68, "加载应用", 90);
ui::shell.begin();
ui::splash.step(82, "装配界面", 80);
// 后台服务
svc::link.begin();
svc::audioLink.begin(); // 同一条 UART1:音轨走 921600 推给副控
svc::net.begin();
svc::platform.begin(); // 读 NVS 里的设备 token,决定是否已绑定
ui::splash.step(94, "连接网络", 70);
svc::astro.begin();
svc::weather.begin();
svc::mediaSync.begin(); // 读 TF 本地清单,等绑定+联网后自动增量同步
svc::webPortal.begin();
svc::remoteDbg.begin();
ui::splash.step(100, "准备就绪", 160);
ui::splash.finish();
// 启动自检:相册是最容易"看不见"的一环(屏上看不到就等于没证据),
// 开机把解码链路跑一次并留日志,远程也能判断问题出在扫描还是解码。
apps::galleryApp.diagDecode();
LOGF("boot done, heap=%u psram=%u",
(unsigned)ESP.getFreeHeap(), (unsigned)ESP.getFreePsram());
xTaskCreatePinnedToCore(knobTask, "knobos", 20480, nullptr, 2, nullptr, 1);
}
void loop() {
// 主循环已经交给 knobos 任务,这里只留一个空转,避免两边同时操作 LVGL
delay(1000);
}

703
lv_conf.h 100644
View File

@ -0,0 +1,703 @@
/**
* @file lv_conf.h
* Configuration file for v8.3.0-dev
*/
/*
* Copy this file as `lv_conf.h`
* 1. simply next to the `lvgl` folder
* 2. or any other places and
* - define `LV_CONF_INCLUDE_SIMPLE`
* - add the path as include path
*/
/* clang-format off */
#if 1 /*Set it to "1" to enable content*/
#ifndef LV_CONF_H
#define LV_CONF_H
#include <stdint.h>
/*====================
COLOR SETTINGS
*====================*/
/*Color depth: 1 (1 byte per pixel), 8 (RGB332), 16 (RGB565), 32 (ARGB8888)*/
#define LV_COLOR_DEPTH 16
/*Swap the 2 bytes of RGB565 color. Useful if the display has an 8-bit interface (e.g. SPI)*/
#define LV_COLOR_16_SWAP 1
/*Enable more complex drawing routines to manage screens transparency.
*Can be used if the UI is above another layer, e.g. an OSD menu or video player.
*Requires `LV_COLOR_DEPTH = 32` colors and the screen's `bg_opa` should be set to non LV_OPA_COVER value*/
#define LV_COLOR_SCREEN_TRANSP 0
/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
* 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
#define LV_COLOR_MIX_ROUND_OFS (LV_COLOR_DEPTH == 32 ? 0: 128)
/*Images pixels with this color will not be drawn if they are chroma keyed)*/
#define LV_COLOR_CHROMA_KEY lv_color_hex(0x00ff00) /*pure green*/
/*=========================
MEMORY SETTINGS
*=========================*/
/*1: use custom malloc/free, 0: use the built-in `lv_mem_alloc()` and `lv_mem_free()`*/
#define LV_MEM_CUSTOM 0
#if LV_MEM_CUSTOM == 0
/*Size of the memory available for `lv_mem_alloc()` in bytes (>= 2kB)*/
#define LV_MEM_SIZE (96U * 1024U) /*[bytes]*/
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
#define LV_MEM_ADR 0 /*0: unused*/
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
#if LV_MEM_ADR == 0
//#define LV_MEM_POOL_INCLUDE your_alloc_library /* Uncomment if using an external allocator*/
//#define LV_MEM_POOL_ALLOC your_alloc /* Uncomment if using an external allocator*/
#endif
#else /*LV_MEM_CUSTOM*/
#define LV_MEM_CUSTOM_INCLUDE <stdlib.h> /*Header for the dynamic memory function*/
#define LV_MEM_CUSTOM_ALLOC malloc
#define LV_MEM_CUSTOM_FREE free
#define LV_MEM_CUSTOM_REALLOC realloc
#endif /*LV_MEM_CUSTOM*/
/*Number of the intermediate memory buffer used during rendering and other internal processing mechanisms.
*You will see an error log message if there wasn't enough buffers. */
#define LV_MEM_BUF_MAX_NUM 16
/*Use the standard `memcpy` and `memset` instead of LVGL's own functions. (Might or might not be faster).*/
#define LV_MEMCPY_MEMSET_STD 0
/*====================
HAL SETTINGS
*====================*/
/*Default display refresh period. LVG will redraw changed areas with this period time*/
#define LV_DISP_DEF_REFR_PERIOD 15 /*[ms]*/ //15
/*Input device read period in milliseconds*/
#define LV_INDEV_DEF_READ_PERIOD 30 /*[ms]*///30
/*Use a custom tick source that tells the elapsed time in milliseconds.
*It removes the need to manually update the tick with `lv_tick_inc()`)*/
#define LV_TICK_CUSTOM 1
#if LV_TICK_CUSTOM
#define LV_TICK_CUSTOM_INCLUDE "Arduino.h" /*Header for the system time function*/
#define LV_TICK_CUSTOM_SYS_TIME_EXPR (millis()) /*Expression evaluating to current system time in ms*/
#endif /*LV_TICK_CUSTOM*/
/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings.
*(Not so important, you can adjust it to modify default sizes and spaces)*/
#define LV_DPI_DEF 130 /*[px/inch]*/
/*=======================
* FEATURE CONFIGURATION
*=======================*/
/*-------------
* Drawing
*-----------*/
/*Enable complex draw engine.
*Required to draw shadow, gradient, rounded corners, circles, arc, skew lines, image transformations or any masks*/
#define LV_DRAW_COMPLEX 1
#if LV_DRAW_COMPLEX != 0
/*Allow buffering some shadow calculation.
*LV_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius`
*Caching has LV_SHADOW_CACHE_SIZE^2 RAM cost*/
#define LV_SHADOW_CACHE_SIZE 0
/* Set number of maximally cached circle data.
* The circumference of 1/4 circle are saved for anti-aliasing
* radius * 4 bytes are used per circle (the most often used radiuses are saved)
* 0: to disable caching */
#define LV_CIRCLE_CACHE_SIZE 4
#endif /*LV_DRAW_COMPLEX*/
/*Default image cache size. Image caching keeps the images opened.
*If only the built-in image formats are used there is no real advantage of caching. (I.e. if no new image decoder is added)
*With complex image decoders (e.g. PNG or JPG) caching can save the continuous open/decode of images.
*However the opened images might consume additional RAM.
*0: to disable caching*/
#define LV_IMG_CACHE_DEF_SIZE 0
/*Number of stops allowed per gradient. Increase this to allow more stops.
*This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/
#define LV_GRADIENT_MAX_STOPS 2
/*Default gradient buffer size.
*When LVGL calculates the gradient "maps" it can save them into a cache to avoid calculating them again.
*LV_GRAD_CACHE_DEF_SIZE sets the size of this cache in bytes.
*If the cache is too small the map will be allocated only while it's required for the drawing.
*0 mean no caching.*/
#define LV_GRAD_CACHE_DEF_SIZE 0
/*Allow dithering the gradients (to achieve visual smooth color gradients on limited color depth display)
*LV_DITHER_GRADIENT implies allocating one or two more lines of the object's rendering surface
*The increase in memory consumption is (32 bits * object width) plus 24 bits * object width if using error diffusion */
#define LV_DITHER_GRADIENT 0
#if LV_DITHER_GRADIENT
/*Add support for error diffusion dithering.
*Error diffusion dithering gets a much better visual result, but implies more CPU consumption and memory when drawing.
*The increase in memory consumption is (24 bits * object's width)*/
#define LV_DITHER_ERROR_DIFFUSION 0
#endif
/*Maximum buffer size to allocate for rotation.
*Only used if software rotation is enabled in the display driver.*/
#define LV_DISP_ROT_MAX_BUF (10*1024)
/*-------------
* GPU
*-----------*/
/*Use STM32's DMA2D (aka Chrom Art) GPU*/
#define LV_USE_GPU_STM32_DMA2D 0
#if LV_USE_GPU_STM32_DMA2D
/*Must be defined to include path of CMSIS header of target processor
e.g. "stm32f769xx.h" or "stm32f429xx.h"*/
#define LV_GPU_DMA2D_CMSIS_INCLUDE
#endif
/*Use NXP's PXP GPU iMX RTxxx platforms*/
#define LV_USE_GPU_NXP_PXP 0
#if LV_USE_GPU_NXP_PXP
/*1: Add default bare metal and FreeRTOS interrupt handling routines for PXP (lv_gpu_nxp_pxp_osa.c)
* and call lv_gpu_nxp_pxp_init() automatically during lv_init(). Note that symbol SDK_OS_FREE_RTOS
* has to be defined in order to use FreeRTOS OSA, otherwise bare-metal implementation is selected.
*0: lv_gpu_nxp_pxp_init() has to be called manually before lv_init()
*/
#define LV_USE_GPU_NXP_PXP_AUTO_INIT 0
#endif
/*Use NXP's VG-Lite GPU iMX RTxxx platforms*/
#define LV_USE_GPU_NXP_VG_LITE 0
/*Use SDL renderer API*/
#define LV_USE_GPU_SDL 0
#if LV_USE_GPU_SDL
#define LV_GPU_SDL_INCLUDE_PATH <SDL2/SDL.h>
/*Texture cache size, 8MB by default*/
#define LV_GPU_SDL_LRU_SIZE (1024 * 1024 * 8)
/*Custom blend mode for mask drawing, disable if you need to link with older SDL2 lib*/
#define LV_GPU_SDL_CUSTOM_BLEND_MODE (SDL_VERSION_ATLEAST(2, 0, 6))
#endif
/*-------------
* Logging
*-----------*/
/*Enable the log module*/
#define LV_USE_LOG 0
#if LV_USE_LOG
/*How important log should be added:
*LV_LOG_LEVEL_TRACE A lot of logs to give detailed information
*LV_LOG_LEVEL_INFO Log important events
*LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem
*LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail
*LV_LOG_LEVEL_USER Only logs added by the user
*LV_LOG_LEVEL_NONE Do not log anything*/
#define LV_LOG_LEVEL LV_LOG_LEVEL_WARN
/*1: Print the log with 'printf';
*0: User need to register a callback with `lv_log_register_print_cb()`*/
#define LV_LOG_PRINTF 0
/*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/
#define LV_LOG_TRACE_MEM 1
#define LV_LOG_TRACE_TIMER 1
#define LV_LOG_TRACE_INDEV 1
#define LV_LOG_TRACE_DISP_REFR 1
#define LV_LOG_TRACE_EVENT 1
#define LV_LOG_TRACE_OBJ_CREATE 1
#define LV_LOG_TRACE_LAYOUT 1
#define LV_LOG_TRACE_ANIM 1
#endif /*LV_USE_LOG*/
/*-------------
* Asserts
*-----------*/
/*Enable asserts if an operation is failed or an invalid data is found.
*If LV_USE_LOG is enabled an error message will be printed on failure*/
#define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/
#define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/
#define LV_USE_ASSERT_STYLE 0 /*Check if the styles are properly initialized. (Very fast, recommended)*/
#define LV_USE_ASSERT_MEM_INTEGRITY 0 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
/*Add a custom handler when assert happens e.g. to restart the MCU*/
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
/*-------------
* Others
*-----------*/
/*1: Show CPU usage and FPS count*/
#define LV_USE_PERF_MONITOR 0
#if LV_USE_PERF_MONITOR
#define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
#endif
/*1: Show the used memory and the memory fragmentation
* Requires LV_MEM_CUSTOM = 0*/
#define LV_USE_MEM_MONITOR 0
#if LV_USE_MEM_MONITOR
#define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
#endif
/*1: Draw random colored rectangles over the redrawn areas*/
#define LV_USE_REFR_DEBUG 0
/*Change the built in (v)snprintf functions*/
#define LV_SPRINTF_CUSTOM 0
#if LV_SPRINTF_CUSTOM
#define LV_SPRINTF_INCLUDE <stdio.h>
#define lv_snprintf snprintf
#define lv_vsnprintf vsnprintf
#else /*LV_SPRINTF_CUSTOM*/
#define LV_SPRINTF_USE_FLOAT 0
#endif /*LV_SPRINTF_CUSTOM*/
#define LV_USE_USER_DATA 1
/*Garbage Collector settings
*Used if lvgl is bound to higher level language and the memory is managed by that language*/
#define LV_ENABLE_GC 0
#if LV_ENABLE_GC != 0
#define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/
#endif /*LV_ENABLE_GC*/
/*=====================
* COMPILER SETTINGS
*====================*/
/*For big endian systems set to 1*/
#define LV_BIG_ENDIAN_SYSTEM 0
/*Define a custom attribute to `lv_tick_inc` function*/
#define LV_ATTRIBUTE_TICK_INC
/*Define a custom attribute to `lv_timer_handler` function*/
#define LV_ATTRIBUTE_TIMER_HANDLER
/*Define a custom attribute to `lv_disp_flush_ready` function*/
#define LV_ATTRIBUTE_FLUSH_READY
/*Required alignment size for buffers*/
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1
/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default).
* E.g. __attribute__((aligned(4)))*/
#define LV_ATTRIBUTE_MEM_ALIGN
/*Attribute to mark large constant arrays for example font's bitmaps*/
#define LV_ATTRIBUTE_LARGE_CONST
/*Compiler prefix for a big array declaration in RAM*/
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY
/*Place performance critical functions into a faster memory (e.g RAM)*/
#define LV_ATTRIBUTE_FAST_MEM
/*Prefix variables that are used in GPU accelerated operations, often these need to be placed in RAM sections that are DMA accessible*/
#define LV_ATTRIBUTE_DMA
/*Export integer constant to binding. This macro is used with constants in the form of LV_<CONST> that
*should also appear on LVGL binding API such as Micropython.*/
#define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/
/*Extend the default -32k..32k coordinate range to -4M..4M by using int32_t for coordinates instead of int16_t*/
#define LV_USE_LARGE_COORD 0
/*==================
* FONT USAGE
*===================*/
/*Montserrat fonts with ASCII range and some symbols using bpp = 4
*https://fonts.google.com/specimen/Montserrat*/
#define LV_FONT_MONTSERRAT_8 0
#define LV_FONT_MONTSERRAT_10 0
#define LV_FONT_MONTSERRAT_12 0
#define LV_FONT_MONTSERRAT_14 1
#define LV_FONT_MONTSERRAT_16 1
#define LV_FONT_MONTSERRAT_18 0
#define LV_FONT_MONTSERRAT_20 1
#define LV_FONT_MONTSERRAT_22 1
#define LV_FONT_MONTSERRAT_24 1
#define LV_FONT_MONTSERRAT_26 0
#define LV_FONT_MONTSERRAT_28 1
#define LV_FONT_MONTSERRAT_30 0
#define LV_FONT_MONTSERRAT_32 1
#define LV_FONT_MONTSERRAT_34 0
#define LV_FONT_MONTSERRAT_36 1
#define LV_FONT_MONTSERRAT_38 0
#define LV_FONT_MONTSERRAT_40 0
#define LV_FONT_MONTSERRAT_42 0
#define LV_FONT_MONTSERRAT_44 0
#define LV_FONT_MONTSERRAT_46 0
#define LV_FONT_MONTSERRAT_48 1
/*Demonstrate special features*/
#define LV_FONT_MONTSERRAT_12_SUBPX 0
#define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, Persian letters and all their forms*/
#define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/
/*Pixel perfect monospace fonts*/
#define LV_FONT_UNSCII_8 0
#define LV_FONT_UNSCII_16 0
/*Optionally declare custom fonts here.
*You can use these fonts as default font too and they will be available globally.
*E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/
#define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(lv_font_cjk_16) LV_FONT_DECLARE(lv_font_cjk_24) LV_FONT_DECLARE(lv_font_num_64) LV_FONT_DECLARE(lv_font_media_16) LV_FONT_DECLARE(lv_font_media_24) LV_FONT_DECLARE(lv_font_zodiac_26)
/*Always set a default font*/
#define LV_FONT_DEFAULT &lv_font_montserrat_14
/*Enable handling large font and/or fonts with a lot of characters.
*The limit depends on the font size, font face and bpp.
*Compiler error will be triggered if a font needs it.*/
#define LV_FONT_FMT_TXT_LARGE 0
/*Enables/disables support for compressed fonts.*/
#define LV_USE_FONT_COMPRESSED 0
/*Enable subpixel rendering*/
#define LV_USE_FONT_SUBPX 0
#if LV_USE_FONT_SUBPX
/*Set the pixel order of the display. Physical order of RGB channels. Doesn't matter with "normal" fonts.*/
#define LV_FONT_SUBPX_BGR 0 /*0: RGB; 1:BGR order*/
#endif
/*=================
* TEXT SETTINGS
*=================*/
/**
* Select a character encoding for strings.
* Your IDE or editor should have the same character encoding
* - LV_TXT_ENC_UTF8
* - LV_TXT_ENC_ASCII
*/
#define LV_TXT_ENC LV_TXT_ENC_UTF8
/*Can break (wrap) texts on these chars*/
#define LV_TXT_BREAK_CHARS " ,.;:-_"
/*If a word is at least this long, will break wherever "prettiest"
*To disable, set to a value <= 0*/
#define LV_TXT_LINE_BREAK_LONG_LEN 0
/*Minimum number of characters in a long word to put on a line before a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3
/*Minimum number of characters in a long word to put on a line after a break.
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3
/*The control character to use for signalling text recoloring.*/
#define LV_TXT_COLOR_CMD "#"
/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts.
*The direction will be processed according to the Unicode Bidirectional Algorithm:
*https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/
#define LV_USE_BIDI 0
#if LV_USE_BIDI
/*Set the default direction. Supported values:
*`LV_BASE_DIR_LTR` Left-to-Right
*`LV_BASE_DIR_RTL` Right-to-Left
*`LV_BASE_DIR_AUTO` detect texts base direction*/
#define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
#endif
/*Enable Arabic/Persian processing
*In these languages characters should be replaced with an other form based on their position in the text*/
#define LV_USE_ARABIC_PERSIAN_CHARS 0
/*==================
* WIDGET USAGE
*================*/
/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/
#define LV_USE_ARC 1
#define LV_USE_ANIMIMG 1
#define LV_USE_BAR 1
#define LV_USE_BTN 1
#define LV_USE_BTNMATRIX 1
#define LV_USE_CANVAS 1
#define LV_USE_CHECKBOX 1
#define LV_USE_DROPDOWN 1 /*Requires: lv_label*/
#define LV_USE_IMG 1 /*Requires: lv_label*/
#define LV_USE_LABEL 1
#if LV_USE_LABEL
#define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/
#define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/
#endif
#define LV_USE_LINE 1
#define LV_USE_ROLLER 1 /*Requires: lv_label*/
#if LV_USE_ROLLER
#define LV_ROLLER_INF_PAGES 7 /*Number of extra "pages" when the roller is infinite*/
#endif
#define LV_USE_SLIDER 1 /*Requires: lv_bar*/
#define LV_USE_SWITCH 1
#define LV_USE_TEXTAREA 1 /*Requires: lv_label*/
#if LV_USE_TEXTAREA != 0
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
#endif
#define LV_USE_TABLE 1
/*==================
* EXTRA COMPONENTS
*==================*/
/*-----------
* Widgets
*----------*/
#define LV_USE_CALENDAR 1
#if LV_USE_CALENDAR
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
#if LV_CALENDAR_WEEK_STARTS_MONDAY
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}
#else
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
#endif
#define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
#define LV_USE_CALENDAR_HEADER_ARROW 1
#define LV_USE_CALENDAR_HEADER_DROPDOWN 1
#endif /*LV_USE_CALENDAR*/
#define LV_USE_CHART 1
#define LV_USE_COLORWHEEL 1
#define LV_USE_IMGBTN 1
#define LV_USE_KEYBOARD 1
#define LV_USE_LED 1
#define LV_USE_LIST 1
#define LV_USE_MENU 1
#define LV_USE_METER 1
#define LV_USE_MSGBOX 1
#define LV_USE_SPINBOX 1
#define LV_USE_SPINNER 1
#define LV_USE_TABVIEW 1
#define LV_USE_TILEVIEW 1
#define LV_USE_WIN 1
#define LV_USE_SPAN 1
#if LV_USE_SPAN
/*A line text can contain maximum num of span descriptor */
#define LV_SPAN_SNIPPET_STACK_SIZE 64
#endif
/*-----------
* Themes
*----------*/
/*A simple, impressive and very complete theme*/
#define LV_USE_THEME_DEFAULT 1
#if LV_USE_THEME_DEFAULT
/*0: Light mode; 1: Dark mode*/
#define LV_THEME_DEFAULT_DARK 0
/*1: Enable grow on press*/
#define LV_THEME_DEFAULT_GROW 1
/*Default transition time in [ms]*/
#define LV_THEME_DEFAULT_TRANSITION_TIME 80
#endif /*LV_USE_THEME_DEFAULT*/
/*A very simple theme that is a good starting point for a custom theme*/
#define LV_USE_THEME_BASIC 1
/*A theme designed for monochrome displays*/
#define LV_USE_THEME_MONO 1
/*-----------
* Layouts
*----------*/
/*A layout similar to Flexbox in CSS.*/
#define LV_USE_FLEX 1
/*A layout similar to Grid in CSS.*/
#define LV_USE_GRID 1
/*---------------------
* 3rd party libraries
*--------------------*/
/*File system interfaces for common APIs */
/*API for fopen, fread, etc*/
#define LV_USE_FS_STDIO 0
#if LV_USE_FS_STDIO
#define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for open, read, etc*/
#define LV_USE_FS_POSIX 0
#if LV_USE_FS_POSIX
#define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for CreateFile, ReadFile, etc*/
#define LV_USE_FS_WIN32 0
#if LV_USE_FS_WIN32
#define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
#define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/
#define LV_USE_FS_FATFS 0
#if LV_USE_FS_FATFS
#define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
#define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
#endif
/*PNG decoder library*/
#define LV_USE_PNG 0
/*BMP decoder library*/
#define LV_USE_BMP 0
/* JPG + split JPG decoder library.
* Split JPG is a custom format optimized for embedded systems. */
#define LV_USE_SJPG 0
/*GIF decoder library*/
#define LV_USE_GIF 0
/*QR code library*/
#define LV_USE_QRCODE 0
/*FreeType library*/
#define LV_USE_FREETYPE 0
#if LV_USE_FREETYPE
/*Memory used by FreeType to cache characters [bytes] (-1: no caching)*/
#define LV_FREETYPE_CACHE_SIZE (16 * 1024)
#if LV_FREETYPE_CACHE_SIZE >= 0
/* 1: bitmap cache use the sbit cache, 0:bitmap cache use the image cache. */
/* sbit cache:it is much more memory efficient for small bitmaps(font size < 256) */
/* if font size >= 256, must be configured as image cache */
#define LV_FREETYPE_SBIT_CACHE 0
/* Maximum number of opened FT_Face/FT_Size objects managed by this cache instance. */
/* (0:use system defaults) */
#define LV_FREETYPE_CACHE_FT_FACES 0
#define LV_FREETYPE_CACHE_FT_SIZES 0
#endif
#endif
/*Rlottie library*/
#define LV_USE_RLOTTIE 0
/*FFmpeg library for image decoding and playing videos
*Supports all major image formats so do not enable other image decoder with it*/
#define LV_USE_FFMPEG 0
#if LV_USE_FFMPEG
/*Dump input information to stderr*/
#define LV_FFMPEG_AV_DUMP_FORMAT 0
#endif
/*-----------
* Others
*----------*/
/*1: Enable API to take snapshot for object*/
#define LV_USE_SNAPSHOT 1
/*1: Enable Monkey test*/
#define LV_USE_MONKEY 0
/*1: Enable grid navigation*/
#define LV_USE_GRIDNAV 0
/*1: Enable lv_obj fragment*/
#define LV_USE_FRAGMENT 0
/*==================
* EXAMPLES
*==================*/
/*Enable the examples to be built with the library*/
#define LV_BUILD_EXAMPLES 1
/*===================
* DEMO USAGE
====================*/
/*Show some widget. It might be required to increase `LV_MEM_SIZE` */
#define LV_USE_DEMO_WIDGETS 1
#if LV_USE_DEMO_WIDGETS
#define LV_DEMO_WIDGETS_SLIDESHOW 1
#endif
/*Demonstrate the usage of encoder and keyboard*/
#define LV_USE_DEMO_KEYPAD_AND_ENCODER 1
/*Benchmark your system*/
#define LV_USE_DEMO_BENCHMARK 1
/*Stress test for LVGL*/
#define LV_USE_DEMO_STRESS 0
/*Music player demo*/
#define LV_USE_DEMO_MUSIC 1
#if LV_USE_DEMO_MUSIC
# define LV_DEMO_MUSIC_SQUARE 1
# define LV_DEMO_MUSIC_LANDSCAPE 1
# define LV_DEMO_MUSIC_ROUND 1
# define LV_DEMO_MUSIC_LARGE 1
# define LV_DEMO_MUSIC_AUTO_PLAY 1
#endif
/*--END OF LV_CONF_H--*/
#endif /*LV_CONF_H*/
#endif /*End of "Content enable"*/

28
partitions.csv 100644
View File

@ -0,0 +1,28 @@
# Name, Type, SubType, Offset, Size, Flags
#
# partitions.csv —— nex_buddy 自定义分区表(16MB Flash)
#
# 注意:第一行必须是表头,"# Name, Type, SubType..." 不能被别的注释挤下去,
# 否则 gen_esp32part.py 会把第一条注释当表头,后面全部错位(踩过)。
#
# 为什么不用官方的 app3M_fat9M_16MB:
# 官方表是 2×3MB app + 9.9MB ffat。9.9MB 的 ffat 这个项目一分没用
# (代码里没有 SPIFFS/LittleFS/FFat,图片与音乐都在 TF 卡上走 SD_MMC),
# 而 3MB 的 app 槽已经被固件占到 81%,OTA 再塞新固件和新功能就没余量了。
# 所以把 ffat 的地盘让给 app:两个 7.5MB 槽,A/B 对等。
#
# 关键:nvs(0x9000) 和 otadata(0xE000) 的偏移与官方表完全一致。
# 这样"只改分区表 + 写 app0"不会碰到 NVS,配网信息与绑定 token 都保留,
# 不用重新配网、不用重新扫码绑定。
#
# OTA 语义:app0 / app1 是两个对等的 ota 槽。固件 OTA 只写"非当前运行"的那个槽,
# 写完把 otadata 指过去。另一个槽天然留着上一个能跑的版本 —— 这就是回滚的底。
# 能不能回滚用镜像头判断(槽首字节 0xE9 = ESP 镜像魔数),不靠"我以为它在"。
#
# 尾部 0xE0000(896KB)未分配:留给以后可能要放进 flash 的静态资源,
# 现在不建 ffat,避免又出现一块永远不用的分区。
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xE000, 0x2000,
app0, app, ota_0, 0x10000, 0x780000,
app1, app, ota_1, 0x790000, 0x780000,
coredump, data, coredump,0xF10000, 0x10000,
Can't render this file because it contains an unexpected character in line 5 and column 39.

1865
slave_audio/minimp3.h 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,18 @@
# Name, Type, SubType, Offset, Size, Flags
#
# Name, Type, SubType, Offset, Size, Flags
#
# 副控 ESP32-U4WDH 4MB 双槽分区表 —— 与主控同构(A/B 对等 OTA)
#
# 为什么 app 槽给 1.75MB:bluedroid + SBC 解码 + minimp3 编出来约 1.3~1.4MB,
# 官方 4MB default 表的双槽只有 1.2MB,塞不下;尾部剩余空间不做文件系统
#(副控不读 TF 卡,配网在主控侧),留白即可。
#
# ⚠ 第一行必须是表头(上面那行就是),否则 gen_esp32part 把第一条注释当表头、
# 后面全部错位 —— 主控的 partitions.csv 踩过同一个坑。
#
# 烧录脚本按这份表对齐 offset:bootloader 0x1000 / 分区表 0x8000 / app0 0x10000。
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x1c0000,
app1, app, ota_1, 0x1d0000, 0x1c0000,

View File

@ -0,0 +1,354 @@
// slave_audio.ino —— 副控 ESP32-U4WDH 音频固件(双音源版)
//
// 两个音源共用同一路 I2S → PCM5100:
// [BT ] A2DP Sink(手机/电脑连 TAIJI_KNOB_AUDIO 推音频)—— 保住原厂的蓝牙能力
// [UART] 主控 KnobOS 推的 MP3 码流(AA 55 帧)—— TF 卡/网络音乐
//
// 仲裁规则(后到者赢):
// - 蓝牙第一包音频到达 → 抢占输出,UART 播放立即停(ring 清空)
// - 主控发 START → 抢占输出,蓝牙被 pause(保持连接不踢下线)
// - 蓝牙断开 → 输出归还空闲
//
// 接线(来自原理图,不是封装引脚序号):
// I2S BCK=GPIO25 DIN=GPIO26 LRCK=GPIO27 XSMT(静音脚)=GPIO32,拉高才出声
// UART RX=GPIO18(收主控 TX40) TX=GPIO23(发主控 RX39) 921600 8N1
//
// 帧格式:AA 55 | cmd | len_lo len_hi | payload | crc8(0x07, init 0)
// 主控→副控:01 START / 02 DATA / 03 END / 04 PAUSE / 05 VOL / 06 STOP
// 副控→主控:30 STATUS payload = [state, freeKbHi, freeKbLo, 0]
//
// 烧录:副控的 USB 走 CH340C(UART0 = GPIO1/3),板子选 "ESP32 Dev Module"
//(4MB Flash,无 PSRAM),分区表用平台官方 no_fs(双 OTA 槽各 2MB + coredump)。
// 注意:烧录会覆盖原厂固件,务必先 read-flash 备份整个 4MB!
#include <Arduino.h>
#include "driver/i2s.h"
#include "BluetoothA2DPSink.h"
extern "C" {
#define MINIMP3_IMPLEMENTATION
#include "minimp3.h"
}
// ------------------------------ 引脚 ------------------------------
#define PIN_I2S_BCK 25
#define PIN_I2S_DIN 26
#define PIN_I2S_LRCK 27
#define PIN_XSMT 32
#define PIN_UART_RX 18
#define PIN_UART_TX 23
#define UART_SPEED 921600
// ---------------------------- 缓冲与状态 ----------------------------
// 64KB 码流缓冲;U4WDH 只有 320KB DRAM 还要养蓝牙栈,
// malloc 失败就降 32KB —— 320kbps 码流下 32KB 也有约 0.8 秒余量。
static const uint32_t RING = 64 * 1024;
static uint32_t s_ringSize = 0;
static uint8_t* s_ring = nullptr;
static uint32_t s_w = 0, s_r = 0; // 自由递增游标,用差值算占用
static uint8_t s_vol = 80;
static bool s_playing = false;
static bool s_paused = false;
static bool s_eos = false;
static bool s_btConnected = false;
static uint8_t s_src = 0; // 0 空闲 / 1 uart / 2 蓝牙
static uint32_t s_underrun = 0, s_decodeErr = 0, s_frames = 0;
static uint32_t s_lastStatus = 0;
BluetoothA2DPSink a2dp_sink;
static inline uint32_t ringAvail() { return s_w - s_r; }
static inline uint32_t ringSpace() { return s_ringSize - ringAvail(); }
static void ringPush(const uint8_t* d, uint32_t n) {
uint32_t sp = ringSpace();
if (n > sp) n = sp; // 满了就丢(主控有流控,正常不会到这)
uint32_t off = s_w % s_ringSize;
uint32_t first = s_ringSize - off;
if (first > n) first = n;
memcpy(s_ring + off, d, first);
if (n > first) memcpy(s_ring, d + first, n - first);
s_w += n;
}
static void ringPop(uint8_t* d, uint32_t n) {
uint32_t off = s_r % s_ringSize;
uint32_t first = s_ringSize - off;
if (first > n) first = n;
memcpy(d, s_ring + off, first);
if (n > first) memcpy(d + first, s_ring, n - first);
s_r += n;
}
static void ringClear() { s_w = s_r = 0; }
// ------------------------------ I2S ------------------------------
static int s_hz = 0;
static void i2sSetup(uint32_t hz) {
if (s_hz == (int)hz) return;
if (s_hz == 0) {
i2s_config_t cfg = {};
cfg.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
cfg.sample_rate = hz;
cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
cfg.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S;
cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
cfg.dma_buf_count = 8;
cfg.dma_buf_len = 256;
cfg.use_apll = false;
cfg.tx_desc_auto_clear = true;
i2s_driver_install(I2S_NUM_0, &cfg, 0, nullptr);
i2s_pin_config_t pins = {};
pins.bck_io_num = PIN_I2S_BCK;
pins.ws_io_num = PIN_I2S_LRCK;
pins.data_out_num = PIN_I2S_DIN;
pins.data_in_num = -1;
i2s_set_pin(I2S_NUM_0, &pins);
i2s_zero_dma_buffer(I2S_NUM_0);
} else {
i2s_set_clk(I2S_NUM_0, hz, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_STEREO);
}
s_hz = (int)hz;
}
static void i2sWrite(const int16_t* d, size_t samples) { // samples = 每声道采样数
size_t bytes = samples * 2 * sizeof(int16_t);
size_t done = 0;
i2s_write(I2S_NUM_0, d, bytes, &done, portMAX_DELAY);
}
// ------------------------------ 解码 ------------------------------
static mp3dec_t s_dec;
static int16_t s_pcm[MINIMP3_MAX_SAMPLES_PER_FRAME];
static uint8_t s_stage[4096];
static int16_t s_silence[1152 * 2] = {0};
static void applyVolume(int16_t* pcm, size_t n) {
if (s_vol >= 100) return;
int32_t g = s_vol;
for (size_t i = 0; i < n; i++) pcm[i] = (int16_t)((int32_t)pcm[i] * g / 100);
}
static void audioStep() {
uint32_t avail = ringAvail();
// 欠载:补一小段静音拖住 I2S 时钟,否则 PCM5100 会听到"咔"
if (avail < 512 && !(s_eos && avail > 0)) {
if (s_playing && !s_paused) { s_underrun++; i2sWrite(s_silence, 1152); }
return;
}
uint32_t take = avail > sizeof(s_stage) ? sizeof(s_stage) : avail;
ringPop(s_stage, take);
mp3dec_frame_info_t info = {};
int samples = mp3dec_decode_frame(&s_dec, s_stage, (int)take, s_pcm, &info);
if (info.frame_bytes == 0) {
// 没找到帧头:扔 1 字节重新对齐
s_r -= (take - 1);
s_decodeErr++;
return;
}
s_r -= (take - info.frame_bytes); // 没吃完的还给缓冲
if (samples <= 0) return;
i2sSetup(info.hz > 0 ? (uint32_t)info.hz : 44100);
size_t n = (size_t)samples * (size_t)info.channels;
if (info.channels == 1) {
// 单声道复制成双声道
for (int i = samples - 1; i >= 0; i--) {
s_pcm[i * 2 + 1] = s_pcm[i];
s_pcm[i * 2] = s_pcm[i];
}
n = (size_t)samples * 2;
}
applyVolume(s_pcm, n);
i2sWrite(s_pcm, (size_t)samples);
s_frames++;
}
// ---------------------------- 音源仲裁 ----------------------------
static void releaseIfIdle() {
if (s_src == 0 && !s_playing) digitalWrite(PIN_XSMT, LOW);
}
// 蓝牙数据到达:抢占输出(后到者赢),UART 播放立即停
static void a2dpDataCb(const uint8_t* data, uint32_t len) {
if (s_src != 2) {
s_src = 2;
if (s_playing || s_paused) { // 打断 UART 播放
s_playing = false; s_paused = false; s_eos = false;
ringClear();
}
i2sSetup(44100);
digitalWrite(PIN_XSMT, HIGH);
}
if (len == 0) return;
size_t done = 0;
// 蓝牙任务里不能无限阻塞:50ms 写不进就丢,I2S DMA 8x256 能扛 23ms
i2s_write(I2S_NUM_0, data, len, &done, pdMS_TO_TICKS(50));
}
// 蓝牙连接状态:断开时把输出还给空闲
static void a2dpConnCb(esp_a2d_connection_state_t st, void*) {
if (st == ESP_A2D_CONNECTION_STATE_CONNECTED) {
s_btConnected = true;
Serial.println("BT connected");
} else if (st == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
s_btConnected = false;
if (s_src == 2) s_src = 0;
releaseIfIdle();
Serial.println("BT disconnected");
}
}
// ---------------------------- 帧解析 ----------------------------
enum : uint8_t { H0, H1, CMD, LEN0, LEN1, PAY, CRC };
static uint8_t s_st = H0;
static uint8_t s_cmd = 0;
static uint16_t s_len = 0, s_idx = 0;
static uint8_t s_crc = 0;
static uint8_t s_ctrl[8];
static uint8_t crc8Update(uint8_t c, uint8_t b) {
c ^= b;
for (int i = 0; i < 8; i++) c = (c & 0x80) ? (uint8_t)((c << 1) ^ 0x07) : (uint8_t)(c << 1);
return c;
}
static void sendStatus() {
uint32_t freeKb = ringSpace() / 1024;
if (freeKb > 0xFFFF) freeKb = 0xFFFF;
uint8_t st = s_playing ? (s_paused ? 2 : (s_eos ? 3 : 1)) : 0;
uint8_t f[10] = {0xAA, 0x55, 0x30, 0x04, 0x00, st,
(uint8_t)(freeKb >> 8), (uint8_t)(freeKb & 0xFF), 0x00, 0x00};
uint8_t c = 0;
for (int i = 2; i < 9; i++) c = crc8Update(c, f[i]);
f[9] = c;
Serial2.write(f, sizeof(f));
}
static void handleCmd(uint8_t cmd) {
switch (cmd) {
case 0x01: // START:抢占输出
if (s_btConnected) a2dp_sink.pause(); // 蓝牙让路但保持连接
ringClear();
mp3dec_init(&s_dec);
s_playing = true; s_paused = false; s_eos = false;
s_src = 1;
i2sSetup(44100);
digitalWrite(PIN_XSMT, HIGH); // PCM5100 解除静音
Serial.println("START");
break;
case 0x03: // END
s_eos = true;
break;
case 0x04: // PAUSE
s_paused = (s_len >= 1 && s_ctrl[0] != 0);
Serial.printf("PAUSE %d\n", s_paused);
break;
case 0x05: // VOL(只作用于 UART 源;蓝牙音量在手机端)
if (s_len >= 1) s_vol = s_ctrl[0] > 100 ? 100 : s_ctrl[0];
break;
case 0x06: // STOP
s_playing = false; s_paused = false; s_eos = false;
s_src = 0;
ringClear();
releaseIfIdle();
Serial.println("STOP");
break;
default:
break;
}
}
static void feedByte(uint8_t b) {
switch (s_st) {
case H0: if (b == 0xAA) s_st = H1; break;
case H1: s_st = (b == 0x55) ? CMD : H0; break;
case CMD: s_cmd = b; s_crc = crc8Update(0, b); s_st = LEN0; break;
case LEN0: s_len = b; s_crc = crc8Update(s_crc, b); s_st = LEN1; break;
case LEN1:
s_len |= (uint16_t)b << 8;
s_crc = crc8Update(s_crc, b);
s_idx = 0;
if (s_len > 1024) { s_st = H0; break; } // 异常长度,重新同步
s_st = s_len ? PAY : CRC;
break;
case PAY:
s_crc = crc8Update(s_crc, b);
if (s_cmd == 0x02) ringPush(&b, 1); // DATA 直接进环形缓冲
else if (s_idx < sizeof(s_ctrl)) s_ctrl[s_idx] = b;
if (++s_idx >= s_len) s_st = CRC;
break;
case CRC:
if (b == s_crc) handleCmd(s_cmd);
else if (s_cmd == 0x02) s_decodeErr++; // 码流帧校验失败:记一笔,解码器会自己找同步
s_st = H0;
break;
default:
s_st = H0;
break;
}
}
// ------------------------------ 主流程 ------------------------------
void setup() {
Serial.begin(115200);
delay(150);
Serial.println("\n=== slave_audio (A2DP sink + uart mp3 + PCM5100) ===");
pinMode(PIN_XSMT, OUTPUT);
digitalWrite(PIN_XSMT, LOW); // 先静音,等有源再放开
s_ring = (uint8_t*)malloc(RING);
s_ringSize = RING;
if (!s_ring) { // 内存紧(蓝牙栈先吃了一口)就降半
s_ring = (uint8_t*)malloc(RING / 2);
s_ringSize = RING / 2;
}
if (!s_ring) {
Serial.println("!! ring alloc failed");
while (true) delay(1000);
}
Serial.printf("ring=%uKB\n", (unsigned)(s_ringSize / 1024));
Serial2.setRxBufferSize(4096);
Serial2.begin(UART_SPEED, SERIAL_8N1, PIN_UART_RX, PIN_UART_TX);
Serial.printf("uart2 rx=%d tx=%d @%d\n", PIN_UART_RX, PIN_UART_TX, UART_SPEED);
i2sSetup(44100);
mp3dec_init(&s_dec);
// A2DP Sink:数据已被库应用了 AVRC 音量,i2s_output=false 表示我们自己写 I2S
a2dp_sink.set_stream_reader(a2dpDataCb, false);
a2dp_sink.set_on_connection_state_changed(a2dpConnCb);
a2dp_sink.set_auto_reconnect(true);
a2dp_sink.start("NEX_BUDDY_AUDIO");
Serial.println("ready");
}
void loop() {
// 收包(一次最多消费一批,避免饿死解码)
int budget = 1024;
while (Serial2.available() && budget-- > 0) feedByte((uint8_t)Serial2.read());
if (s_playing && s_src == 1) audioStep();
uint32_t now = millis();
if (now - s_lastStatus >= 250) {
s_lastStatus = now;
sendStatus();
if (s_playing && (now % 5000) < 250) {
Serial.printf("frames=%u under=%u err=%u free=%uKB src=%u\n",
(unsigned)s_frames, (unsigned)s_underrun,
(unsigned)s_decodeErr, (unsigned)(ringSpace() / 1024), s_src);
}
}
}

View File

@ -0,0 +1,273 @@
#include "AstroApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../services/AstroService.h"
#include "../services/PlatformService.h"
#include "../services/NetService.h"
#include "../core/Log.h"
#include <math.h>
namespace apps {
// 黄经度数那一行:LVGL 的 lv_snprintf 默认不编译浮点(LV_SPRINTF_USE_FLOAT=0),
// "%.1f" 会打成一串乱码(实测只吐出 "f")。这里自己拆整数十位,绕开浮点格式化。
static void setElementDeg(lv_obj_t* lbl, const String& element, float deg) {
int tenths = (int)lroundf(deg * 10.0f);
if (tenths < 0) tenths = 0;
char buf[48];
snprintf(buf, sizeof(buf), "%s · %d.%d°", element.c_str(), tenths / 10, tenths % 10);
lv_label_set_text(lbl, buf);
}
AstroApp astroApp;
// needBind=true:按用户约定,除设置和时钟外所有模块都强制绑定,
// 未绑定时进模块直接拉起绑定页(Shell 统一处理)。
static const AppMeta META = {"astro", "星盘", LV_SYMBOL_EYE_OPEN, &icon_astro, 0xB39DDB, true, true};
const AppMeta& AstroApp::meta() const { return META; }
// 一行「符号 + 星座名」:26px 黄道字形 + 24px 中文,横排居中。
// 符号单独用一种字体:CJK 字库里没有 ♈~♓,混排只会得到空心方块。
static lv_obj_t* signRow(lv_obj_t* parent, int y, lv_obj_t** icon, lv_obj_t** name) {
lv_obj_t* row = lv_obj_create(parent);
lv_obj_remove_style_all(row);
lv_obj_set_size(row, 280, 36);
lv_obj_align(row, LV_ALIGN_CENTER, 0, y);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(row, 10, 0);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
*icon = ui::label(row, "", FONT_ZODIAC, theme::accent());
*name = ui::label(row, "", FONT_MEDIA_24, theme::text());
return row;
}
// "2026-11" → "2026 年 11 月"。运势标题里的月份原来和标题挤在一行,
// 读起来像一句话;拆开单独一行,月份才是这一页的"日期锚点"。
static String monthText(const String& p) {
int dash = p.indexOf('-');
if (dash <= 0 || dash >= (int)p.length() - 1) return p;
String y = p.substring(0, dash);
String m = p.substring(dash + 1);
return y + " 年 " + m + " 月";
}
void AstroApp::build(lv_obj_t* root) {
lv_obj_add_flag(root, LV_OBJ_FLAG_CLICKABLE);
// 根节点不可滚:页面高度超出圆屏内切矩形,留着 SCROLLABLE(LVGL 默认开)
// 一棵下滑就把内容推出屏,露出一屏黑底——看起来像死机。
lv_obj_clear_flag(root, LV_OBJ_FLAG_SCROLLABLE);
// 不再画"太阳在星座内的度数"弧:它没有标签,读者只会以为在加载;
// 度数本身已经写在「火 · 3.4°」那一行里。
// ---- 页 0:星座 ----
_page0 = lv_obj_create(root);
lv_obj_remove_style_all(_page0);
lv_obj_set_size(_page0, 300, 280);
lv_obj_align(_page0, LV_ALIGN_CENTER, 0, 0);
lv_obj_clear_flag(_page0, LV_OBJ_FLAG_SCROLLABLE);
_period = ui::label(_page0, "", FONT_MEDIA, theme::textDim());
lv_obj_align(_period, LV_ALIGN_CENTER, 0, -106);
// 空态用图标撑住上半圆,否则整页只有几行小字,看着像没加载出来
_icon = lv_img_create(_page0);
lv_img_set_src(_icon, &icon_astro);
lv_obj_set_style_img_recolor(_icon, theme::textDim(), 0);
lv_obj_set_style_img_recolor_opa(_icon, LV_OPA_60, 0);
lv_obj_align(_icon, LV_ALIGN_CENTER, 0, -18);
lv_obj_clear_flag(_icon, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(_icon, LV_OBJ_FLAG_HIDDEN);
// 星座信息加大到 24px:这一页只有两个答案(太阳是什么、月亮是什么),
// 16px 在圆屏上要凑近才看得清。符号行和名字行同高,居中排。
_sunRow = signRow(_page0, -64, &_sunIcon, &_sunName);
_sunMeta = ui::label(_page0, "", FONT_MEDIA, theme::textDim());
lv_obj_align(_sunMeta, LV_ALIGN_CENTER, 0, -28);
_moonRow = signRow(_page0, 6, &_moonIcon, &_moonName);
_moonMeta = ui::label(_page0, "", FONT_MEDIA, theme::textDim());
lv_obj_align(_moonMeta, LV_ALIGN_CENTER, 0, 42);
_state = ui::label(_page0, "", FONT_TEXT, theme::textDim());
lv_obj_align(_state, LV_ALIGN_CENTER, 0, 92);
// ---- 页 1:运势 ----
_page1 = lv_obj_create(root);
lv_obj_remove_style_all(_page1);
lv_obj_set_size(_page1, 264, 240);
lv_obj_align(_page1, LV_ALIGN_CENTER, 0, 0);
// 运势正文比屏高,容器要能滚:竖向布局 + 隐藏滚动条
ui::listColumn(_page1);
lv_obj_set_style_pad_all(_page1, 6, 0);
lv_obj_add_flag(_page1, LV_OBJ_FLAG_HIDDEN);
// 月份单独一行:它是这一页的日期锚点,不该和标题揉成一句话
_fMonth = ui::label(_page1, "", FONT_MEDIA_24, theme::accent());
lv_obj_set_width(_fMonth, 244);
_fTitle = ui::label(_page1, "", FONT_MEDIA, theme::textDim());
lv_label_set_long_mode(_fTitle, LV_LABEL_LONG_WRAP);
lv_obj_set_width(_fTitle, 244);
lv_obj_set_style_pad_top(_fTitle, 4, 0);
_fBody = ui::label(_page1, "", FONT_MEDIA, theme::text());
lv_label_set_long_mode(_fBody, LV_LABEL_LONG_WRAP);
lv_obj_set_width(_fBody, 244);
lv_obj_set_style_pad_top(_fBody, 10, 0);
}
// 点击不再触发更新:更新走缓存策略(进页/定时),
// "点一下就打接口"既浪费又容易让人以为页面没反应。
void AstroApp::onEnter() {
apply();
svc::astro.requestUpdate(); // 是否真发请求由 6h 缓存决定
}
void AstroApp::onTick(uint32_t nowMs) {
if (nowMs - _lastTick < 1200) return;
_lastTick = nowMs;
// 数据版本变了才重刷控件,避免每 1.2s 重写 label 造成闪烁
if (svc::astro.data().updatedMs != _lastApplied) {
apply();
return;
}
// 绑定/联网状态自己会变(未绑定时空态文案要跟着走),变了也重画一次
uint8_t st = !svc::platform.bound()
? (svc::net.online() ? (svc::platform.serverOk() ? 2 : 1) : 0)
: 3;
if (st != _bindState) {
_bindState = st;
apply();
return;
}
// 页 1 在更新期间给个轻提示
if (_page == 1 && svc::astro.data().updating) lv_label_set_text(_fTitle, "更新中…");
}
void AstroApp::showPage(uint8_t page) {
_page = page & 1;
if (_page == 0) {
lv_obj_add_flag(_page1, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_page0, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(_page0, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_page1, LV_OBJ_FLAG_HIDDEN);
lv_obj_scroll_to_y(_page1, 0, LV_ANIM_OFF);
}
}
void AstroApp::apply() {
const auto& d = svc::astro.data();
_lastApplied = d.updatedMs;
// 首页顶部月份也用「2026 年 11 月」:和运势页一致,别一页一个写法
lv_label_set_text(_period, ui::fitFont(FONT_MEDIA,
d.period.length() ? monthText(d.period) : String("星盘")).c_str());
// 空态:图标居中偏上,两行星座信息整体收起,只留顶部状态 + 底部提示。
auto showEmpty = [this](bool on) {
if (on) {
lv_obj_clear_flag(_icon, LV_OBJ_FLAG_HIDDEN);
lv_obj_align(_icon, LV_ALIGN_CENTER, 0, -24);
lv_obj_add_flag(_sunRow, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_sunMeta, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_moonRow, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_moonMeta, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(_icon, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_sunRow, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_sunMeta, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_moonRow, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_moonMeta, LV_OBJ_FLAG_HIDDEN);
}
};
if (!svc::platform.bound()) {
showEmpty(true);
lv_label_set_text(_period, "星盘");
// 统一空态文案(platform.stateHint()),与「我的」/天气同口径
lv_label_set_text(_state, svc::platform.stateHint());
lv_label_set_text(_fMonth, "星盘");
lv_label_set_text(_fTitle, "");
lv_label_set_text(_fBody, ""); // 上面一句已经说清了,不再重复
return;
}
if (!d.valid) {
showEmpty(true);
lv_label_set_text(_period, d.updating ? "更新中" : "暂无数据");
// 错误原文只进日志:用户看不懂 "HTTP 500",屏幕上给一句人话
if (d.error.length()) LOG("ASTRO", "error: %s", d.error.c_str());
lv_label_set_text(_state, d.updating ? "更新中…" : "");
lv_label_set_text(_fMonth, monthText(d.period).c_str());
lv_label_set_text(_fTitle, "本月运势");
lv_label_set_text(_fBody, d.updating ? "" : "暂时取不到,稍后再看");
return;
}
showEmpty(false);
// 星座名是服务端动态文本,必须用媒体字体。
// 符号(♊ 这类)走单独的黄道字形字体——CJK 字库里没有这些码位,
// 混在中文字体里排出来就是一个空心方块(过去干脆不显示)。
lv_label_set_text(_sunName,
ui::fitFont(FONT_MEDIA_24, String("太阳 ") + d.sun.name).c_str());
lv_label_set_text(_moonName,
ui::fitFont(FONT_MEDIA_24, String("月亮 ") + d.moon.name).c_str());
String sunSym = ui::fitFont(FONT_ZODIAC, d.sun.symbol);
String moonSym = ui::fitFont(FONT_ZODIAC, d.moon.symbol);
lv_label_set_text(_sunIcon, sunSym.c_str());
lv_label_set_text(_moonIcon, moonSym.c_str());
// 服务端没给符号就整块收起,别在名字旁边留一个空位。
// 收起/展开会改变同排的布局,显式让它重排一次(否则文字还停在旧位置)。
if (sunSym.length()) lv_obj_clear_flag(_sunIcon, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(_sunIcon, LV_OBJ_FLAG_HIDDEN);
if (moonSym.length()) lv_obj_clear_flag(_moonIcon, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(_moonIcon, LV_OBJ_FLAG_HIDDEN);
lv_obj_update_layout(_sunRow);
lv_obj_update_layout(_moonRow);
setElementDeg(_sunMeta, d.sun.element, d.sun.degree);
setElementDeg(_moonMeta, d.moon.element, d.moon.degree);
lv_label_set_text(_state, ""); // 状态行只在有话说的时候才写
// 月份、运势标题、正文各占一行:月份是日期锚点,标题说明这是谁的运势
lv_label_set_text(_fMonth, ui::fitFont(FONT_MEDIA_24, monthText(d.period)).c_str());
lv_label_set_text(_fTitle,
ui::fitFont(FONT_MEDIA, d.fortuneTitle.length() ? d.fortuneTitle
: String("本月运势")).c_str());
lv_label_set_text(_fBody,
ui::fitFont(FONT_MEDIA, d.fortuneBody.length() ? d.fortuneBody
: String("本月运势还没准备好")).c_str());
}
bool AstroApp::onKnob(int32_t diff) {
if (diff == 0) return false;
if (_page == 0) {
showPage(1);
return true;
}
// 页 1:旋钮滚运势正文。
// 下滚必须鍴制在内容高度内:lv_obj_scroll_by 不检查边界,
// 拧过头就是一屏黑底(看上去像死机)。到底后停在原地。
if (diff > 0) {
int32_t left = lv_obj_get_scroll_bottom(_page1); // 还能往下滚多少
if (left <= 0) return true;
lv_obj_scroll_by(_page1, 0, -(diff * 40 > left ? left : diff * 40), LV_ANIM_ON);
} else {
lv_obj_scroll_by(_page1, 0, -diff * 40, LV_ANIM_ON);
// 已经滚到顶还往上拧,就翻回星座页
if (lv_obj_get_scroll_y(_page1) <= 0) showPage(0);
}
return true;
}
void AstroApp::buildAppSettings(lv_obj_t* list) {
ui::buildSettingGroup(list, "星盘", nullptr);
}
} // namespace apps

View File

@ -0,0 +1,49 @@
#pragma once
// AstroApp.h —— 星盘
#include "../core/App.h"
namespace apps {
class AstroApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override;
void buildAppSettings(lv_obj_t* list) override;
private:
void showPage(uint8_t page);
void apply();
// 页 0:太阳/月亮星座;页 1:本月运势(可滚)
lv_obj_t* _page0 = nullptr;
lv_obj_t* _page1 = nullptr;
lv_obj_t* _icon = nullptr; // 空态时的星盘图标
lv_obj_t* _period = nullptr;
lv_obj_t* _sunRow = nullptr; // 符号 + 名字 一行(横排,居中)
lv_obj_t* _moonRow = nullptr;
lv_obj_t* _sunIcon = nullptr; // ♈~♓(黄道字形字体)
lv_obj_t* _moonIcon = nullptr;
lv_obj_t* _sunName = nullptr;
lv_obj_t* _moonName = nullptr;
lv_obj_t* _sunMeta = nullptr;
lv_obj_t* _moonMeta = nullptr;
lv_obj_t* _state = nullptr; // 页 0 底部状态行
lv_obj_t* _scroll = nullptr; // 页 1 滚动容器
lv_obj_t* _fMonth = nullptr; // 月份单独一行
lv_obj_t* _fTitle = nullptr;
lv_obj_t* _fBody = nullptr;
uint8_t _page = 0;
uint32_t _lastApplied = 0xFFFFFFFF; // 数据版本(用 updatedMs 判断)
uint32_t _lastTick = 0;
uint8_t _bindState = 0xFF; // 网络/服务端/绑定三态,变了才重画
};
extern AstroApp astroApp;
} // namespace apps

View File

@ -0,0 +1,310 @@
#include "ClockApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../hal/Display.h"
#include "../hal/Haptic.h"
#include "../config/AppConfig.h"
#include "../services/PlatformService.h"
#include <time.h>
#include <math.h>
namespace apps {
ClockApp clockApp;
static const AppMeta META = {"clock", "时钟", LV_SYMBOL_BELL, &icon_clock, 0xFF7A45, true, false};
const AppMeta& ClockApp::meta() const { return META; }
// ============================ 构建 ============================
void ClockApp::build(lv_obj_t* root) {
lv_obj_add_flag(root, LV_OBJ_FLAG_CLICKABLE);
_arc = ui::arc(root, 171, 2, theme::accent());
lv_obj_set_style_arc_opa(_arc, LV_OPA_20, LV_PART_MAIN);
// 环末端游标:一个小点跟着进度走,时间才有"在流动"的感觉
_tip = lv_obj_create(root);
lv_obj_set_size(_tip, 7, 7);
lv_obj_set_style_radius(_tip, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(_tip, theme::accent(), 0);
lv_obj_set_style_border_width(_tip, 0, 0);
lv_obj_clear_flag(_tip, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
_status = ui::label(root, "", FONT_TEXT, theme::textDim());
lv_obj_align(_status, LV_ALIGN_CENTER, 0, -108); // 与天气/星盘顶行同一基线
_big = ui::label(root, "--:--", FONT_NUM_XL, theme::text());
lv_obj_align(_big, LV_ALIGN_CENTER, 0, -6);
// 这一页没有任何常驻说明:表盘 + 状态行已经说清了"现在是什么状态",
// 底部再压一条"点击开始/暂停"只会把时间挤小。阶段结束才用 toast 反馈一次。
lv_obj_add_event_cb(root, [](lv_event_t* e) {
((ClockApp*)lv_event_get_user_data(e))->handleTap();
}, LV_EVENT_CLICKED, this);
lv_obj_add_event_cb(root, [](lv_event_t* e) {
((ClockApp*)lv_event_get_user_data(e))->handleLong();
}, LV_EVENT_LONG_PRESSED, this);
// 下半幅统一信息面板:只在专注模式(设定/倒计时)出现,
// 告诉用户当前手势怎么用;表盘态收起,屏上只有时间。
_panel = ui::bottomPanel(root);
lv_obj_t* hint = ui::label(_panel, "", FONT_TEXT, theme::textDim());
lv_obj_set_style_text_align(hint, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(hint, LV_ALIGN_TOP_MID, 0, 38);
lv_obj_set_user_data(_panel, hint);
lv_obj_add_flag(_panel, LV_OBJ_FLAG_HIDDEN);
_setMin = settings.getI("clk.work");
resetToClock();
}
void ClockApp::onEnter() {
_lastMs = millis();
// 已绑定就顺手跟服务端对一次时(内部有 1 分钟节流,进页面不会打接口)
svc::platform.syncTime();
refresh();
}
void ClockApp::handleTap() {
hal::hapticClick();
if (_state == State::Set) startRun();
else if (_state == State::Run) pauseRun(!_paused);
}
void ClockApp::handleLong() {
hal::hapticClick();
resetToClock();
}
// ============================ 圆环 ============================
void ClockApp::setRing(int pct, bool showTip) {
ui::arcSetPct(_arc, pct);
if (!showTip) {
lv_obj_add_flag(_tip, LV_OBJ_FLAG_HIDDEN);
return;
}
float deg = ((float)pct * 3.6f - 90.0f) * 0.01745329f;
lv_obj_align(_tip, LV_ALIGN_CENTER,
(int)lroundf(171.0f * cosf(deg)),
(int)lroundf(171.0f * sinf(deg)));
lv_obj_clear_flag(_tip, LV_OBJ_FLAG_HIDDEN);
}
// ============================ 状态迁移 ============================
int ClockApp::phaseMinutes() const {
switch (_phase) {
case Phase::Work: return settings.getI("clk.work");
case Phase::ShortBreak: return settings.getI("clk.short");
case Phase::LongBreak: return settings.getI("clk.long");
}
return 25;
}
const char* ClockApp::phaseName() const {
switch (_phase) {
case Phase::Work: return _paused ? "已暂停" : "专注中";
case Phase::ShortBreak: return _paused ? "已暂停" : "短休息";
case Phase::LongBreak: return _paused ? "已暂停" : "长休息";
}
return "";
}
void ClockApp::enterSet() {
_state = State::Set;
_paused = false;
refresh();
}
void ClockApp::startRun() {
_state = State::Run;
_paused = false;
_remainMs = (uint32_t)_setMin * 60UL * 1000UL;
_lastMs = millis();
refresh();
LOG("CLK", "start %d min", _setMin);
}
void ClockApp::pauseRun(bool paused) {
if (_state != State::Run) return;
_paused = paused;
_lastMs = millis();
refresh();
}
void ClockApp::resetToClock() {
bool wasRunning = (_state == State::Run);
_state = State::Clock;
_paused = false;
_phase = Phase::Work;
if (wasRunning) LOG("CLK", "cancelled");
refresh();
}
void ClockApp::finishPhase() {
_state = State::Clock;
_paused = false;
if (_phase == Phase::Work) {
_round++;
int rounds = settings.getI("clk.rounds");
_phase = (_round % rounds == 0) ? Phase::LongBreak : Phase::ShortBreak;
ui::toast(_root, _phase == Phase::LongBreak ? "该长休息了" : "休息一下", 2200);
} else {
_phase = Phase::Work;
ui::toast(_root, "开始下一轮", 1800);
}
// 计时结束给一段长震,比一声"叮"更符合这台设备的性格
hal::hapticBuzz();
_setMin = phaseMinutes();
_remainMs = (uint32_t)_setMin * 60UL * 1000UL;
if (settings.getB("clk.auto")) {
startRun();
} else {
refresh();
}
LOG("CLK", "phase -> %d", (int)_phase);
}
// ============================ 周期 ============================
void ClockApp::tickClock(uint32_t nowMs) {
(void)nowMs;
static uint32_t lastSec = 0xFFFFFFFF;
time_t t = time(nullptr);
tm* lt = localtime(&t);
if (!lt) return;
uint32_t secOfDay = lt->tm_hour * 3600 + lt->tm_min * 60 + lt->tm_sec;
if (secOfDay == lastSec) return;
lastSec = secOfDay;
refresh();
}
void ClockApp::tickRun(uint32_t nowMs) {
uint32_t dt = nowMs - _lastMs;
_lastMs = nowMs;
if (!_paused) {
if (dt >= _remainMs) {
_remainMs = 0;
refresh();
finishPhase();
return;
}
_remainMs -= dt;
}
static uint32_t acc = 0;
acc += dt;
if (acc >= 400) {
acc = 0;
refresh();
}
}
void ClockApp::onTick(uint32_t nowMs) {
switch (_state) {
case State::Clock:
tickClock(nowMs);
break;
case State::Set:
if (millis() - _setTouchedMs > 2500) resetToClock();
break;
case State::Run:
tickRun(nowMs);
break;
}
}
// ============================ 旋钮 ============================
bool ClockApp::onKnob(int32_t diff) {
if (_state == State::Run) return true; // 运行中旋钮无效,避免误触
if (_state == State::Clock) enterSet();
int v = _setMin + diff;
if (v < 1) v = 1;
if (v > 90) v = 90;
_setMin = v;
_setTouchedMs = millis();
refresh();
return true;
}
// ============================ 渲染 ============================
void ClockApp::refresh() {
char buf[24];
if (_state == State::Clock) {
time_t t = time(nullptr);
tm* lt = localtime(&t);
// 没有 RTC 芯片,时间只能靠 NTP。没联网时不做假,直接显示未对时。
bool synced = lt && (lt->tm_year + 1900) >= 2024;
if (synced) {
bool h24 = settings.getB("sys.cal24");
int h = lt->tm_hour;
if (!h24) {
h = h % 12;
if (h == 0) h = 12;
}
snprintf(buf, sizeof(buf), "%02d:%02d", h, lt->tm_min);
lv_label_set_text(_big, buf);
const char* wd[] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
lv_label_set_text_fmt(_status, "%s %d月%d日", wd[lt->tm_wday], lt->tm_mon + 1,
lt->tm_mday);
setRing(lt->tm_sec * 100 / 60, true);
} else {
lv_label_set_text(_big, "--:--");
lv_label_set_text(_status, "尚未校时");
setRing(0, false);
}
// 表盘不显示昵称:昵称是「我的」页的信息,压在时间下面只会分散注意力
ui::arcSetColor(_arc, theme::accent());
lv_obj_set_style_bg_color(_tip, theme::accent(), 0);
lv_obj_add_flag(_panel, LV_OBJ_FLAG_HIDDEN);
return;
}
if (_state == State::Set) {
snprintf(buf, sizeof(buf), "%02d:00", _setMin);
lv_label_set_text(_big, buf);
lv_label_set_text(_status, "专注时长");
setRing(_setMin * 100 / 90, false);
ui::arcSetColor(_arc, theme::accent());
lv_obj_clear_flag(_panel, LV_OBJ_FLAG_HIDDEN);
lv_label_set_text((lv_obj_t*)lv_obj_get_user_data(_panel), "旋钮调整时长 · 点击开始");
return;
}
// Run
uint32_t sec = (_remainMs + 999) / 1000;
snprintf(buf, sizeof(buf), "%02lu:%02lu", (unsigned long)(sec / 60), (unsigned long)(sec % 60));
lv_label_set_text(_big, buf);
lv_label_set_text(_status, phaseName());
uint32_t total = (uint32_t)phaseMinutes() * 60UL * 1000UL;
setRing(total ? (int)(_remainMs * 100ULL / total) : 0, true);
// 休息段也用主色:同一页面出现第二种强调色,看起来像两个不同的状态机
ui::arcSetColor(_arc, theme::accent());
lv_obj_set_style_bg_color(_tip, theme::accent(), 0);
// 专注模式的信息面板:手势说明常驻(这是用户点名要的),
// 暂停时说"点击继续",别让人点一下发现没反应又不敢再点。
lv_obj_clear_flag(_panel, LV_OBJ_FLAG_HIDDEN);
lv_label_set_text((lv_obj_t*)lv_obj_get_user_data(_panel),
_paused ? "点击继续 · 长按结束" : "点击暂停 · 长按结束");
}
// ============================ 设置 ============================
void ClockApp::buildAppSettings(lv_obj_t* list) {
ui::buildSettingGroup(list, "时钟", nullptr);
}
} // namespace apps

View File

@ -0,0 +1,66 @@
#pragma once
// ClockApp.h —— 时钟 + 番茄钟
//
// 一个应用两种身份,靠状态区分:
// CLOCK 显示实时时间,外环走秒
// SET 转动旋钮进入,显示设定时长,2.5s 无操作自动退回 CLOCK
// RUN 倒计时中,点击暂停,长按取消
//
// 这个"旋钮即调时"的交互是从原厂固件保留的核心手感:
// 不用进菜单,直接把旋钮拧到你想要的分钟数,按下开始。
#include "../core/App.h"
namespace apps {
class ClockApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override;
void buildAppSettings(lv_obj_t* list) override;
// 供其他模块查询状态(例如 Web 端)
bool running() const { return _state == State::Run; }
uint32_t remainSeconds() const { return _remainMs / 1000; }
// 触摸回调入口(LVGL 事件是 C 回调,不能直接访问私有成员)
void handleTap();
void handleLong();
private:
enum class State { Clock, Set, Run };
enum class Phase { Work, ShortBreak, LongBreak };
void enterSet();
void startRun();
void pauseRun(bool paused);
void resetToClock();
void finishPhase();
void tickClock(uint32_t nowMs);
void tickRun(uint32_t nowMs);
void refresh();
int phaseMinutes() const;
const char* phaseName() const;
State _state = State::Clock;
Phase _phase = Phase::Work;
bool _paused = false;
int _setMin = 25;
uint32_t _remainMs = 0;
uint32_t _lastMs = 0;
uint32_t _setTouchedMs = 0;
uint8_t _round = 0;
lv_obj_t* _panel = nullptr; // 下半幅统一信息面板(专注模式提示)
lv_obj_t* _arc = nullptr;
lv_obj_t* _tip = nullptr; // 环末端的游标点
lv_obj_t* _big = nullptr;
lv_obj_t* _status = nullptr;
void setRing(int pct, bool showTip);
};
extern ClockApp clockApp;
} // namespace apps

View File

@ -0,0 +1,385 @@
#include "GalleryApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../hal/Storage.h"
#include "../services/MediaSync.h"
#include "../config/AppConfig.h"
#include <SD_MMC.h>
#include <JPEGDEC.h>
#include <esp_heap_caps.h>
namespace apps {
GalleryApp galleryApp;
static const AppMeta META = {"gallery", "相册", LV_SYMBOL_IMAGE, &icon_gallery, 0x4FC3F7, true, true};
constexpr int PIX_W = SCREEN_W;
constexpr int PIX_H = SCREEN_H;
static uint16_t* s_pix = nullptr; // 解码目标:360×360 RGB565(PSRAM)
static uint8_t* s_file = nullptr; // 原始 JPEG 数据(PSRAM)
static size_t s_fileCap = 0;
static lv_img_dsc_t s_dsc;
// JPEGDEC 对象自身十几 KB,而 Arduino loop 任务栈只有 8KB,
// 放局部变量会直接爆栈(表现为"一进相册就重启")。这里是它唯一的家。
static JPEGDEC s_jpeg;
// JPEGDEC 按 MCU 块回调;iWidthUsed 才是有效宽度(边缘块会小于 iWidth)
static int jpegDrawCb(JPEGDRAW* d) {
if (!s_pix || !d->pPixels) return 0;
int w = d->iWidthUsed > 0 ? d->iWidthUsed : d->iWidth;
for (int y = 0; y < d->iHeight; y++) {
int dy = d->y + y;
if (dy < 0 || dy >= PIX_H) continue;
int dw = w;
int dx = d->x;
if (dx < 0) { dw += dx; dx = 0; }
if (dx + dw > PIX_W) dw = PIX_W - dx;
if (dw <= 0) continue;
memcpy(s_pix + dy * PIX_W + dx, d->pPixels + y * d->iWidth, (size_t)dw * 2);
}
return 1;
}
static bool ensureBuffers() {
if (!s_pix) {
s_pix = (uint16_t*)heap_caps_malloc(PIX_W * PIX_H * 2, MALLOC_CAP_SPIRAM);
if (!s_pix) s_pix = (uint16_t*)malloc(PIX_W * PIX_H * 2);
}
if (!s_file) {
s_fileCap = 320 * 1024;
s_file = (uint8_t*)heap_caps_malloc(s_fileCap, MALLOC_CAP_SPIRAM);
if (!s_file) s_file = (uint8_t*)malloc(s_fileCap);
}
if (!s_pix || !s_file) {
LOG("GAL", "buffer alloc failed (pix=%p file=%p)", s_pix, s_file);
return false;
}
return true;
}
// 圆形遮罩:圆屏上方形图会把四角露在外壳里,直接按圆裁掉最干净
static const int PHOTO_R = 171; // 相片圆半径,留出的 9px 黑边给"轮缘"进度环
static void applyCircleMask() {
const int cx = PIX_W / 2, cy = PIX_H / 2;
const int rIn = PHOTO_R - 1, rOut = PHOTO_R;
for (int y = 0; y < PIX_H; y++) {
int dy = y - cy;
uint16_t* row = s_pix + y * PIX_W;
int dy2 = dy * dy;
for (int x = 0; x < PIX_W; x++) {
int dx = x - cx;
int d2 = dx * dx + dy2;
if (d2 > rOut * rOut) {
row[x] = 0x0000;
} else if (d2 > rIn * rIn) {
// 边缘一像素压暗,等于廉价抗锯齿
uint16_t p = row[x];
row[x] = (uint16_t)(((p >> 1) & 0x7BEF) | ((p >> 2) & 0x39E7));
}
}
}
}
// LVGL 8 的渐变不能单独改两端透明度,这里用多条递进的半透黑叠出等效渐变,
// 目的是让白底照片上的标题和页码依然读得清。条数要够多(这里 13 条 × 10px),
// 否则每一档之间的透明度跳变会被眼睛读成"横向条带",比不做还难看。
static const int VEIL_N = 13;
static const int VEIL_H = 10;
static lv_obj_t* buildVeil(lv_obj_t* parent, bool top) {
const int N = VEIL_N, H = VEIL_H;
lv_obj_t* box = lv_obj_create(parent);
lv_obj_set_size(box, SCREEN_W, N * H);
if (top) lv_obj_align(box, LV_ALIGN_TOP_MID, 0, 0);
else lv_obj_align(box, LV_ALIGN_BOTTOM_MID, 0, 0);
lv_obj_set_style_bg_opa(box, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(box, 0, 0);
lv_obj_set_style_radius(box, 0, 0);
lv_obj_set_style_pad_all(box, 0, 0);
lv_obj_clear_flag(box, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
for (int i = 0; i < N; i++) {
lv_obj_t* s = lv_obj_create(box);
lv_obj_set_size(s, SCREEN_W, H);
lv_obj_set_pos(s, 0, top ? i * H : (N - 1 - i) * H);
int lvl = top ? i : (N - 1 - i);
lv_obj_set_style_bg_color(s, lv_color_black(), 0);
lv_obj_set_style_bg_opa(s, (lv_opa_t)(112 - lvl * 8), 0);
lv_obj_set_style_border_width(s, 0, 0);
lv_obj_set_style_radius(s, 0, 0);
lv_obj_clear_flag(s, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
}
return box;
}
const AppMeta& GalleryApp::meta() const { return META; }
void GalleryApp::build(lv_obj_t* root) {
_img = lv_img_create(root);
lv_obj_set_size(_img, SCREEN_W, SCREEN_H);
lv_obj_center(_img);
lv_obj_clear_flag(_img, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
// 顶部压暗,保证白底照片上的标题读得清;底部由统一信息面板负责
_topVeil = buildVeil(root, true);
// 不再画外圈进度弧:页码在信息面板里。
// 一圈橙色弧没有任何标签,看起来像"设备在加载",和"环 = 正在同步"的语言打架。
// 下半幅统一信息面板:图片名与页码都住在这里,
// 照片是主角,蒙层比别处更透(OPA_50),画面能一直延伸到底部;
// 文件名来自 TF 卡、字不可控,用媒体字体 + fitFont。
_panel = ui::bottomPanel(root, LV_OPA_50);
_title = ui::label(_panel, "", FONT_MEDIA, theme::text());
lv_obj_set_style_text_align(_title, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(_title, SCREEN_W - 72);
lv_label_set_long_mode(_title, LV_LABEL_LONG_DOT);
lv_obj_align(_title, LV_ALIGN_TOP_MID, 0, 22);
// 页码 + 同步进度可能带服务端文件名,不能走源码子集
_counter = ui::label(_panel, "", FONT_MEDIA, theme::textDim());
lv_obj_align(_counter, LV_ALIGN_TOP_MID, 0, 58);
_empty = ui::label(root, "TF 卡里还没有图片", FONT_TEXT, theme::textDim());
lv_obj_set_style_text_align(_empty, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_center(_empty);
}
void GalleryApp::onEnter() {
scan();
_lastSwitch = millis();
_syncPrompted = false;
svc::mediaSync.checkNow();
}
void GalleryApp::onExit() {
// 弹窗建在 lv_layer_top(),必须跟着应用一起走
_syncPrompt.close();
_syncPrompted = true;
}
// 探测结果回来后弹确认框;同步收尾后重扫 /pic(新旧照片集合变了)
void GalleryApp::maybeSyncPrompt() {
const bool busy = svc::mediaSync.busy();
if (_syncWasBusy && !busy) {
scan();
_dirty = true;
}
_syncWasBusy = busy;
if (_syncPrompted || _syncPrompt.visible()) return;
if (!svc::mediaSync.checkReady()) return;
_syncPrompted = true;
// 相册只关心图片(清单删除/改名类变更还是全量的,跟着提示走)
if ((svc::mediaSync.pendingPic() <= 0 && !svc::mediaSync.revChanged())
|| busy) return;
char l1[48];
int n = svc::mediaSync.pendingPic(); // 只报图片数:音乐有没有新文件不该出现在相册里
if (n > 0) snprintf(l1, sizeof(l1), "有 %d 张新图片", n);
else snprintf(l1, sizeof(l1), "相册清单有变更");
_syncPrompt.show(l1, "现在同步到 TF 卡?", [] { svc::mediaSync.confirmSync(); });
}
void GalleryApp::scan() {
_files.clear();
if (hal::storageReady()) {
auto names = hal::listDir("/pic");
LOG("GAL", "/pic has %u entries", (unsigned)names.size());
for (auto& n : names) {
String low = n;
low.toLowerCase();
if (low.endsWith(".jpg") || low.endsWith(".jpeg")) _files.push_back(n);
}
} else {
LOG("GAL", "storage not ready");
}
LOG("GAL", "%u pictures found", (unsigned)_files.size());
if (_files.empty()) {
showEmpty();
return;
}
if (_idx >= (int)_files.size()) _idx = 0;
lv_obj_add_flag(_empty, LV_OBJ_FLAG_HIDDEN);
load(_idx, false);
}
void GalleryApp::showEmpty() {
if (_empty) lv_obj_clear_flag(_empty, LV_OBJ_FLAG_HIDDEN);
if (_img) lv_obj_add_flag(_img, LV_OBJ_FLAG_HIDDEN);
if (_topVeil) lv_obj_add_flag(_topVeil, LV_OBJ_FLAG_HIDDEN);
if (_panel) lv_obj_add_flag(_panel, LV_OBJ_FLAG_HIDDEN); // 没图可看,面板一起收
if (_counter) lv_label_set_text(_counter, "");
if (_title) lv_label_set_text(_title, "相册");
}
bool GalleryApp::load(int idx, bool animate) {
if (idx < 0 || idx >= (int)_files.size()) return false;
if (!ensureBuffers()) return false;
String path = String("/pic/") + _files[idx];
hal::storageLock();
File f = SD_MMC.open(path, FILE_READ);
if (!f) {
hal::storageUnlock();
LOG("GAL", "open failed: %s", path.c_str());
return false;
}
size_t len = f.size();
size_t rd = 0;
if (len <= s_fileCap) rd = f.read(s_file, len);
f.close();
hal::storageUnlock();
if (rd == 0) {
LOG("GAL", "read failed or too big: %s (%u bytes)", path.c_str(), (unsigned)len);
return false;
}
for (int i = 0; i < PIX_W * PIX_H; i++) s_pix[i] = 0x0000;
JPEGDEC& jpeg = s_jpeg;
if (!jpeg.openRAM(s_file, (int)rd, jpegDrawCb)) {
LOG("GAL", "jpeg open failed: %s (%u bytes)", path.c_str(), (unsigned)rd);
return false;
}
// 本工程 LV_COLOR_16_SWAP=1,LVGL 的颜色在内存里是高字节在前。
// 注意:openRAM 会 memset 整个解码器状态,所以 setPixelType 必须放在它之后,
// 放在前面会被静默重置成小端,整张照片就会变成粉紫蓝绿。
jpeg.setPixelType(RGB565_BIG_ENDIAN);
int w = jpeg.getWidth(), h = jpeg.getHeight();
int ox = (PIX_W - w) / 2, oy = (PIX_H - h) / 2;
int ok = jpeg.decode(ox, oy, 0);
jpeg.close();
if (!ok) {
LOG("GAL", "jpeg decode failed: %s", path.c_str());
return false;
}
LOG("GAL", "loaded %s (%dx%d, %u bytes)", _files[idx].c_str(), w, h, (unsigned)rd);
applyCircleMask();
s_dsc.header.cf = LV_IMG_CF_TRUE_COLOR;
s_dsc.header.always_zero = 0;
s_dsc.header.w = PIX_W;
s_dsc.header.h = PIX_H;
s_dsc.data_size = PIX_W * PIX_H * 2;
s_dsc.data = (const uint8_t*)s_pix;
if (_img) {
// 同一个描述符反复用,必须让 LVGL 丢掉上一张的缓存
lv_img_cache_invalidate_src(&s_dsc);
lv_obj_clear_flag(_img, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_topVeil, LV_OBJ_FLAG_HIDDEN);
if (_panel) lv_obj_clear_flag(_panel, LV_OBJ_FLAG_HIDDEN);
lv_img_set_src(_img, &s_dsc);
lv_obj_invalidate(_img);
if (animate) {
lv_obj_set_style_opa(_img, LV_OPA_30, 0);
lv_obj_fade_in(_img, 220, 0);
}
}
_idx = idx;
_lastSwitch = millis();
if (_counter) lv_label_set_text_fmt(_counter, "%d / %d", _idx + 1, (int)_files.size());
if (_title) {
String name = _files[idx];
int dot = name.lastIndexOf('.');
if (dot > 0) name = name.substring(0, dot);
lv_label_set_text(_title, ui::fitFont(FONT_MEDIA, name).c_str());
}
return true;
}
// 启动自检:把解码链路跑一遍,只留日志,不动 UI
void GalleryApp::diagDecode() {
if (!hal::storageReady()) {
LOG("GAL", "diag: storage not ready");
return;
}
auto names = hal::listDir("/pic");
LOG("GAL", "diag: /pic has %u entries", (unsigned)names.size());
for (auto& n : names) {
String low = n;
low.toLowerCase();
if (!low.endsWith(".jpg") && !low.endsWith(".jpeg")) {
LOG("GAL", "diag: skip %s", n.c_str());
continue;
}
std::vector<String> keep;
keep.swap(_files);
_files.push_back(n);
bool ok = load(0, false);
LOG("GAL", "diag: decode %s -> %s", n.c_str(), ok ? "OK" : "FAIL");
_files.swap(keep);
return;
}
LOG("GAL", "diag: no jpeg in /pic");
}
void GalleryApp::onTick(uint32_t nowMs) {
maybeSyncPrompt();
// 同步期间:卡正被写,别再读图(否则主线程会和同步任务抢 SD 卡)。
// 顺带把页码位置让给进度——不然屏幕上一点动静都没有,很像卡死。
if (svc::mediaSync.busy()) {
if (nowMs - _lastSyncUi > 500) {
_lastSyncUi = nowMs;
if (_title) lv_label_set_text(_title, "正在同步");
if (_counter) lv_label_set_text(_counter,
ui::fitFont(FONT_MEDIA, svc::mediaSync.progress()).c_str());
}
return;
}
if (_files.size() < 2) return;
uint32_t interval = (uint32_t)settings.getI("gal.interval") * 1000UL;
if (interval == 0) return;
if (nowMs - _lastSwitch < interval) return;
int next;
if (settings.getI("gal.order") == 1) { // 随机
next = random(0, (long)_files.size());
if (next == _idx) next = (next + 1) % _files.size();
} else {
next = (_idx + 1) % _files.size();
}
load(next, true);
}
bool GalleryApp::onKnob(int32_t diff) {
if (svc::mediaSync.busy()) return true; // 同步期间不翻图
if (_files.empty()) return true;
int n = (int)_files.size();
int next = ((_idx + diff) % n + n) % n;
load(next, true);
return true;
}
bool GalleryApp::onGesture(Gesture g) {
if (_files.empty()) return true;
int n = (int)_files.size();
int next = _idx;
if (g == Gesture::SwipeLeft) next = (_idx + 1) % n;
else if (g == Gesture::SwipeRight) next = ((_idx - 1) % n + n) % n;
else return false;
load(next, true);
return true;
}
void GalleryApp::buildAppSettings(lv_obj_t* list) {
ui::buildSettingGroup(list, "相册", nullptr);
}
} // namespace apps

View File

@ -0,0 +1,57 @@
#pragma once
// GalleryApp.h —— 相册
//
// 读 TF 卡 /pic 下的 JPEG(原厂素材就是 360×360 baseline JPEG)。
// 旋钮转一下换一张,左右滑动也能翻,到点自动播放。
// 解码用 JPEGDEC 直接输出 RGB565 到 PSRAM,再交给 LVGL 当图像源——
// 这样不需要 LVGL 的图片解码器,也省掉把图转成 C 数组的步骤。
#include "../core/App.h"
#include "../ui/SyncPrompt.h"
#include <Arduino.h>
#include <vector>
namespace apps {
class GalleryApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onExit() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override;
bool onGesture(Gesture g) override;
void buildAppSettings(lv_obj_t* list) override;
int count() const { return (int)_files.size(); }
// 启动自检:解码第一张图并写日志(不上屏),用来远程判断相册链路是否通
void diagDecode();
private:
void scan();
bool load(int idx, bool animate);
void showEmpty();
std::vector<String> _files;
int _idx = 0;
lv_obj_t* _img = nullptr;
lv_obj_t* _panel = nullptr; // 下半幅统一信息面板(图片名/页码)
lv_obj_t* _counter = nullptr;
lv_obj_t* _empty = nullptr;
lv_obj_t* _title = nullptr;
lv_obj_t* _topVeil = nullptr;
uint32_t _lastSwitch = 0;
uint32_t _lastSyncUi = 0;
bool _dirty = true;
// TF 卡同步:进入时探测一次,有待同步就弹确认框;同步完成后重扫相册
ui::SyncPrompt _syncPrompt;
bool _syncPrompted = false;
bool _syncWasBusy = false;
void maybeSyncPrompt();
};
extern GalleryApp galleryApp;
} // namespace apps

View File

@ -0,0 +1,648 @@
#include "MusicApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../hal/Haptic.h"
#include "../hal/Storage.h"
#include "../services/MusicLibrary.h"
#include "../services/AudioLink.h"
#include "../services/MediaSync.h"
#include "../config/AppConfig.h"
#include <SD_MMC.h>
#include <JPEGDEC.h>
#include <esp_heap_caps.h>
#include <string.h>
#include <math.h>
namespace apps {
MusicApp musicApp;
static const AppMeta META = {"music", "音乐", LV_SYMBOL_AUDIO, &icon_music, 0x4DD6A8, true, true};
const AppMeta& MusicApp::meta() const { return META; }
// ================================================================ 唱片画布
// 整张唱片在 PSRAM 里合成一次:黑胶底纹 + 盘心封面(或厂标色芯),再交给
// lv_img 旋转。TRUE_COLOR(无 alpha)画布的旋转路径是 LVGL 软件变换的主干道,
// 不踩"TRUE_COLOR_ALPHA 缩放不渲染"的坑。
static const int DISC = 240; // 唱片直径
static const int DISC_R = DISC / 2;
static const int CV = 168; // 封面解码暂存画布
static uint16_t* s_discPix = nullptr; // 唱片成品(PSRAM)
static uint16_t* s_cvPix = nullptr; // 封面解码暂存(PSRAM)
static uint8_t* s_covBuf = nullptr; // 封面 JPEG 原始数据(PSRAM)
static lv_img_dsc_t s_dsc;
// JPEGDEC 对象十几 KB,绝不能放任务栈(相册已经踩过一次)
static JPEGDEC s_jpeg;
// RGB565 + LV_COLOR_16_SWAP:LVGL 的像素在内存里高字节在前,
// 所以算好普通域的值后要交换字节再落进画布(相册靠 JPEGDEC 的
// RGB565_BIG_ENDIAN 得到同样效果,这里是手工合成,得自己做)。
static inline uint16_t rgb565(uint8_t r, uint8_t g, uint8_t b) {
uint16_t v = (uint16_t)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));
return (uint16_t)((v << 8) | (v >> 8));
}
// 画布里的像素 → 普通域分量(做明暗运算前先换回来)
static inline void rgb565Unpack(uint16_t v, uint8_t& r, uint8_t& g, uint8_t& b) {
uint16_t n = (uint16_t)((v << 8) | (v >> 8));
r = (n >> 8) & 0xF8;
g = (n >> 3) & 0xFC;
b = (n << 3) & 0xF8;
}
// 封面解码回调:裁进 CV 画布
static int coverDrawCb(JPEGDRAW* d) {
if (!s_cvPix || !d->pPixels) return 0;
int w = d->iWidthUsed > 0 ? d->iWidthUsed : d->iWidth;
for (int y = 0; y < d->iHeight; y++) {
int dy = d->y + y;
if (dy < 0 || dy >= CV) continue;
int dw = w, dx = d->x;
if (dx < 0) { dw += dx; dx = 0; }
if (dx + dw > CV) dw = CV - dx;
if (dw <= 0) continue;
memcpy(s_cvPix + dy * CV + dx, d->pPixels + y * d->iWidth, (size_t)dw * 2);
}
return 1;
}
static bool ensureDiscBuffers() {
if (!s_discPix)
s_discPix = (uint16_t*)heap_caps_malloc(DISC * DISC * 2, MALLOC_CAP_SPIRAM);
if (!s_cvPix)
s_cvPix = (uint16_t*)heap_caps_malloc(CV * CV * 2, MALLOC_CAP_SPIRAM);
if (!s_covBuf)
s_covBuf = (uint8_t*)heap_caps_malloc(512 * 1024, MALLOC_CAP_SPIRAM);
return s_discPix && s_cvPix && s_covBuf;
}
// 黑胶底纹:同心槽纹 + 两道分曲细缝 + 斜向高光
static void paintVinyl() {
const float sheenDeg[2] = {138.0f, 318.0f};
// 圆外的像素刷成页面底色:TRUE_COLOR 没有 alpha,留黑会露出一个方块
const uint16_t outside = rgb565(10, 12, 16);
for (int y = 0; y < DISC; y++) {
for (int x = 0; x < DISC; x++) {
int dx = x - DISC_R + 1, dy = y - DISC_R + 1;
float r = sqrtf((float)dx * dx + (float)dy * dy);
uint8_t rr = 0, gg = 0, bb = 0;
if (r > DISC_R - 2) {
s_discPix[y * DISC + x] = outside;
continue;
}
if (r > 112) { rr = 46; gg = 50; bb = 58; } // 外缘亮圈
else if (r > 108) { rr = 14; gg = 15; bb = 18; } // 分曲缝
else if (r > 96) { rr = 14; gg = 15; bb = 18; } // 分曲缝
else {
// 槽纹:每 3px 一道微亮的细环
int gro = (int)r % 3;
rr = gro == 0 ? 26 : 18;
gg = gro == 0 ? 28 : 19;
bb = gro == 0 ? 33 : 23;
// 高光:两条对角的柔光带。角度必须归一到 [0,360)——
// atan2f 返回 [-180,180],不归一的话 |deg-sd| 会超过 360,
// 下面的"360-dd"就变成负数,dd<26 恒真、亮度系数溢出成一片亮斑。
float deg = atan2f((float)dy, (float)dx) * 57.29578f;
if (deg < 0) deg += 360.0f;
for (float sd : sheenDeg) {
float dd = fabsf(deg - sd);
if (dd > 180) dd = 360 - dd;
if (dd < 26 && r > 62 && r < 110) {
float k = (1.0f - dd / 26) * 0.55f;
if (k < 0) k = 0;
rr = (uint8_t)(rr + (72 - rr) * k);
gg = (uint8_t)(gg + (76 - gg) * k);
bb = (uint8_t)(bb + (86 - bb) * k);
}
}
}
s_discPix[y * DISC + x] = rgb565(rr, gg, bb);
}
}
}
// 盘心贴封面:中心裁方、圆掩膜、一圈细压边
static void pasteCover() {
const int ART_R = 72; // 封面圆半径
const int cx = DISC_R - 1, cy = DISC_R - 1;
// 从 CV 画布中心裁最大的方形,缩到 2*ART_R
int crop = CV;
// CV 里非空区域按内容居中,这里简单取整幅画布的中心方
float stepPx = (float)crop / (2 * ART_R);
for (int y = -ART_R; y <= ART_R; y++) {
for (int x = -ART_R; x <= ART_R; x++) {
float d = sqrtf((float)x * x + (float)y * y);
if (d > ART_R) continue;
int sx = (int)((x + ART_R) * stepPx);
int sy = (int)((y + ART_R) * stepPx);
if (sx >= CV) sx = CV - 1;
if (sy >= CV) sy = CV - 1;
uint16_t p = s_cvPix[sy * CV + sx];
// 边缘两圈逐级压暗,等于廉价抗锯齿
uint8_t r, g, b;
rgb565Unpack(p, r, g, b);
if (d > ART_R - 1.5f) { r >>= 1; g >>= 1; b >>= 1; }
else if (d > ART_R - 2.5f) { r = (uint8_t)(r * 3 / 4); g = (uint8_t)(g * 3 / 4); b = (uint8_t)(b * 3 / 4); }
s_discPix[(cy + y) * DISC + (cx + x)] = rgb565(r, g, b);
}
}
// 封面外的细压边环
for (int a = 0; a < 360; a++) {
float rad = a * 0.0174533f;
int px = cx + (int)lroundf(cosf(rad) * (ART_R + 2));
int py = cy + (int)lroundf(sinf(rad) * (ART_R + 2));
if (px >= 0 && px < DISC && py >= 0 && py < DISC)
s_discPix[py * DISC + px] = rgb565(52, 57, 66);
}
}
// 无封面:画一枚强调色的"厂标"圆芯,唱片不显得秃
static void paintLabel(uint32_t accentHex) {
const int cx = DISC_R - 1, cy = DISC_R - 1;
uint8_t ar = (accentHex >> 16) & 0xFF, ag = (accentHex >> 8) & 0xFF, ab = accentHex & 0xFF;
for (int y = -30; y <= 30; y++)
for (int x = -30; x <= 30; x++) {
float d = sqrtf((float)x * x + (float)y * y);
if (d > 30) continue;
uint8_t k = d > 28 ? 60 : 100;
s_discPix[(cy + y) * DISC + (cx + x)] =
rgb565((uint8_t)(ar * k / 100), (uint8_t)(ag * k / 100), (uint8_t)(ab * k / 100));
}
// 中轴小孔
for (int y = -4; y <= 4; y++)
for (int x = -4; x <= 4; x++) {
if (x * x + y * y <= 16)
s_discPix[(cy + y) * DISC + (cx + x)] = rgb565(8, 9, 11);
}
}
// ================================================================ UI
void MusicApp::build(lv_obj_t* root) {
lv_obj_add_flag(root, LV_OBJ_FLAG_CLICKABLE);
_arc = ui::arc(root, 176, 4, theme::accent());
lv_obj_set_style_arc_opa(_arc, LV_OPA_20, LV_PART_MAIN);
lv_obj_set_style_arc_opa(_arc, LV_OPA_80, LV_PART_INDICATOR);
_disc = lv_img_create(root);
lv_obj_set_size(_disc, DISC, DISC);
lv_obj_align(_disc, LV_ALIGN_CENTER, 0, 0);
lv_img_set_pivot(_disc, DISC_R, DISC_R);
lv_img_set_antialias(_disc, true);
lv_obj_clear_flag(_disc, LV_OBJ_FLAG_CLICKABLE);
// 盘心热区:透明圆,盖在唱片上。只有点它才切播放/停止——
// 整页当按钮时,上滑菜单/下拉设置松手也会发 CLICKED,音乐就自己乱停。
_center = lv_obj_create(root);
lv_obj_set_size(_center, 150, 150);
lv_obj_center(_center);
lv_obj_set_style_bg_opa(_center, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(_center, 0, 0);
lv_obj_set_style_radius(_center, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_pad_all(_center, 0, 0);
lv_obj_clear_flag(_center, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_center, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(_center, [](lv_event_t* e) {
MusicApp* m = (MusicApp*)lv_event_get_user_data(e);
lv_indev_get_point(lv_indev_get_act(), &m->_press);
}, LV_EVENT_PRESSED, this);
lv_obj_add_event_cb(_center, [](lv_event_t* e) {
MusicApp* m = (MusicApp*)lv_event_get_user_data(e);
lv_point_t p;
lv_indev_get_point(lv_indev_get_act(), &p);
// 位移超过阈值当滑动(上滑/下拉/横向切页),不算点击
if (abs(p.x - m->_press.x) + abs(p.y - m->_press.y) > 48) return;
m->handleTap();
}, LV_EVENT_CLICKED, this);
lv_obj_add_event_cb(_center, [](lv_event_t* e) {
((MusicApp*)lv_event_get_user_data(e))->handleLong();
}, LV_EVENT_LONG_PRESSED, this);
// 下半幅统一信息面板:歌名和时长都住在这里,唱片区域不再压任何胶囊。
// 唱片是这一页的主角,所以蒙层比别处更透(OPA_50):黑胶的槽纹能透出来,
// 又刚好压得住白字。歌名来自 ID3 标签、字不可控,用 2500 常用字的媒体字体。
_panel = ui::bottomPanel(root, LV_OPA_50);
_title = ui::label(_panel, "", FONT_MEDIA, theme::text());
lv_obj_set_style_text_align(_title, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(_title, SCREEN_W - 72);
lv_label_set_long_mode(_title, LV_LABEL_LONG_DOT);
lv_obj_align(_title, LV_ALIGN_TOP_MID, 0, 22);
_time = ui::label(_panel, "", FONT_TEXT, theme::textDim());
lv_obj_align(_time, LV_ALIGN_TOP_MID, 0, 58);
// 这一页不用任何常驻提示:唱片 + 时间就是全部信息。
_empty = ui::label(root, "", FONT_TEXT, theme::textDim());
lv_obj_set_style_text_align(_empty, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_center(_empty);
buildSyncOverlay(root);
// 这一页不绑长按:以前长按 = 重扫曲库,但那是排障手段——
// 手上出汗压一下就把曲库清空重扫,屏上闪一条"正在扫描 TF 卡",像个 bug。
// 曲库在同步完成后会自己重扫,真需要手动重扫走串口。
}
// ================================================================ 同步进度层
// 同步是"用户必须等它做完"的操作:期间写 TF 卡、删多余文件,
// 这时候让他继续切歌只会读到半截文件。所以同步期间盖一层遮罩,
// 明说进度(3/10 歌名),做完自动收起。
//
// 这一层也是"点同步没反应"的解药:以前点完什么都没有,
// 用户以为死机就反复点,反而叠了多次请求。
void MusicApp::buildSyncOverlay(lv_obj_t* root) {
_syncMask = lv_obj_create(root);
lv_obj_set_size(_syncMask, SCREEN_W, SCREEN_H);
lv_obj_center(_syncMask);
lv_obj_set_style_bg_color(_syncMask, lv_color_hex(0x000000), 0);
lv_obj_set_style_bg_opa(_syncMask, LV_OPA_80, 0);
lv_obj_set_style_border_width(_syncMask, 0, 0);
lv_obj_set_style_radius(_syncMask, 0, 0);
lv_obj_set_style_pad_all(_syncMask, 0, 0);
lv_obj_clear_flag(_syncMask, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_syncMask, LV_OBJ_FLAG_CLICKABLE); // 吃掉点击:同步期间别乱动
lv_obj_add_flag(_syncMask, LV_OBJ_FLAG_HIDDEN);
_syncTitle = ui::label(_syncMask, "正在同步音乐", FONT_TEXT, theme::text());
lv_obj_align(_syncTitle, LV_ALIGN_CENTER, 0, -44);
_syncMsg = ui::label(_syncMask, "", FONT_MEDIA, theme::textDim());
lv_obj_set_width(_syncMsg, 280);
lv_label_set_long_mode(_syncMsg, LV_LABEL_LONG_DOT);
lv_obj_set_style_text_align(_syncMsg, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(_syncMsg, LV_ALIGN_CENTER, 0, 4);
_syncBar = lv_bar_create(_syncMask);
lv_obj_set_size(_syncBar, 220, 6);
lv_obj_align(_syncBar, LV_ALIGN_CENTER, 0, 46);
lv_bar_set_range(_syncBar, 0, 100);
lv_bar_set_value(_syncBar, 0, LV_ANIM_OFF);
lv_obj_set_style_bg_color(_syncBar, theme::surfaceHi(), LV_PART_MAIN);
lv_obj_set_style_bg_opa(_syncBar, LV_OPA_COVER, LV_PART_MAIN);
lv_obj_set_style_radius(_syncBar, LV_RADIUS_CIRCLE, LV_PART_MAIN);
lv_obj_set_style_bg_color(_syncBar, theme::accent(), LV_PART_INDICATOR);
lv_obj_set_style_bg_opa(_syncBar, LV_OPA_COVER, LV_PART_INDICATOR);
lv_obj_set_style_radius(_syncBar, LV_RADIUS_CIRCLE, LV_PART_INDICATOR);
}
void MusicApp::showSyncOverlay(bool on) {
if (!_syncMask) return;
if (on) {
lv_label_set_text(_syncMsg, "正在检查清单…");
lv_bar_set_value(_syncBar, 0, LV_ANIM_OFF);
lv_obj_clear_flag(_syncMask, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_syncMask);
} else {
lv_obj_add_flag(_syncMask, LV_OBJ_FLAG_HIDDEN);
}
}
void MusicApp::startSync() {
_syncPrompt.close();
_syncing = true;
_syncSeen = false;
_syncStart = millis();
showSyncOverlay(true);
svc::mediaSync.confirmSync();
LOG("MUS", "sync requested");
}
// "3/10 歌名" → 30。拿不到数字就返回 -1(进度未知)
static int progressPct(const String& p) {
if (p.length() == 0) return -1;
int slash = p.indexOf('/');
if (slash <= 0) return -1;
int a = p.substring(0, slash).toInt();
int b = p.substring(slash + 1).toInt();
if (b <= 0) return -1;
int pct = a * 100 / b;
return pct < 0 ? 0 : (pct > 100 ? 100 : pct);
}
void MusicApp::onEnter() {
// 同步检查与曲库扫描并行:有没有新文件,弹不弹窗,onTick 里看结果
_syncPrompted = false;
svc::mediaSync.checkNow();
if (!svc::musicLib.ready() && !svc::musicLib.scanning()) {
svc::musicLib.scanAsync();
_waitLib = true;
}
if (!ensureDiscBuffers()) {
showEmpty("内存不足", "");
return;
}
if (svc::musicLib.ready() && svc::musicLib.count() > 0) {
if (_idx >= svc::musicLib.count()) _idx = 0;
loadTrack(_idx);
} else if (svc::musicLib.scanning() || _waitLib) {
showEmpty("正在扫描 TF 卡", "");
} else {
showEmpty("TF 卡里还没有音乐", "");
}
}
void MusicApp::onExit() {
// 弹窗建在 lv_layer_top(),必须跟着应用一起走,否则会盖住别的界面
_syncPrompt.close();
_syncPrompted = true;
// 同步还在跑:把进度层收掉,但保留 _syncing,回来时能接着显示结果
showSyncOverlay(false);
}
// 探测结果回来后弹确认框;用户点了「同步」交给 MediaSync,曲库刷新由它负责
void MusicApp::maybeSyncPrompt() {
if (_syncPrompted || _syncPrompt.visible()) return;
if (!svc::mediaSync.checkReady()) return;
_syncPrompted = true;
// 音乐只关心音乐(清单删除/改名类变更还是全量的,跟着提示走)
if ((svc::mediaSync.pendingMusic() <= 0 && !svc::mediaSync.revChanged())
|| svc::mediaSync.busy()) return;
char l1[48];
int n = svc::mediaSync.pendingMusic(); // 只报音乐数:图片的变更归相册管
if (n > 0) snprintf(l1, sizeof(l1), "有 %d 首新音乐", n);
else snprintf(l1, sizeof(l1), "文件清单有变更");
_syncPrompt.show(l1, "现在同步到 TF 卡?", [this] { startSync(); });
}
void MusicApp::showEmpty(const char* l1, const char* l2) {
String s = String(l1);
if (l2 && strlen(l2)) s += String("\n") + l2;
lv_label_set_text(_empty, s.c_str());
lv_obj_clear_flag(_empty, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_disc, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_panel, LV_OBJ_FLAG_HIDDEN); // 没歌可放,面板也一起收起来
ui::arcSetPct(_arc, 0);
setPlaying(false);
}
// 同步进度:每帧读一下 MediaSync 的状态(它只写状态,不碰 LVGL),
// 把 "3/10 歌名" 翻成进度条 + 一行文字。任务结束的那一刻收遮罩并给一句结论。
void MusicApp::tickSync(uint32_t nowMs) {
// 别人发起的同步(串口 force / 相册页里确认的)也接过来显示进度:
// 写卡期间不管从哪儿触发,界面上都得看得见。
if (!_syncing && svc::mediaSync.syncingJob()) {
_syncing = true;
_syncSeen = true;
_syncStart = nowMs;
showSyncOverlay(true);
}
if (!_syncing) return;
if (svc::mediaSync.busy()) {
_syncSeen = true;
lv_obj_clear_flag(_syncMask, LV_OBJ_FLAG_HIDDEN);
const String& p = svc::mediaSync.progress();
int pct = progressPct(p);
if (pct >= 0) {
lv_bar_set_value(_syncBar, pct, LV_ANIM_ON);
// 进度行里的文件名来自服务端清单,同样要过一遍字体
lv_label_set_text(_syncMsg, ui::fitFont(FONT_MEDIA, p).c_str());
} else {
lv_label_set_text(_syncMsg, "正在检查清单…");
}
if (nowMs - _syncStart > 3UL * 60UL * 1000UL) { // 3 分钟兜底
_syncing = false;
_syncSeen = false;
showSyncOverlay(false);
ui::toast(_root, "同步超时,可再试一次", 2000);
}
return;
}
// 还没见到任务起来:confirmSync 是排队的(可能正在等前一个探测任务收尾),
// 任务栈申请失败时 MediaSync 自己也会退避重试。给它 8 秒再下结论,
// 别把"马上就好"报成失败。
if (!_syncSeen && nowMs - _syncStart < 8000) return;
const String& p = svc::mediaSync.progress();
bool ok = (p == "synced") || (p == "up to date");
bool failed = (svc::mediaSync.state() == svc::SyncState::Failed);
bool sawJob = _syncSeen;
_syncing = false;
_syncSeen = false;
showSyncOverlay(false);
if (ok) {
ui::toast(_root, "同步完成", 1800);
} else if (failed) {
const char* e = svc::mediaSync.lastError();
ui::toast(_root, (e && *e) ? e : "同步失败", 2200);
} else if (sawJob) {
ui::toast(_root, "同步已结束", 1800); // 任务跑过但没给出结论
} else {
ui::toast(_root, "同步未开始,稍后自动重试", 2200);
}
LOG("MUS", "sync finished: ok=%d failed=%d progress=%s", (int)ok, (int)failed, p.c_str());
}
bool MusicApp::loadTrack(int idx) {
int n = svc::musicLib.count();
if (n <= 0) return false;
idx = ((idx % n) + n) % n;
_idx = idx;
svc::Track t = svc::musicLib.at(idx);
lv_obj_clear_flag(_empty, LV_OBJ_FLAG_HIDDEN); // 换曲期间先清状态
composeDisc(t.coverLen > 0 && t.coverJpeg);
s_dsc.header.cf = LV_IMG_CF_TRUE_COLOR;
s_dsc.header.always_zero = 0;
s_dsc.header.w = DISC;
s_dsc.header.h = DISC;
s_dsc.data_size = DISC * DISC * 2;
s_dsc.data = (const uint8_t*)s_discPix;
lv_img_cache_invalidate_src(&s_dsc);
lv_img_set_src(_disc, &s_dsc);
lv_img_set_angle(_disc, 0);
lv_obj_clear_flag(_disc, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_panel, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_empty, LV_OBJ_FLAG_HIDDEN);
_posSec = 0;
refreshMeta();
refreshProgress();
// 正在播的时候换曲,得让副控换码流(否则 UI 变了声音还是上一首)
if (_playing) svc::audioLink.play(t.path);
LOG("MUS", "track %d: %s - %s", idx, t.title.c_str(), t.artist.c_str());
return true;
}
void MusicApp::composeDisc(bool wantCover) {
paintVinyl();
bool coverOk = false;
if (wantCover) {
svc::Track t = svc::musicLib.at(_idx);
size_t rd = svc::readCover(t, s_covBuf, 512 * 1024);
if (rd > 4) {
if (s_jpeg.openRAM(s_covBuf, (int)rd, coverDrawCb)) {
// openRAM 会 memset 整个解码器状态,setPixelType 必须在它之后
s_jpeg.setPixelType(RGB565_BIG_ENDIAN);
int w = s_jpeg.getWidth(), h = s_jpeg.getHeight();
// 封面太大就分级降采样,省内存也省时间
int opt = 0;
if (w > 600 || h > 600) opt = JPEG_SCALE_QUARTER;
else if (w > 300 || h > 300) opt = JPEG_SCALE_HALF;
memset(s_cvPix, 0, CV * CV * 2);
int ox = (CV - w / (opt == JPEG_SCALE_QUARTER ? 4 : (opt == JPEG_SCALE_HALF ? 2 : 1))) / 2;
int oy = (CV - h / (opt == JPEG_SCALE_QUARTER ? 4 : (opt == JPEG_SCALE_HALF ? 2 : 1))) / 2;
coverOk = s_jpeg.decode(ox, oy, opt) == 1;
s_jpeg.close();
}
}
if (coverOk) pasteCover();
else LOG("MUS", "cover decode failed, fallback vinyl");
}
if (!coverOk) paintLabel(META.accent);
}
void MusicApp::refreshMeta() {
svc::Track t = svc::musicLib.at(_idx);
String s = t.title;
if (t.artist.length()) s += " - " + t.artist;
// ID3 是外部文本:字体子集里没有的字直接丢,别在屏上排一串空心方块
lv_label_set_text(_title, ui::fitFont(FONT_MEDIA, s).c_str());
char buf[16];
if (t.durationSec > 0) {
snprintf(buf, sizeof(buf), "%u:%02u / %u:%02u",
(unsigned)(_posSec / 60), (unsigned)(_posSec % 60),
(unsigned)(t.durationSec / 60), (unsigned)(t.durationSec % 60));
} else {
snprintf(buf, sizeof(buf), "%u:%02u", (unsigned)(_posSec / 60), (unsigned)(_posSec % 60));
}
lv_label_set_text(_time, buf);
}
void MusicApp::refreshProgress() {
svc::Track t = svc::musicLib.at(_idx);
int pct = 0;
if (t.durationSec > 0) pct = (int)(_posSec * 100 / t.durationSec);
ui::arcSetPct(_arc, pct);
if (t.durationSec > 0) ui::arcSetColor(_arc, theme::accent());
}
void MusicApp::setPlaying(bool on) {
if (_playing == on) return;
_playing = on;
// 真正出声在副控:主控只把 MP3 码流推过去(见 AudioLink.h)
if (on) {
svc::Track t = svc::musicLib.at(_idx);
if (svc::audioLink.active()) svc::audioLink.setPaused(false);
else svc::audioLink.play(t.path);
} else {
svc::audioLink.setPaused(true);
}
if (on) {
if (!_spin) {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _disc);
lv_anim_set_exec_cb(&a, [](void* var, int32_t v) {
lv_img_set_angle((lv_obj_t*)var, v);
});
lv_anim_set_values(&a, 0, 3600);
lv_anim_set_time(&a, 2600); // ≈23 转/分,比真唱片快,转起来才有生命感
lv_anim_set_path_cb(&a, lv_anim_path_linear);
lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
lv_anim_start(&a);
_spin = true;
}
} else if (_spin) {
lv_anim_del(_disc, nullptr);
_spin = false;
lv_img_set_angle(_disc, lv_img_get_angle(_disc)); // 停在当前角度
}
}
void MusicApp::handleTap() {
if (_syncing) return; // 同步期间遮罩在,别让点击穿到播放
hal::hapticClick();
if (svc::musicLib.count() == 0) {
onEnter(); // 也许扫描刚完成
return;
}
setPlaying(!_playing);
}
void MusicApp::handleLong() {
if (_syncing) return;
hal::hapticClick();
svc::musicLib.scanAsync();
showEmpty("正在扫描 TF 卡", "");
}
// 串口 'Y':走和用户点「同步」完全一样的路径(关弹窗 + 进度层 + 收尾提示),
// 只有这样调试看到的才是真实体验;直接 mediaSync.force() 会绕过界面。
void MusicApp::forceSync() { startSync(); }
void MusicApp::onTick(uint32_t nowMs) {
tickSync(nowMs);
maybeSyncPrompt();
// 同步完成后 MediaSync 会发起曲库重扫:这里挂上等待,一到货自动换歌单
if (!_waitLib && svc::musicLib.scanning()) _waitLib = true;
// 等后台扫描完成,一到货就换上第一首
if (_waitLib && svc::musicLib.ready()) {
_waitLib = false;
if (svc::musicLib.count() > 0) loadTrack(0);
else showEmpty("TF 卡里还没有音乐", "");
return;
}
if (!_playing || svc::musicLib.count() == 0) return;
if (nowMs - _lastTick < 1000) return;
_lastTick = nowMs;
_posSec++;
svc::Track t = svc::musicLib.at(_idx);
if (t.durationSec > 0 && _posSec >= t.durationSec) {
// 播放模式:0=顺序,1=随机(设置 → 音乐 → 播放模式)
int n = svc::musicLib.count();
int next = _idx + 1;
if (settings.getI("mus.mode") == 1 && n > 1) {
next = (int)random(0, (long)n);
if (next == _idx) next = (next + 1) % n;
}
loadTrack(next);
return;
}
refreshMeta();
refreshProgress();
}
bool MusicApp::dumpDisc() {
if (!s_discPix) return false;
Serial.printf("DISC %d %d %u\n", DISC, DISC, (unsigned)(DISC * DISC * 2));
Serial.write((const uint8_t*)s_discPix, DISC * DISC * 2);
Serial.flush();
return true;
}
bool MusicApp::onKnob(int32_t diff) {
if (_syncing) return true; // 同步期间不切歌:卡上的文件正在被改写
if (svc::musicLib.count() == 0) return true;
hal::hapticTick();
loadTrack(_idx + (int)diff);
return true;
}
void MusicApp::buildAppSettings(lv_obj_t* list) {
ui::buildSettingGroup(list, "音乐", nullptr);
}
} // namespace apps

View File

@ -0,0 +1,78 @@
#pragma once
// MusicApp.h —— 本地唱片播放机
//
// 方向(用户已定):读 TF 卡本地音乐 + 内嵌封面,做成"唱片机":
// 中央黑胶唱片(有封面时封面嵌在盘心),播放时旋转;
// 旋钮切歌,**点击盘心**播放/暂停,外圈进度环。
// 为什么只认盘心:LVGL 对滑动手势松手时也会发 CLICKED,
// 整页可点会把"上滑菜单 / 下拉设置"全都变成误触播放/停止。
// 发声链路(MP3 软解 → 输出)在服务平台 M5 接入;在此之前位置随时间推进,
// 作为交互的完整预演。
#include "../core/App.h"
#include "../ui/SyncPrompt.h"
namespace apps {
class MusicApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onExit() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override;
void buildAppSettings(lv_obj_t* list) override;
void handleTap();
void handleLong();
void forceSync(); // 串口调试:等同于点确认框里的「同步」
// 调试:把合成好的唱片画布原样用串口吐出来(校验"画布本身"与"LVGL 显示"谁有问题)
bool dumpDisc();
private:
void refreshMeta(); // 标题/歌手/时间文字
void refreshProgress();
bool loadTrack(int idx); // 换曲:重绘唱片面
void setPlaying(bool on);
void composeDisc(bool hasCover);
void showEmpty(const char* line1, const char* line2);
lv_obj_t* _arc = nullptr; // 外圈进度环
lv_obj_t* _disc = nullptr; // 唱片(PSRAM 画布)
lv_obj_t* _center = nullptr; // 盘心热区(唯一响应"播放/停止"的地方)
lv_point_t _press{0, 0}; // 按下坐标,用于区分点击与滑动
lv_obj_t* _panel = nullptr; // 下半幅统一信息面板(歌名/时长)
lv_obj_t* _title = nullptr; // 歌名
lv_obj_t* _time = nullptr;
lv_obj_t* _empty = nullptr;
// 同步进度层(同步期间盖住整屏,做完自己收)
lv_obj_t* _syncMask = nullptr;
lv_obj_t* _syncTitle = nullptr;
lv_obj_t* _syncMsg = nullptr;
lv_obj_t* _syncBar = nullptr;
int _idx = 0;
bool _playing = false;
bool _spin = false; // 旋转动画是否在跑
uint32_t _posSec = 0;
uint32_t _lastTick = 0;
bool _waitLib = false; // 已发起后台扫描
// TF 卡同步:进入时探测一次,有待同步就弹确认框(用户同意才写卡)
ui::SyncPrompt _syncPrompt;
bool _syncPrompted = false;
bool _syncing = false; // 用户已确认,正在同步
bool _syncSeen = false; // 见过任务真的跑起来(区分"还没开始")
uint32_t _syncStart = 0;
void maybeSyncPrompt();
void buildSyncOverlay(lv_obj_t* root);
void showSyncOverlay(bool on);
void startSync();
void tickSync(uint32_t nowMs);
};
extern MusicApp musicApp;
} // namespace apps

View File

@ -0,0 +1,255 @@
#include "SettingsApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../core/Settings.h"
#include "../hal/Power.h"
#include "../hal/Storage.h"
#include "../services/NetService.h"
#include "../services/PlatformService.h"
#include "../services/OtaService.h"
#include "../config/AppConfig.h"
#include "../ui/Shell.h"
#include "../ui/ServerEditor.h"
#include "../ui/NetWizard.h"
#include <WiFi.h>
namespace apps {
SettingsApp settingsApp;
static const AppMeta META = {"settings", "设置", LV_SYMBOL_SETTINGS, &icon_settings, 0xB388FF, true, false};
const AppMeta& SettingsApp::meta() const { return META; }
// 只读信息行:左标签右数值,比可操作的设置行更轻
static lv_obj_t* infoRow(lv_obj_t* list, const char* name, const char* value) {
lv_obj_t* row = lv_obj_create(list);
lv_obj_set_width(row, LV_PCT(100));
lv_obj_set_height(row, 46);
lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(row, 0, 0);
lv_obj_set_style_radius(row, 0, 0);
lv_obj_set_style_pad_hor(row, 14, 0);
lv_obj_set_style_pad_ver(row, 0, 0);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t* n = ui::label(row, name, FONT_TEXT, theme::textDim());
lv_obj_align(n, LV_ALIGN_LEFT_MID, 0, 0);
// 值用媒体字体:昵称/星座名/地址都可能是任意汉字,源码子集里没有
lv_obj_t* v = ui::label(row, value, FONT_MEDIA, theme::text());
lv_obj_set_width(v, 150);
lv_label_set_long_mode(v, LV_LABEL_LONG_DOT);
lv_obj_set_style_text_align(v, LV_TEXT_ALIGN_RIGHT, 0);
lv_obj_align(v, LV_ALIGN_RIGHT_MID, 0, 0);
return row;
}
// 可点击行:左边名字、右边当前值 + ›。0=服务端地址 1=配网向导
// 设置行里只放 host:port:带 http:// 的完整地址 150px 放不下,
// 协议在编辑器里能看能改,这里省掉不影响判断
static String shortUrl(const String& u) {
String s = u;
int p = s.indexOf("://");
if (p >= 0) s = s.substring(p + 3);
int slash = s.indexOf('/');
if (slash >= 0) s = s.substring(0, slash);
return s;
}
// 可点行的动作号。以前直接用 0/1 裸数字,加第三、第四个动作时可读性就崩了。
enum : int {
ACT_SERVER_EDITOR = 0,
ACT_NET_WIZARD = 1,
ACT_OTA_CHECK = 2,
};
static lv_obj_t* actionRow(lv_obj_t* list, const char* name, const char* value, int action,
lv_obj_t** outValue = nullptr) {
lv_obj_t* row = lv_obj_create(list);
lv_obj_set_width(row, LV_PCT(100));
lv_obj_set_height(row, 50);
lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(row, 0, 0);
lv_obj_set_style_radius(row, 12, 0);
lv_obj_set_style_pad_hor(row, 14, 0);
lv_obj_set_style_pad_ver(row, 0, 0);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(row, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(row, [](lv_event_t* e) {
int act = (int)(intptr_t)lv_event_get_user_data(e);
if (act == ACT_SERVER_EDITOR) {
ui::shell.openServerEditor();
} else if (act == ACT_NET_WIZARD) {
ui::shell.openNetWizard();
} else if (act == ACT_OTA_CHECK) {
// 规则很简单:已经知道有新版就直接装,否则先去问一遍。
if (svc::ota.state() == svc::OtaState::Available) {
svc::ota.start();
} else if (!svc::ota.check()) {
ui::toast(lv_layer_top(), svc::ota.error().c_str(), 1600);
}
}
}, LV_EVENT_CLICKED, (void*)(intptr_t)action);
lv_obj_t* n = ui::label(row, name, FONT_TEXT, theme::text());
lv_obj_align(n, LV_ALIGN_LEFT_MID, 0, 0);
lv_obj_t* v = ui::label(row, value, FONT_TEXT, theme::accent());
lv_obj_set_width(v, 150);
lv_obj_set_height(v, 20); // 限死一行:LONG_DOT 在 LVGL 8 里是"先换行再加省略号",
// 不限高就会折成两行把下一行压住
lv_label_set_long_mode(v, LV_LABEL_LONG_DOT);
lv_obj_set_style_text_align(v, LV_TEXT_ALIGN_RIGHT, 0);
lv_obj_align(v, LV_ALIGN_RIGHT_MID, -12, 0);
if (outValue) *outValue = v;
lv_obj_t* chev = ui::label(row, ">", FONT_TEXT, theme::textDim());
lv_obj_align(chev, LV_ALIGN_RIGHT_MID, 0, 0);
return row;
}
void SettingsApp::build(lv_obj_t* root) {
// 设置是一个**全屏应用**:不套卡片、不撞圆角安全区,
// 列表直接铺满圆屏,由轮盘导航(中心聚焦)负责行位置。
// 之前 312×236 卡片上方留白一大块,看着像浮层不像应用。
_list = lv_obj_create(root);
lv_obj_set_size(_list, SCREEN_W, SCREEN_H);
lv_obj_center(_list);
lv_obj_set_style_bg_opa(_list, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(_list, 0, 0);
lv_obj_set_style_pad_all(_list, 0, 0);
lv_obj_set_style_pad_hor(_list, 20, 0); // 行宽 320:贴边行不再切进圆边
lv_obj_clear_flag(_list, LV_OBJ_FLAG_SCROLLABLE); // 轮盘自己算位置,不要 LVGL 滚动
// 注意:不能用 listColumn —— 轮盘布局与 LVGL 流式布局互斥
buildAppSettings(_list);
ui::settingNavAttach(_list);
}
void SettingsApp::buildAppSettings(lv_obj_t* list) {
// 网络组放最前:服务端地址/配网向导是排障时最常找的两项,
// 360° 圆屏一屏放不下全列表,排在后面就要滚很久
ui::settingGroupTitle(list, "网络");
infoRow(list, "WiFi", WiFi.status() == WL_CONNECTED ? WiFi.SSID().c_str() : "未连接");
infoRow(list, "IP 地址", WiFi.status() == WL_CONNECTED ? WiFi.localIP().toString().c_str() : "—");
// 服务端地址只在配网页(192.168.4.1)改,设备上只读展示——
// 圆屏没有键盘,分段编辑器那套交互太重,真要改地址还是网页最顺手。
infoRow(list, "服务端地址", shortUrl(svc::net.serverUrl()).c_str());
actionRow(list, "配网向导", "热点配网", ACT_NET_WIZARD);
// 固件组紧跟网络组:升级入口埋到列表最底下的"关于"里时,
// 圆屏一屏只放得下两行,实际要点十几下旋钮才够得着(而且滚到底就停了)。
// 版本只给版本号:槽位(app0/app1)是开发期的概念,用户不需要知道;
// 排障要看槽位用串口 V。
ui::settingGroupTitle(list, "固件");
infoRow(list, "版本", BRAND_VERSION);
_otaVal = nullptr;
actionRow(list, "固件更新", "检查更新", ACT_OTA_CHECK, &_otaVal);
// 不提供"回滚到上一版":回退是设备自己换槽的机制(启动失败自动回),
// 不该做成用户可点的按钮。
ui::buildSettingGroup(list, "系统", nullptr);
// 账号这一组是"服务端真的同步过来了没有"的现场证据:
// 昵称/星座来自 /device/v1/profile,不是本地编的。
ui::settingGroupTitle(list, "账号");
infoRow(list, "绑定状态", svc::platform.bound() ? "已绑定" : "未绑定");
const auto& pf = svc::platform.profile();
if (svc::platform.bound()) {
infoRow(list, "昵称", pf.nickname.length()
? ui::fitFont(FONT_TEXT, pf.nickname).c_str() : "—");
// 不拼 pf.sunSymbol:♈~♓ 这些码位系统字体里没有,排出来是空心方块
infoRow(list, "太阳星座", pf.sunName.length() ? pf.sunName.c_str() : "—");
}
infoRow(list, "设备码", svc::platform.chipId().c_str());
ui::settingGroupTitle(list, "关于");
// 只给电量百分比:mV 是电芯原始值,用户看不懂也用不上(排障看串口 ?)
char buf[32];
snprintf(buf, sizeof(buf), "%u%%", hal::batteryPercent());
infoRow(list, "电量", buf);
if (hal::storageReady()) {
snprintf(buf, sizeof(buf), "%llu / %llu MB",
hal::storageUsedBytes() / (1024ULL * 1024ULL),
hal::storageTotalBytes() / (1024ULL * 1024ULL));
infoRow(list, "TF 卡", buf);
} else {
infoRow(list, "TF 卡", "未挂载");
}
}
void SettingsApp::onEnter() {
// 值可能被网页改过,重进时重建一次
lv_obj_clean(_list);
buildAppSettings(_list);
ui::settingNavAttach(_list);
}
void SettingsApp::onPress(int x, int y) {
(void)x; (void)y; // 轮盘不靠手指滚动,按下的滚动位置记录不再需要
}
bool SettingsApp::allowShellSwipe(int dx, int dy) {
(void)dx; (void)dy;
// 列表不吃滚动了:任何纵向手势都可以交给框架(上滑退出等)。
// 滑轨调值是在行内小距离拖动,够不到手势阈值。
return true;
}
void SettingsApp::onTick(uint32_t nowMs) {
(void)nowMs;
// "固件更新"那一行的值就是升级状态机的人话版。
// 不做轮询式重建:只改这一格文字,避免每帧刷整张列表导致闪烁。
if (!_otaVal) return;
char buf[32];
const char* txt = nullptr;
switch (svc::ota.state()) {
case svc::OtaState::Checking: txt = "检查中"; break;
case svc::OtaState::UpToDate: txt = "已是最新"; break;
case svc::OtaState::Available: txt = svc::ota.release().version.c_str(); break;
case svc::OtaState::Downloading:
case svc::OtaState::Verifying:
snprintf(buf, sizeof(buf), "%d%%", svc::ota.progress());
txt = buf;
break;
case svc::OtaState::Ready: txt = "即将重启"; break;
case svc::OtaState::Failed: txt = "失败,重试"; break;
default: txt = "检查更新"; break;
}
if (strcmp(lv_label_get_text(_otaVal), txt) != 0) lv_label_set_text(_otaVal, txt);
}
void SettingsApp::dumpList() {
if (!_list) { Serial.println("LIST none"); return; }
uint32_t n = lv_obj_get_child_cnt(_list);
Serial.printf("LIST children=%u scroll_y=%d max=%d h=%d\n", n,
(int)lv_obj_get_scroll_y(_list), (int)lv_obj_get_scroll_bottom(_list),
(int)lv_obj_get_height(_list));
for (uint32_t i = 0; i < n; i++) {
lv_obj_t* row = lv_obj_get_child(_list, i);
// 行里第一个 label 一般就是名字(分组标题同样是 label)
const char* txt = "-";
uint32_t cn = lv_obj_get_child_cnt(row);
for (uint32_t k = 0; k < cn; k++) {
lv_obj_t* c = lv_obj_get_child(row, k);
if (lv_obj_check_type(c, &lv_label_class)) { txt = lv_label_get_text(c); break; }
}
Serial.printf(" [%02u] y=%4d h=%3d %s\n", (unsigned)i,
(int)lv_obj_get_y(row), (int)lv_obj_get_height(row), txt);
}
}
void SettingsApp::rebuild() {
if (!_list) return;
lv_obj_clean(_list);
buildAppSettings(_list);
}
bool SettingsApp::onKnob(int32_t diff) {
if (!_list) return true;
ui::settingNavKnob(diff); // 轮盘:旋到中心即选中
return true;
}
} // namespace apps

View File

@ -0,0 +1,37 @@
#pragma once
// SettingsApp.h —— 系统设置
//
// 分层的设置入口:
// 总设置(这里):系统、网络、关于
// 应用设置:在各应用内下拉打开,只显示与该应用相关的项
// 两边都从同一张 SettingDesc 表生成,不会出现"加了设置项但界面没跟上"。
#include "../core/App.h"
namespace apps {
class SettingsApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override;
void buildAppSettings(lv_obj_t* list) override;
void rebuild(); // 服务端地址改完就地刷新,不用退出重进
// 串口 L 键:把整张设置列表的行(文字/坐标/高度)打到串口。
// 圆屏一屏只显示四行,"列表到底有没有这些行、是不是没被布局"光看截图判断不了。
void dumpList();
// 手指在列表里拖动时,列表自己会滚;这时不能把上滑当成"切到一级菜单"
void onPress(int x, int y) override;
bool allowShellSwipe(int dx, int dy) override;
private:
lv_obj_t* _list = nullptr;
lv_obj_t* _otaVal = nullptr; // "固件更新"那行的值,跟着 OTA 状态变
uint32_t _lastRefresh = 0;
};
extern SettingsApp settingsApp;
} // namespace apps

View File

@ -0,0 +1,224 @@
#include "UserApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../ui/Shell.h"
#include "../ui/QrScreen.h"
#include "../services/PlatformService.h"
#include "../services/NetService.h"
#include "../core/Log.h"
namespace apps {
static const AppMeta META = {"user", "我的", LV_SYMBOL_HOME, &icon_user, 0x6FC7B5, false, true};
const AppMeta& UserApp::meta() const { return META; }
// 版式以昵称为中心:姓名大字落在圆心,星座/常住地/生日依次往下衰减。
// 三个手势,各管一件事:
// 转动旋钮 → 拉一次资料(反馈环扫一圈 + 一句"已同步",和天气页同一套)
// 长按屏幕 → 开/关管理二维码(0.1.8 起:以前是"点击",但点击太容易误触,
// 而且和"转动=同步"挤在一起,改成按住不放才出码)
// 下滑 → 也能开码(老习惯,留着)
// 底部那层 1/3 遮罩信息层只写这一件事:长按生成管理二维码。
// 手势从点击变成长按之后,没有这行字用户根本猜不到怎么出码。
void UserApp::build(lv_obj_t* root) {
// 反馈环:平时整圈隐藏,只在同步资料时出现
_ring = ui::ringNew(root, 171, 2);
// 昵称:大字居中。宽度收到 280 + 省略号——邮箱当昵称时不至于捅出圆边。
// 用媒体字体:昵称是用户数据,源码子集里不可能有所有字。
_name = ui::label(root, "—", FONT_MEDIA_24, theme::text());
lv_obj_set_width(_name, 280);
lv_label_set_long_mode(_name, LV_LABEL_LONG_DOT);
lv_obj_set_style_text_align(_name, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(_name, LV_ALIGN_CENTER, 0, -56);
// 太阳星座:主色小字,紧贴昵称下方。星座名来自服务端(如“射手座”),
// 必须用媒体字体——用源码子集的话这些字全部是方块。
_sun = ui::label(root, "", FONT_MEDIA, theme::accent());
lv_obj_align(_sun, LV_ALIGN_CENTER, 0, -14);
// 常住地:媒体字体(服务端文案,源码子集里没有)
_res = ui::label(root, "", FONT_MEDIA, theme::textDim());
lv_obj_set_width(_res, 300);
lv_label_set_long_mode(_res, LV_LABEL_LONG_DOT);
lv_obj_set_style_text_align(_res, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(_res, LV_ALIGN_CENTER, 0, 24);
// 生日 · 时区:一行小字收尾
_sub = ui::label(root, "", FONT_TEXT, theme::textDim());
lv_obj_align(_sub, LV_ALIGN_CENTER, 0, 60);
// 点击整页 = 开关二维码。LVGL 在滑动手势松手时也会发 CLICKED,
// 所以按下时记坐标、松手时比对位移,超过阈值就当滑动不算点击。
lv_obj_add_flag(root, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(root, [](lv_event_t* e) {
UserApp* u = (UserApp*)lv_event_get_user_data(e);
lv_indev_get_point(lv_indev_get_act(), &u->_press);
}, LV_EVENT_PRESSED, this);
// 长按(默认 400ms)才出码:按下时记的坐标还在,位移大就当滑动不算
lv_obj_add_event_cb(root, [](lv_event_t* e) {
UserApp* u = (UserApp*)lv_event_get_user_data(e);
lv_point_t p;
lv_indev_get_point(lv_indev_get_act(), &p);
if (abs(p.x - u->_press.x) + abs(p.y - u->_press.y) > 44) return;
u->toggleQr();
}, LV_EVENT_LONG_PRESSED, this);
// 底部 1/3 遮罩信息层:与时钟专注模式、其它模块的设置层同一套外观。
// 只写一行——长按生成管理二维码。已绑定时才出现(未绑定按了也没用)。
_panel = ui::bottomPanel(root);
_hint = ui::label(_panel, "长按生成管理二维码", FONT_TEXT, theme::textDim());
lv_obj_set_width(_hint, 300);
lv_obj_set_style_text_align(_hint, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(_hint, LV_ALIGN_TOP_MID, 0, 38);
lv_obj_add_flag(_panel, LV_OBJ_FLAG_HIDDEN);
}
void UserApp::refresh() {
if (!_name) return;
// 底部提示层只在已绑定时出现:没绑定时长按什么也不会发生,
// 却先弹一句绑定提示,那是两句话抢同一件事。
// 二维码浮层开着时也收起:浮层是 80% 黑的半透明遮罩,挡不住这行字,
// 会透在码下面,看着像屏幕坏了。
if (_panel) {
if (svc::platform.bound() && !_qrUp) lv_obj_clear_flag(_panel, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(_panel, LV_OBJ_FLAG_HIDDEN);
}
if (!svc::platform.bound()) {
// 统一空态文案(platform.stateHint()):等待网络 / 正在连接服务端 /
// 设备未绑定——三段话所有模块同口径,不再各写各的
lv_label_set_text(_name, "—");
lv_label_set_text(_sun, "");
lv_label_set_text(_sub, "");
lv_label_set_text(_res, svc::platform.stateHint());
return;
}
const auto& pf = svc::platform.profile();
lv_label_set_text(_name, pf.valid && pf.nickname.length()
? ui::fitFont(FONT_MEDIA_24, pf.nickname).c_str() : "—");
// 不拼 pf.sunSymbol:♈~♓ 系统字体没有这些码位,排出来是空心方块
lv_label_set_text(_sun, pf.valid && pf.sunName.length()
? ui::fitFont(FONT_MEDIA, pf.sunName).c_str() : "");
// 不手工截断:标签固定 300 宽 + LONG_DOT,超长自己出省略号
lv_label_set_text(_res, pf.valid && pf.residence.length()
? ui::fitFont(FONT_MEDIA, pf.residence).c_str() : "");
String tz = pf.timezone;
if (tz.length() > 14) { tz = tz.substring(tz.lastIndexOf('/') + 1); } // Asia/Shanghai -> Shanghai
String sub = pf.valid && pf.birthday.length() ? pf.birthday.c_str() : "";
if (tz.length()) {
if (sub.length()) sub += " · ";
sub += tz;
}
lv_label_set_text(_sub, sub.c_str());
}
// 未绑定时挡住操作的提示语:与页面空态同一口径(stateHint)
static const char* bindHint() {
const char* h = svc::platform.stateHint();
return h[0] ? h : "先在网页绑定设备";
}
void UserApp::onEnter() {
_syncing = false;
ui::ringHide(_ring);
_stateShown = 0xFF; // 进页强制重画一次
refresh();
}
// 0 等待网络 / 1 正在连服务端 / 2 服务端确认未绑定 / 3 已绑定有资料 / 4 已绑定待取资料
uint8_t UserApp::stateCode() {
if (svc::platform.bound())
return svc::platform.profile().valid ? 3 : 4;
if (!svc::net.online()) return 0;
return svc::platform.serverOk() ? 2 : 1;
}
bool UserApp::onKnob(int32_t diff) {
(void)diff;
sync(); // 转动即同步;busy() 里防叠加
return true;
}
// 下滑仍然开码(老习惯),点一下则是开/关的切换
bool UserApp::onGesture(Gesture g) {
if (g != Gesture::SwipeDown) return false;
if (!svc::platform.bound()) {
ui::toast(lv_layer_top(), bindHint(), 1600);
return true; // 吃掉这次下滑,别再滑出空设置抽屉
}
ui::qrScreen.open();
LOG("USER", "qr login opened");
return true;
}
void UserApp::toggleQr() {
if (!svc::platform.bound()) {
ui::toast(lv_layer_top(), bindHint(), 1800);
return;
}
ui::qrScreen.toggle();
LOG("USER", "qr toggle -> %s", ui::qrScreen.visible() ? "open" : "close");
}
void UserApp::sync() {
if (!svc::platform.bound()) {
ui::toast(lv_layer_top(), bindHint(), 1800);
return;
}
if (_syncing || svc::platform.busy()) return; // 正在同步别叠加
svc::platform.requestProfile(true);
_syncing = true;
_syncStart = millis();
ui::ringWorking(_ring);
LOG("USER", "sync requested");
}
void UserApp::onTick(uint32_t nowMs) {
// 二维码浮层的开关可能来自长按、下滑,也可能来自串口 'Q',
// 所以在这里统一跟踪可见性(变了才重画,避免每帧写 label)。
const bool qrUp = ui::qrScreen.visible();
if (qrUp != _qrUp) {
_qrUp = qrUp;
refresh();
}
// 状态自己会变(WiFi 起来、服务端探通、资料到位),用户往往就停在这一页等它。
// 只在状态真的变了时重画,避免每次 tick 都写 label。
uint8_t st = stateCode();
if (st != _stateShown) {
_stateShown = st;
refresh();
}
if (!_syncing) return;
if (svc::platform.busy()) {
// 兜底:20 秒还没回来也要收圈,不能一直转
if (nowMs - _syncStart <= 20000) return;
_syncing = false;
ui::ringDone(_ring);
ui::toast(lv_layer_top(), "同步超时,稍后再试", 1800);
return;
}
_syncing = false;
ui::ringDone(_ring);
const auto& pf = svc::platform.profile();
// 上次成功过不代表这次成功:真结果看本次请求有没有留下错误
if (pf.valid && svc::platform.lastError().length() == 0) {
ui::toast(lv_layer_top(), "已同步", 2000);
} else {
ui::toast(lv_layer_top(),
svc::platform.lastError().length() ? svc::platform.lastError().c_str()
: "同步失败,检查网络", 1800);
}
refresh();
}
UserApp userApp;
} // namespace apps

46
src/apps/UserApp.h 100644
View File

@ -0,0 +1,46 @@
#pragma once
// UserApp.h —— 我的(一级菜单入口)
//
// 展示绑定用户的资料,页面以昵称为中心:
// 昵称(大字居中)→ 太阳星座(主色)→ 常住地 → 生日 · 时区(一行小字)。
// 只读:这些都在 web 端改(平台 Home 页)。
// - 转动旋钮 = 拉一次 /device/v1/profile:反馈环扫一圈 → 淡出 → "已同步"
// (与天气页"旋钮更新"同一套反馈,页面上没有任何常驻说明)
// - 长按屏幕 = 开/关管理二维码;下滑也能开(底部 1/3 遮罩层写着这行提示)
#include "../core/App.h"
namespace apps {
class UserApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override; // 转动即同步
bool onGesture(Gesture g) override; // 下滑 → 扫码登录
void sync(); // 旋钮 / 串口调试调用
void toggleQr(); // 长按:开/关二维码
private:
void refresh(); // 把 profile 内容刷到各行
uint8_t stateCode(); // 网络/服务端/绑定三态打包成一个数
lv_obj_t* _name = nullptr; // 昵称(大字,页面中心)
lv_obj_t* _sun = nullptr; // 太阳星座(主色)
lv_obj_t* _res = nullptr; // 常住地
lv_obj_t* _sub = nullptr; // 生日 · 时区(一行小字)
lv_obj_t* _ring = nullptr; // 同步反馈环(平时隐藏)
lv_obj_t* _panel = nullptr; // 底部 1/3 遮罩信息层(长按提示)
lv_obj_t* _hint = nullptr; // 其中的那行字
lv_point_t _press{0, 0}; // 按下坐标:区分点击与滑动
bool _syncing = false;
bool _qrUp = false; // 二维码浮层当前是否开着(决定提示层显隐)
uint32_t _syncStart = 0;
uint8_t _stateShown = 0xFF; // 上一次画的状态(变了才重画)
};
extern UserApp userApp;
} // namespace apps

View File

@ -0,0 +1,198 @@
#include "WeatherApp.h"
#include "../ui/Theme.h"
#include "../ui/Widgets.h"
#include "../core/Settings.h"
#include "../services/WeatherService.h"
#include "../services/PlatformService.h"
#include "../services/NetService.h"
#include "../core/Log.h"
#include "../config/AppConfig.h"
#include <WiFi.h>
namespace apps {
WeatherApp weatherApp;
static const AppMeta META = {"weather", "天气", LV_SYMBOL_REFRESH, &icon_weather, 0x8FA6B2, false, true};
const AppMeta& WeatherApp::meta() const { return META; }
void WeatherApp::build(lv_obj_t* root) {
// 页面平时是干净的:没有常驻外圈,也没有底部说明条。
// 这圈只在"旋钮更新"的时候亮一下——扫满一圈 → 淡出 → 弹一句结果,
// 和「我的」页同步资料用的是同一套反馈语言。
_ring = ui::ringNew(root, 171, 2);
// 城市名来自服务端(按账号资料),不在源码字面量里 → 必须用媒体字体
_city = ui::label(root, "", FONT_MEDIA, theme::textDim());
lv_obj_align(_city, LV_ALIGN_CENTER, 0, -112);
// 顶部留白太大时整个页面像"漏了一块",用一个天气图标把上半圆撑起来
_icon = lv_img_create(root);
lv_img_set_src(_icon, &icon_weather);
lv_obj_set_style_img_recolor(_icon, theme::textDim(), 0);
lv_obj_set_style_img_recolor_opa(_icon, LV_OPA_COVER, 0);
lv_obj_align(_icon, LV_ALIGN_CENTER, 0, -70);
lv_obj_clear_flag(_icon, LV_OBJ_FLAG_CLICKABLE);
_temp = ui::label(root, "--", FONT_NUM_XL, theme::text());
lv_obj_align(_temp, LV_ALIGN_CENTER, 0, -14);
// 下半幅统一信息面板:阴晴/体感/湿度/风都住这里。
// 阴晴是第一行、24px:它紧跟在温度大字下面,是"17° 下面那个字",
// 16px 太轻,用户会以为天气描述压根没显示。
_panel = ui::bottomPanel(root);
_row1 = ui::label(_panel, "", FONT_MEDIA_24, theme::text());
lv_obj_set_style_text_align(_row1, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(_row1, SCREEN_W - 72);
lv_obj_set_height(_row1, 30); // 限死一行:LONG_DOT 是"先换行再加省略号",
// 不限高的话长天气文案会折成两行挤出面板
lv_label_set_long_mode(_row1, LV_LABEL_LONG_DOT);
lv_obj_align(_row1, LV_ALIGN_TOP_MID, 0, 14);
// 风级/风向我写的是中文,但"东风/西北风"里的字是**服务端**给的,
// 源码子集里没有(cjk 字体连"东""阴"都缺)——过去这一行排出来就是空心方块。
// 凡是可能含外部文本的行,一律走媒体字体 + fitFont。
// 宽度按屏幕下沿的弦长收窄:面板越往下越窄,给小字留 208 才不会被圆边切掉。
_row2 = ui::label(_panel, "", FONT_MEDIA, theme::textDim());
lv_obj_set_style_text_align(_row2, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(_row2, 208);
lv_obj_set_height(_row2, 20);
lv_label_set_long_mode(_row2, LV_LABEL_LONG_DOT);
lv_obj_align(_row2, LV_ALIGN_TOP_MID, 0, 58);
}
void WeatherApp::onEnter() {
_syncing = false;
ui::ringHide(_ring);
refresh();
// 进页面就拉一次(是否真发请求由 wx.interval 决定,没到期直接返回)
if (svc::platform.bound()) svc::weather.requestUpdate();
}
// 旋钮 = 更新。反馈分三段:立刻扫圈 → 请求回来 → 一句结果。
// 请求本身是后台任务(WeatherService 里 xTaskCreate),UI 全程不等它,
// 所以"转一下要卡半秒"这种手感的来源不是这里。
void WeatherApp::update() {
if (!svc::platform.bound()) {
ui::toast(_root, "先在网页端绑定设备", 1800);
return;
}
if (WiFi.status() != WL_CONNECTED) {
ui::toast(_root, "设备未联网", 1800);
return;
}
if (_syncing || svc::weather.busy()) return; // 已经在更新,别叠请求
if (!svc::weather.requestUpdate(true)) {
ui::toast(_root, svc::weather.data().error.length()
? svc::weather.data().error.c_str() : "更新失败", 1800);
return;
}
_syncing = true;
_baseMs = svc::weather.data().updatedMs;
_syncStart = millis();
ui::ringWorking(_ring);
}
void WeatherApp::onTick(uint32_t nowMs) {
if (nowMs - _lastRefresh >= 1200) {
_lastRefresh = nowMs;
refresh();
}
if (!_syncing) return;
// 结束条件:后台任务交卷(busy 落回 false)。再加一条 20 秒兜底——
// DNS 卡住时任务可能很久不返回,屏幕上一直转圈会被当成死机。
const auto& d = svc::weather.data();
bool finished = !svc::weather.busy();
bool timedOut = (nowMs - _syncStart > 20000);
if (!finished && !timedOut) return;
_syncing = false;
ui::ringDone(_ring);
if (!finished) ui::toast(_root, "更新较慢,稍后再看", 1800);
else if (d.valid && d.updatedMs != _baseMs) ui::toast(_root, "已同步", 2000);
else if (d.error.length()) ui::toast(_root, d.error.c_str(), 2000);
else ui::toast(_root, "已是最新", 2000);
refresh();
}
void WeatherApp::refresh() {
const auto& d = svc::weather.data();
// 城市只来自服务端(按账号"常住地"解析),本地不再兜底——设置里已经没有城市项了
const String& city = d.city;
lv_label_set_text(_city, city.length() ? ui::fitFont(FONT_MEDIA, city).c_str() : "未设置常住地");
if (!svc::platform.bound()) {
lv_label_set_text(_temp, "--");
// 统一空态口径与「我的」/星盘一致:等待网络 / 正在连接服务端 / 设备未绑定
if (!svc::net.online()) {
lv_label_set_text(_row1, "等待网络连接");
lv_label_set_text(_row2, "");
} else if (!svc::platform.serverOk()) {
lv_label_set_text(_row1, "正在连接服务端");
lv_label_set_text(_row2, "");
} else {
lv_label_set_text(_row1, "设备未绑定");
lv_label_set_text(_row2, "请先完成配对");
}
lv_obj_set_style_img_recolor(_icon, theme::textDim(), 0);
return;
}
if (!d.valid) {
bool online = (WiFi.status() == WL_CONNECTED);
lv_label_set_text(_temp, "--");
lv_label_set_text(_row1, d.updating ? "更新中" : "暂无数据");
// 错误原文只进日志:屏上"暂时取不到"比"HTTP 500"有用
if (online && d.error.length()) LOG("WX", "error: %s", d.error.c_str());
lv_label_set_text(_row2, online ? "" : "设备未联网");
lv_obj_set_style_img_recolor(_icon, theme::textDim(), 0);
return;
}
bool f = settings.getI("wx.unit") == 1;
auto conv = [f](int c) { return f ? (int)lround(c * 9.0 / 5.0 + 32) : c; };
lv_label_set_text_fmt(_temp, "%d°", conv(d.tempC));
// 第一行:阴晴紧跟在温度大字下面(24px)。
// 服务端原文更准("小到中雨" 比归一化的 "雨" 有用),但它的字不在字库里时
// fitFont 会整串丢字——"晴/阴" 就这么消失过。丢干净了就退回本地码表,
// 宁可粗一点,也不能让这一行空着。
String desc = ui::fitFont(FONT_MEDIA_24, d.text);
if (desc.length() == 0) desc = svc::WeatherService::codeToText(d.code);
char line1[64];
snprintf(line1, sizeof(line1), "%s · 体感 %d°", desc.c_str(), conv(d.feels));
lv_label_set_text(_row1, line1);
// 风向是服务端文本("西北风"),必须过媒体字体
String wind = ui::fitFont(FONT_MEDIA, d.windDir);
char line2[80];
if (d.windScale > 0) {
snprintf(line2, sizeof(line2), "湿度 %d%% · %s %d 级", d.humidity,
wind.length() ? wind.c_str() : "风", d.windScale);
} else {
snprintf(line2, sizeof(line2), "湿度 %d%%", d.humidity);
}
lv_label_set_text(_row2, line2);
// 页面里只留一种强调色:晴/雨的区分交给图标和文字
lv_obj_set_style_img_recolor(_icon, theme::accent(), 0);
}
bool WeatherApp::onKnob(int32_t diff) {
(void)diff;
update();
return true;
}
// 天气没有设置项:城市/经纬度早就删了(位置只认账号的"常住地"),
// 温度单位与刷新间隔也一并去掉——一台只显示一个城市的桌面设备,
// 留两个能改的旋钮只会让人怀疑"是不是我设错了"。
// hasSettings = false,Shell 不会为它弹抽屉。
} // namespace apps

View File

@ -0,0 +1,35 @@
#pragma once
// WeatherApp.h —— 天气
#include "../core/App.h"
namespace apps {
class WeatherApp : public App {
public:
const AppMeta& meta() const override;
void build(lv_obj_t* root) override;
void onEnter() override;
void onTick(uint32_t nowMs) override;
bool onKnob(int32_t diff) override;
void update(); // 旋钮更新(后台任务 + 扫圈反馈)
private:
void refresh();
lv_obj_t* _ring = nullptr; // 更新反馈环:平时隐藏
lv_obj_t* _icon = nullptr;
lv_obj_t* _city = nullptr;
lv_obj_t* _temp = nullptr;
lv_obj_t* _panel = nullptr; // 下半幅统一信息面板
lv_obj_t* _row1 = nullptr; // 阴晴 · 体感
lv_obj_t* _row2 = nullptr; // 湿度 · 风
bool _syncing = false;
uint32_t _baseMs = 0; // 发起时的数据版本,用来判断"真的换了新数据"
uint32_t _syncStart = 0;
uint32_t _lastRefresh = 0;
};
extern WeatherApp weatherApp;
} // namespace apps

2460
src/assets/icons.c 100644

File diff suppressed because it is too large Load Diff

22
src/assets/icons.h 100644
View File

@ -0,0 +1,22 @@
#pragma once
// 线性图标资源(LVGL 图片描述符),见 tools/gen_icons.py
#include <lvgl.h>
#ifdef __cplusplus
extern "C" {
#endif
extern const lv_img_dsc_t icon_clock;
extern const lv_img_dsc_t icon_gallery;
extern const lv_img_dsc_t icon_music;
extern const lv_img_dsc_t icon_weather;
extern const lv_img_dsc_t icon_astro;
extern const lv_img_dsc_t icon_user;
extern const lv_img_dsc_t icon_settings;
extern const lv_img_dsc_t icon_back;
extern const lv_img_dsc_t icon_check;
#ifdef __cplusplus
}
#endif

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,422 @@
/*******************************************************************************
* Size: 26 px
* Bpp: 4
* Opts: --font /System/Library/Fonts/Apple Symbols.ttf --symbols ♈♉♊♋♌♍♎♏♐♑♒♓ --size 26 --bpp 4 --format lvgl --lv-include lvgl.h --lv-font-name lv_font_zodiac_26 --no-compress -o /Volumes/DATA/资料/esp32/01-开发工作区/新项目/knob_os/src/assets/lv_font_zodiac_26.c
******************************************************************************/
#ifdef LV_LVGL_H_INCLUDE_SIMPLE
#include "lvgl.h"
#else
#include "lvgl.h"
#endif
#ifndef LV_FONT_ZODIAC_26
#define LV_FONT_ZODIAC_26 1
#endif
#if LV_FONT_ZODIAC_26
/*-----------------
* BITMAPS
*----------------*/
/*Store the image of the glyphs*/
static LV_ATTRIBUTE_LARGE_CONST const uint8_t glyph_bitmap[] = {
/* U+2648 "♈" */
0x0, 0x1, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0,
0x14, 0x51, 0x0, 0x1, 0xcf, 0xfe, 0x50, 0x0,
0x0, 0x0, 0x6, 0xef, 0xff, 0x50, 0xd, 0xf7,
0x5c, 0xf6, 0x0, 0x0, 0x0, 0x5f, 0x91, 0x2d,
0xf2, 0x4f, 0x60, 0x0, 0xcf, 0x20, 0x0, 0x1,
0xfa, 0x0, 0x4, 0xf9, 0x8f, 0x10, 0x0, 0x1f,
0xb0, 0x0, 0x9, 0xf1, 0x0, 0x0, 0xfc, 0x9f,
0x0, 0x0, 0x8, 0xf3, 0x0, 0x1f, 0x80, 0x0,
0x0, 0xec, 0x6f, 0x30, 0x0, 0x1, 0xf9, 0x0,
0x7f, 0x10, 0x0, 0x1, 0xf9, 0x1f, 0x70, 0x0,
0x0, 0xbe, 0x0, 0xbb, 0x0, 0x0, 0x5, 0xf4,
0xa, 0xd0, 0x0, 0x0, 0x6f, 0x20, 0xf6, 0x0,
0x0, 0xc, 0xe0, 0x0, 0x0, 0x0, 0x0, 0x2f,
0x63, 0xf2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xe, 0x96, 0xf0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xb, 0xc9, 0xb0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x8, 0xeb, 0x90, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x5, 0xfd, 0x60, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff,
0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x1, 0xff, 0x30, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0x10, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xdf, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0xdf, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xcf, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0xbe, 0x0, 0x0, 0x0, 0x0, 0x0,
/* U+2649 "♉" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x1f, 0xd6, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7, 0xdf, 0x5, 0xcf, 0x80, 0x0,
0x0, 0x0, 0x0, 0x0, 0x9f, 0x94, 0x0, 0xa,
0xf3, 0x0, 0x0, 0x0, 0x0, 0x4, 0xf8, 0x0,
0x0, 0x1, 0xec, 0x0, 0x0, 0x0, 0x0, 0xd,
0xe0, 0x0, 0x0, 0x0, 0x7f, 0x60, 0x0, 0x0,
0x0, 0x7f, 0x50, 0x0, 0x0, 0x0, 0xc, 0xf3,
0x0, 0x0, 0x4, 0xfb, 0x0, 0x0, 0x0, 0x0,
0x1, 0xcf, 0x83, 0x12, 0x7f, 0xb1, 0x0, 0x0,
0x0, 0x0, 0x0, 0xa, 0xff, 0xff, 0xf8, 0x0,
0x0, 0x0, 0x0, 0x0, 0x1, 0xbf, 0xe9, 0x89,
0xef, 0xa0, 0x0, 0x0, 0x0, 0x0, 0xc, 0xf7,
0x0, 0x0, 0x8, 0xfb, 0x0, 0x0, 0x0, 0x0,
0x7f, 0x80, 0x0, 0x0, 0x0, 0x8f, 0x60, 0x0,
0x0, 0x0, 0xde, 0x0, 0x0, 0x0, 0x0, 0xe,
0xc0, 0x0, 0x0, 0x0, 0xf9, 0x0, 0x0, 0x0,
0x0, 0x9, 0xf0, 0x0, 0x0, 0x0, 0xf8, 0x0,
0x0, 0x0, 0x0, 0x7, 0xf1, 0x0, 0x0, 0x0,
0xea, 0x0, 0x0, 0x0, 0x0, 0x9, 0xf0, 0x0,
0x0, 0x0, 0xae, 0x0, 0x0, 0x0, 0x0, 0xe,
0xc0, 0x0, 0x0, 0x0, 0x4f, 0x80, 0x0, 0x0,
0x0, 0x7f, 0x50, 0x0, 0x0, 0x0, 0xa, 0xf8,
0x0, 0x0, 0x7, 0xfb, 0x0, 0x0, 0x0, 0x0,
0x0, 0xaf, 0xe9, 0x89, 0xef, 0xb0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x5, 0xbf, 0xff, 0xb5, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0,
/* U+264A "♊" */
0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x15, 0x2f, 0xfc, 0x97, 0x65, 0x55, 0x56, 0x78,
0xbe, 0xfe, 0x1, 0x58, 0xcf, 0xff, 0xff, 0xff,
0xff, 0xa7, 0x40, 0x0, 0x0, 0x3f, 0x70, 0x0,
0x0, 0xcd, 0x0, 0x0, 0x0, 0x0, 0x3f, 0x70,
0x0, 0x0, 0xcd, 0x0, 0x0, 0x0, 0x0, 0x3f,
0x70, 0x0, 0x0, 0xcd, 0x0, 0x0, 0x0, 0x0,
0x3f, 0x70, 0x0, 0x0, 0xcd, 0x0, 0x0, 0x0,
0x0, 0x3f, 0x70, 0x0, 0x0, 0xcd, 0x0, 0x0,
0x0, 0x0, 0x3f, 0x70, 0x0, 0x0, 0xcd, 0x0,
0x0, 0x0, 0x0, 0x3f, 0x70, 0x0, 0x0, 0xcd,
0x0, 0x0, 0x0, 0x0, 0x3f, 0x70, 0x0, 0x0,
0xcd, 0x0, 0x0, 0x0, 0x0, 0x3f, 0x70, 0x0,
0x0, 0xcd, 0x0, 0x0, 0x0, 0x0, 0x3f, 0x70,
0x0, 0x0, 0xcd, 0x0, 0x0, 0x0, 0x0, 0x3f,
0x70, 0x0, 0x0, 0xcd, 0x0, 0x0, 0x0, 0x0,
0x3f, 0x70, 0x0, 0x0, 0xcd, 0x0, 0x0, 0x0,
0x0, 0x3f, 0x70, 0x11, 0x0, 0xcd, 0x0, 0x0,
0x2, 0x6a, 0xdf, 0xff, 0xff, 0xff, 0xff, 0xc9,
0x62, 0x3f, 0xfc, 0xa8, 0x76, 0x55, 0x67, 0x78,
0xbd, 0xfe, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x2,
/* U+264B "♋" */
0x0, 0x0, 0x0, 0x2, 0x57, 0x9a, 0x98, 0x74,
0x10, 0x0, 0x0, 0x0, 0x3, 0x9e, 0xff, 0xfe,
0xef, 0xff, 0xff, 0xc7, 0x0, 0x0, 0x1a, 0xff,
0xd6, 0x20, 0x0, 0x0, 0x36, 0xaf, 0xff, 0x70,
0x1e, 0xd8, 0x8e, 0x90, 0x0, 0x0, 0x0, 0x0,
0x4, 0xac, 0xb, 0xb0, 0x0, 0x1d, 0x70, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xf4, 0x0, 0x0,
0x6d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1f,
0x20, 0x0, 0x5, 0xe0, 0x0, 0x0, 0x5d, 0xff,
0xa1, 0x0, 0xe6, 0x0, 0x0, 0xac, 0x0, 0x0,
0x6e, 0x50, 0x2b, 0xd1, 0x7, 0xf4, 0x0, 0x7f,
0x50, 0x0, 0xf, 0x50, 0x0, 0xd, 0x70, 0x7,
0xfe, 0xff, 0x70, 0x0, 0x4, 0xf0, 0x0, 0x0,
0x8b, 0x0, 0x0, 0x44, 0x0, 0x0, 0x0, 0x3f,
0x0, 0x0, 0x8, 0xa0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xe6, 0x0, 0x1, 0xe6, 0x3d, 0x50,
0x0, 0x0, 0x0, 0x0, 0x4, 0xf9, 0x56, 0xdc,
0x2, 0xff, 0xe9, 0x40, 0x0, 0x0, 0x0, 0x4,
0xff, 0xfb, 0x10, 0x1, 0x7d, 0xff, 0xfd, 0xa9,
0x88, 0xad, 0xff, 0xd5, 0x0, 0x0, 0x0, 0x3,
0x7a, 0xde, 0xff, 0xed, 0xa7, 0x30, 0x0, 0x0,
/* U+264C "♌" */
0x0, 0x0, 0x0, 0x0, 0x2, 0x32, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x5, 0xef, 0xff, 0xf8,
0x0, 0x0, 0x0, 0x0, 0x0, 0x8f, 0xc5, 0x35,
0xaf, 0xc0, 0x0, 0x0, 0x0, 0x3, 0xfa, 0x0,
0x0, 0x4, 0xf8, 0x0, 0x0, 0x0, 0xa, 0xf0,
0x0, 0x0, 0x0, 0xaf, 0x0, 0x0, 0x0, 0xc,
0xc0, 0x0, 0x0, 0x0, 0x5f, 0x30, 0x0, 0x0,
0xc, 0xc0, 0x0, 0x0, 0x0, 0x3f, 0x40, 0x0,
0x0, 0x9, 0xf0, 0x0, 0x0, 0x0, 0x4f, 0x30,
0x0, 0x0, 0x4, 0xf5, 0x0, 0x0, 0x0, 0x8f,
0x0, 0x0, 0x1, 0x45, 0xeb, 0x0, 0x0, 0x0,
0xeb, 0x0, 0x0, 0x5f, 0xfe, 0xff, 0x30, 0x0,
0x5, 0xf4, 0x0, 0x4, 0xf6, 0x0, 0x3d, 0xa0,
0x0, 0xc, 0xd0, 0x0, 0xc, 0x80, 0x0, 0x3,
0xf1, 0x0, 0x3f, 0x60, 0x0, 0xf, 0x40, 0x0,
0x0, 0xf4, 0x0, 0xae, 0x0, 0x0, 0xe, 0x50,
0x0, 0x0, 0xf3, 0x1, 0xf8, 0x0, 0x0, 0x9,
0xd0, 0x0, 0x9, 0xd0, 0x8, 0xf1, 0x0, 0x0,
0x0, 0xcd, 0x76, 0xbf, 0x30, 0xe, 0xa0, 0x0,
0x0, 0x0, 0x7, 0xcd, 0x92, 0x0, 0x3f, 0x50,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5f,
0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x4f, 0x70, 0x0, 0x61, 0x0, 0x0, 0x0, 0x0,
0x0, 0xc, 0xf9, 0x7c, 0xf6, 0x0, 0x0, 0x0,
0x0, 0x0, 0x1, 0xaf, 0xfb, 0x40, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* U+264D "♍" */
0xa, 0x90, 0x7, 0xb6, 0x0, 0xab, 0x20, 0x0,
0x0, 0x7, 0xf4, 0x3f, 0xee, 0x7, 0xef, 0xa0,
0x0, 0x0, 0x1, 0xfa, 0xca, 0x6f, 0x7f, 0x3d,
0xf0, 0x0, 0x0, 0x0, 0xcf, 0xf1, 0x2f, 0xfa,
0x9, 0xf1, 0x13, 0x0, 0x0, 0xaf, 0x80, 0xf,
0xf3, 0x8, 0xf1, 0xcf, 0x40, 0x0, 0xaf, 0x20,
0xf, 0xd0, 0x8, 0xf6, 0xef, 0xc0, 0x0, 0xaf,
0x0, 0xf, 0xa0, 0x8, 0xfd, 0x6a, 0xf2, 0x0,
0xaf, 0x0, 0xf, 0xa0, 0x8, 0xfd, 0x5, 0xf5,
0x0, 0xaf, 0x0, 0xf, 0xa0, 0x8, 0xf6, 0x3,
0xf6, 0x0, 0xaf, 0x0, 0xf, 0xa0, 0x8, 0xf2,
0x1, 0xf6, 0x0, 0xaf, 0x0, 0xf, 0xa0, 0x8,
0xf1, 0x3, 0xf4, 0x0, 0xaf, 0x0, 0xf, 0xa0,
0x8, 0xf1, 0x7, 0xf1, 0x0, 0xaf, 0x0, 0xf,
0xa0, 0x8, 0xf1, 0xd, 0xc0, 0x0, 0xaf, 0x0,
0xf, 0xa0, 0x8, 0xf1, 0x6f, 0x50, 0x0, 0xaf,
0x0, 0xf, 0xa0, 0x8, 0xf4, 0xfc, 0x0, 0x0,
0xaf, 0x0, 0xf, 0xa0, 0x7, 0xfe, 0xd1, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x19, 0xfc, 0x10,
0x0, 0x0, 0x0, 0x0, 0x0, 0x2a, 0xff, 0xf9,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5c, 0x71,
0x9f, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x1f, 0xc0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0,
/* U+264E "♎" */
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x8e, 0xff, 0xc5, 0x0,
0x0, 0x0, 0x0, 0x0, 0xc, 0xfb, 0x89, 0xef,
0x80, 0x0, 0x0, 0x0, 0x0, 0x9f, 0x40, 0x0,
0x1c, 0xf4, 0x0, 0x0, 0x0, 0x0, 0xfa, 0x0,
0x0, 0x1, 0xfa, 0x0, 0x0, 0x0, 0x3, 0xf5,
0x0, 0x0, 0x0, 0xcc, 0x0, 0x0, 0x0, 0x4,
0xf4, 0x0, 0x0, 0x0, 0xbc, 0x0, 0x0, 0x0,
0x1, 0xf7, 0x0, 0x0, 0x0, 0xe9, 0x0, 0x0,
0x0, 0x0, 0xbf, 0x30, 0x0, 0x9, 0xf3, 0x0,
0x0, 0x9f, 0xff, 0xff, 0xf0, 0x0, 0x8f, 0xff,
0xff, 0xf1, 0x48, 0x88, 0x88, 0x80, 0x0, 0x58,
0x88, 0x88, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x58, 0x88, 0x88,
0x88, 0x88, 0x88, 0x88, 0x88, 0x80, 0x9f, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
/* U+264F "♏" */
0x78, 0x0, 0x49, 0x60, 0x8, 0x92, 0x0, 0x0,
0x0, 0x5, 0xf4, 0x2f, 0xef, 0x17, 0xef, 0x80,
0x0, 0x0, 0x0, 0xe, 0xba, 0xa4, 0xf7, 0xf3,
0xce, 0x0, 0x0, 0x0, 0x0, 0xbf, 0xe1, 0xf,
0xfb, 0x9, 0xf0, 0x0, 0x0, 0x0, 0xb, 0xf7,
0x0, 0xff, 0x20, 0x8f, 0x10, 0x0, 0x0, 0x0,
0xbf, 0x20, 0xf, 0xd0, 0x8, 0xf1, 0x0, 0x0,
0x0, 0xb, 0xf0, 0x0, 0xfa, 0x0, 0x8f, 0x10,
0x0, 0x0, 0x0, 0xbf, 0x0, 0xf, 0xa0, 0x8,
0xf1, 0x0, 0x0, 0x0, 0xb, 0xf0, 0x0, 0xfa,
0x0, 0x8f, 0x10, 0x0, 0x0, 0x0, 0xbf, 0x0,
0xf, 0xa0, 0x8, 0xf1, 0x0, 0x0, 0x0, 0xb,
0xf0, 0x0, 0xfa, 0x0, 0x8f, 0x10, 0x0, 0x0,
0x0, 0xbf, 0x0, 0xf, 0xa0, 0x8, 0xf1, 0x0,
0x0, 0x0, 0xb, 0xf0, 0x0, 0xfa, 0x0, 0x8f,
0x10, 0x0, 0x0, 0x0, 0xbf, 0x0, 0xf, 0xa0,
0x8, 0xf1, 0x0, 0x0, 0x0, 0xb, 0xf0, 0x0,
0xfa, 0x0, 0x8f, 0x10, 0x0, 0x0, 0x0, 0xbf,
0x0, 0xf, 0xa0, 0x8, 0xf1, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x5f, 0x70, 0x3,
0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xbf,
0xa7, 0x9f, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x7c, 0xde, 0xfb, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x3b, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0,
/* U+2650 "♐" */
0x0, 0x0, 0x0, 0x2, 0x63, 0x10, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x5f, 0xff, 0xfd, 0xb9,
0x30, 0x0, 0x0, 0x0, 0x0, 0x25, 0x79, 0xbf,
0xf9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5,
0xff, 0xb0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5,
0xfa, 0xbd, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5,
0xfa, 0x8, 0xf0, 0x0, 0x20, 0x0, 0x0, 0x5,
0xfa, 0x0, 0x6f, 0x20, 0xe, 0xc0, 0x0, 0x5,
0xfa, 0x0, 0x4, 0xf4, 0x0, 0x6f, 0xc0, 0x5,
0xfa, 0x0, 0x0, 0x2f, 0x60, 0x0, 0x6f, 0xc6,
0xfa, 0x0, 0x0, 0x0, 0x72, 0x0, 0x0, 0x6f,
0xfa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5,
0xff, 0xc0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5,
0xfa, 0x7f, 0xc0, 0x0, 0x0, 0x0, 0x0, 0x5,
0xfa, 0x0, 0x7f, 0xc0, 0x0, 0x0, 0x0, 0x5,
0xfa, 0x0, 0x0, 0x6f, 0x40, 0x0, 0x0, 0x5,
0xfa, 0x0, 0x0, 0x0, 0x20, 0x0, 0x0, 0x0,
0x28, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0,
/* U+2651 "♑" */
0x0, 0x0, 0x0, 0x0, 0x7a, 0x0, 0x0, 0x0,
0x0, 0x0, 0x7, 0xb5, 0x0, 0x0, 0x3f, 0xf2,
0x0, 0x0, 0x0, 0x0, 0x0, 0x4a, 0xf7, 0x0,
0xd, 0xce, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0,
0x7, 0xf1, 0x7, 0xf2, 0x9b, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0xf, 0x60, 0xe8, 0x6, 0xe0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xba, 0x5f,
0x20, 0x2f, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0,
0x7, 0xda, 0xb0, 0x0, 0xf4, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x4f, 0xf7, 0x0, 0xe, 0x60,
0x0, 0x0, 0x0, 0x0, 0x0, 0x2, 0xff, 0x30,
0x0, 0xc8, 0x0, 0x1, 0x31, 0x0, 0x0, 0x0,
0xf, 0xf0, 0x0, 0xa, 0xa0, 0x1b, 0xff, 0xfa,
0x10, 0x0, 0x0, 0xfe, 0x0, 0x0, 0x8d, 0xc,
0xe5, 0x14, 0xeb, 0x0, 0x0, 0xd, 0xd0, 0x0,
0x4, 0xf9, 0xf2, 0x0, 0x3, 0xf3, 0x0, 0x0,
0x11, 0x0, 0x0, 0xe, 0xf7, 0x0, 0x0, 0xf,
0x60, 0x0, 0x0, 0x0, 0x0, 0x0, 0x9f, 0x20,
0x0, 0x0, 0xf5, 0x0, 0x0, 0x0, 0x0, 0x0,
0xd, 0xfd, 0x10, 0x0, 0x8f, 0x10, 0x0, 0x0,
0x0, 0x0, 0x3, 0xf5, 0xce, 0x97, 0xbf, 0x60,
0x0, 0x0, 0x0, 0x0, 0x0, 0xbd, 0x0, 0x6b,
0xda, 0x30, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5f,
0x40, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x67, 0xbf, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xc, 0xda, 0x40, 0x0, 0x0, 0x0,
0x0, 0x0,
/* U+2652 "♒" */
0x0, 0x0, 0x70, 0x0, 0x3, 0x40, 0x0, 0x5,
0x20, 0x0, 0x0, 0xc, 0xf9, 0x0, 0x3e, 0xf5,
0x0, 0x6f, 0xe2, 0x0, 0x0, 0xce, 0x6f, 0x93,
0xeb, 0x9f, 0x56, 0xf7, 0xce, 0x20, 0x1c, 0xe2,
0x5, 0xff, 0xb0, 0x9, 0xff, 0x60, 0xc, 0xe2,
0x2c, 0x20, 0x0, 0x5b, 0x0, 0x0, 0x96, 0x0,
0x0, 0xb3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x60, 0x0, 0x3, 0x40, 0x0, 0x5,
0x20, 0x0, 0x0, 0xc, 0xf9, 0x0, 0x3f, 0xf4,
0x0, 0x6f, 0xe2, 0x0, 0x0, 0xce, 0x6f, 0x83,
0xfa, 0x9f, 0x45, 0xf8, 0xce, 0x20, 0x1c, 0xe2,
0x4, 0xff, 0xa0, 0x9, 0xff, 0x70, 0xc, 0xe2,
0x1b, 0x20, 0x0, 0x4a, 0x0, 0x0, 0x97, 0x0,
0x0, 0xb3,
/* U+2653 "♓" */
0x5, 0x30, 0x0, 0x0, 0x0, 0x0, 0x55, 0x0,
0x8f, 0x20, 0x0, 0x0, 0x0, 0x8f, 0x40, 0x0,
0xcd, 0x0, 0x0, 0x0, 0x4f, 0x70, 0x0, 0x3,
0xf7, 0x0, 0x0, 0xd, 0xd0, 0x0, 0x0, 0xb,
0xe0, 0x0, 0x6, 0xf5, 0x0, 0x0, 0x0, 0x5f,
0x40, 0x0, 0xbe, 0x0, 0x0, 0x0, 0x1, 0xf8,
0x0, 0xf, 0xb0, 0x0, 0x0, 0x11, 0x1f, 0xb1,
0x24, 0xf9, 0x22, 0x10, 0x1f, 0xff, 0xff, 0xff,
0xff, 0xff, 0xfd, 0x0, 0x22, 0x2e, 0xc2, 0x25,
0xf8, 0x22, 0x20, 0x0, 0x0, 0xfa, 0x0, 0xf,
0x80, 0x0, 0x0, 0x0, 0x2f, 0x70, 0x0, 0xdb,
0x0, 0x0, 0x0, 0x7, 0xf2, 0x0, 0x9, 0xf1,
0x0, 0x0, 0x0, 0xdc, 0x0, 0x0, 0x3f, 0x70,
0x0, 0x0, 0x6f, 0x40, 0x0, 0x0, 0xaf, 0x10,
0x0, 0x1e, 0xa0, 0x0, 0x0, 0x1, 0xdb, 0x0,
0xc, 0xd0, 0x0, 0x0, 0x0, 0x2, 0xfa, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
};
/*---------------------
* GLYPH DESCRIPTION
*--------------------*/
static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = {
{.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */,
{.bitmap_index = 0, .adv_w = 386, .box_w = 22, .box_h = 21, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 231, .adv_w = 364, .box_w = 20, .box_h = 22, .ofs_x = 1, .ofs_y = -4},
{.bitmap_index = 451, .adv_w = 358, .box_w = 18, .box_h = 19, .ofs_x = 2, .ofs_y = -2},
{.bitmap_index = 622, .adv_w = 379, .box_w = 21, .box_h = 16, .ofs_x = 1, .ofs_y = 0},
{.bitmap_index = 790, .adv_w = 328, .box_w = 18, .box_h = 23, .ofs_x = 1, .ofs_y = -6},
{.bitmap_index = 997, .adv_w = 334, .box_w = 18, .box_h = 21, .ofs_x = 1, .ofs_y = -5},
{.bitmap_index = 1186, .adv_w = 346, .box_w = 18, .box_h = 16, .ofs_x = 2, .ofs_y = -1},
{.bitmap_index = 1330, .adv_w = 350, .box_w = 19, .box_h = 21, .ofs_x = 2, .ofs_y = -5},
{.bitmap_index = 1530, .adv_w = 339, .box_w = 17, .box_h = 17, .ofs_x = 2, .ofs_y = -1},
{.bitmap_index = 1675, .adv_w = 363, .box_w = 21, .box_h = 20, .ofs_x = 1, .ofs_y = -3},
{.bitmap_index = 1885, .adv_w = 381, .box_w = 20, .box_h = 13, .ofs_x = 2, .ofs_y = 0},
{.bitmap_index = 2015, .adv_w = 302, .box_w = 15, .box_h = 18, .ofs_x = 2, .ofs_y = -1}
};
/*---------------------
* CHARACTER MAPPING
*--------------------*/
/*Collect the unicode lists and glyph_id offsets*/
static const lv_font_fmt_txt_cmap_t cmaps[] =
{
{
.range_start = 9800, .range_length = 12, .glyph_id_start = 1,
.unicode_list = NULL, .glyph_id_ofs_list = NULL, .list_length = 0, .type = LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY
}
};
/*--------------------
* ALL CUSTOM DATA
*--------------------*/
#if LVGL_VERSION_MAJOR == 8
/*Store all the custom data of the font*/
static lv_font_fmt_txt_glyph_cache_t cache;
#endif
#if LVGL_VERSION_MAJOR >= 8
static const lv_font_fmt_txt_dsc_t font_dsc = {
#else
static lv_font_fmt_txt_dsc_t font_dsc = {
#endif
.glyph_bitmap = glyph_bitmap,
.glyph_dsc = glyph_dsc,
.cmaps = cmaps,
.kern_dsc = NULL,
.kern_scale = 0,
.cmap_num = 1,
.bpp = 4,
.kern_classes = 0,
.bitmap_format = 0,
#if LVGL_VERSION_MAJOR == 8
.cache = &cache
#endif
};
/*-----------------
* PUBLIC FONT
*----------------*/
/*Initialize a public general font descriptor*/
#if LVGL_VERSION_MAJOR >= 8
const lv_font_t lv_font_zodiac_26 = {
#else
lv_font_t lv_font_zodiac_26 = {
#endif
.get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/
.get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/
.line_height = 24, /*The maximum line height required by the font*/
.base_line = 6, /*Baseline measured from the bottom of the line*/
#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0)
.subpx = LV_FONT_SUBPX_NONE,
#endif
#if LV_VERSION_CHECK(7, 4, 0) || LVGL_VERSION_MAJOR >= 8
.underline_position = -2,
.underline_thickness = 1,
#endif
.dsc = &font_dsc, /*The custom font data. Will be accessed by `get_glyph_bitmap/dsc` */
#if LV_VERSION_CHECK(8, 2, 0) || LVGL_VERSION_MAJOR >= 9
.fallback = NULL,
#endif
.user_data = NULL,
};
#endif /*#if LV_FONT_ZODIAC_26*/

View File

@ -0,0 +1,52 @@
// AppConfig.h —— 全局常量与编译开关
#pragma once
// ============================ 品牌 ============================
// 客户端品牌只有一个来源:显示、启动动画、网页门户、串口横幅、mDNS、热点名
// 全部从这里取值。改名只改这一处,不要在别处硬编码字符串。
#define BRAND_NAME "nex_buddy"
// 版本号 = 这一版固件的唯一身份,OTA 全靠它比大小:
// * 服务端只推「比自己大」的版本(点名推送可降级,用于回滚)
// * 设备 check 时把它当 current 传上去,回来相等就不升
// 所以**每次发版必须改这里**,否则设备升完还会被反复推同一版。
#define BRAND_VERSION "0.1.8"
#define BRAND_TAGLINE "星盘 · 天气 · 音乐" // 启动动画名下的副标题
#define BRAND_MODEL "nex_buddy-knob"
// 兼容旧宏(历史代码里还在用,值统一指向新品牌)
#define KNOBOS_NAME BRAND_NAME
#define KNOBOS_VERSION BRAND_VERSION
#define SCREEN_W 360
#define SCREEN_H 360
#define SCREEN_R (SCREEN_W / 2) // 180,圆屏半径
// 圆环 UI 设计基准(半径)
#define RING_OUTER 168 // 最外圈弧
#define RING_ICON 112 // 主菜单图标环
#define RING_CONTENT 104 // 内容安全区
// LVGL 绘制缓冲区行数(内部 RAM:360 × 40 × 2 ≈ 28 KB)
// 原来 72 行要吃掉 51KB;内部堆只剩 ~40KB,20KB 的同步任务栈直接申请不到
// (现象就是"点了同步没动静")。降到 40 行省出 23KB,渲染照样够用。
#define LV_BUF_ROWS 40
// 设备默认 AP(首次配网)
#define DEFAULT_AP_SSID BRAND_NAME
#define DEFAULT_AP_PASS "12345678"
#define MDNS_HOSTNAME "nexbuddy"
// 配网成功后热点再保留多久(毫秒)。
// 手机在配网页点「连接」后设备会切到 STA,热点一关页面就失联,
// 页面就没法把「连上了、新地址是 x」弹出来。留一段宽限时间让它读完再关。
#define AP_GRACE_MS 60000
// 热点兜底期间多久再试一次 STA(路由器重启/2.4G 恢复后能自己回网)
#define AP_RETRY_MS 300000
// 服务端地址出厂默认值(用户可在配网页修改,NVS 保存后立即生效)。
// 开发期指向跑 nex_buddy 的那台机器(本机 192.168.2.147:8100,DHCP 会变,改配置以设备内 NVS 为准);
// 正式部署时改成平台域名再出厂。已烧录的设备 NVS 里存着旧值,改这里不影响它们。
#define DEFAULT_SERVER_URL "http://192.168.2.147:8100"
// 串口调试
#define LOG_ENABLED 1

View File

@ -0,0 +1,53 @@
// BoardPins.h —— 硬件引脚唯一真源
//
// 依据:原理图 V1.0 + 实物实测。
// 注意:原厂 demo 的 pincfg.h 里 SD_MMC 引脚(13~18)是错的,与屏幕 QSPI 冲突,
// 本文件按原理图修正为 4/3/5/6/42/2。
#pragma once
// ---------- 显示 ST77916 (QSPI) ----------
#define PIN_LCD_SCK 13
#define PIN_LCD_CS 14
#define PIN_LCD_D0 15
#define PIN_LCD_D1 16
#define PIN_LCD_D2 17
#define PIN_LCD_D3 18
#define PIN_LCD_RST 21
#define PIN_LCD_BLK 47 // 背光,PWM
#define PIN_LCD_TE 48 // 撕裂同步(当前未用)
// ---------- 触摸 CST816S (I2C,与 DRV2605L 共用总线) ----------
#define PIN_TOUCH_SDA 11
#define PIN_TOUCH_SCL 12
#define PIN_TOUCH_RST 10
#define PIN_TOUCH_INT 9
#define TOUCH_I2C_ADDR 0x15
// ---------- 旋转编码器 ----------
#define PIN_ENC_A 8
#define PIN_ENC_B 7
// ---------- 按键 ----------
#define PIN_BTN_BOOT 0
// ---------- TF 卡 (SDMMC 4-bit) ----------
#define PIN_SD_CLK 4
#define PIN_SD_CMD 3
#define PIN_SD_D0 5
#define PIN_SD_D1 6
#define PIN_SD_D2 42
#define PIN_SD_D3 2
// ---------- 电池检测 ----------
// R62/R63 各 10K 分压,上端接 5V/VCC 主轨:未插 USB 时 V×2 ≈ VBAT
#define PIN_BATT_ADC 1
#define BATT_DIVIDER 2.0f
// ---------- 触觉 DRV2605L ----------
#define PIN_HAPTIC_EN 38
#define HAPTIC_I2C_ADDR 0x5A
// ---------- 与副控 ESP32 的 UART ----------
#define PIN_UART_TX 40 // S3 → 副控
#define PIN_UART_RX 39 // 副控 → S3
#define UART_BAUD 921600 // 音频码流要走这条线:128kbps MP3 ≈ 16KB/s,115200 只剩 11KB/s 不够

59
src/core/App.h 100644
View File

@ -0,0 +1,59 @@
#pragma once
// App.h —— 应用基类
//
// 约定:
// build() 只在第一次进入时调用一次,负责创建全部 LVGL 对象;
// onEnter()/onExit() 每次进出都调用,用于启停定时器、刷新数据;
// onTick() 由主循环驱动(约 20~30 Hz),只做轻量刷新,禁止阻塞;
// onKnob() 返回 true 表示已消费该次旋转,否则交给框架(用于翻页等)。
#include <lvgl.h>
#include "../assets/icons.h"
struct AppMeta {
const char* id; // 唯一标识,同时是设置里的身份
const char* name; // 中文名
const char* symbol; // LVGL 内置符号(保留给不支持的场景)
const lv_img_dsc_t* icon; // 线性图标,见 tools/gen_icons.py
uint32_t accent; // 应用强调色
bool hasSettings;
bool needBind; // 进入前必须已绑定设备(未绑定则拉起绑定页)
};
// 手势类型(由 Shell 层统一识别后下发)
enum class Gesture : uint8_t { SwipeUp, SwipeDown, SwipeLeft, SwipeRight, Tap, LongPress };
class App {
public:
virtual ~App() {}
virtual const AppMeta& meta() const = 0;
// 生命周期
virtual void build(lv_obj_t* root) = 0;
virtual void onEnter() {}
virtual void onExit() {}
// 周期驱动
virtual void onTick(uint32_t nowMs) { (void)nowMs; }
// 输入
virtual bool onKnob(int32_t diff) { (void)diff; return false; }
virtual bool onGesture(Gesture g) { (void)g; return false; }
// 触摸按下时通知应用(用于记录"按下那一刻的滚动位置")
virtual void onPress(int x, int y) { (void)x; (void)y; }
// 应用可否放行这次滑动手势。返回 false = Shell 不处理。
// 典型用途:设置页手指拖的是自己的列表(列表真的滚动了),
// 这时不能把上滑当成"打开一级菜单",否则用户滑一下列表就"退出"了。
virtual bool allowShellSwipe(int dx, int dy) { (void)dx; (void)dy; return true; }
// 应用内下拉设置面板:把设置项画到 list 容器里(可为空)
virtual void buildAppSettings(lv_obj_t* list) { (void)list; }
// 供 Shell 访问的对象
lv_obj_t* root() const { return _root; }
void setRoot(lv_obj_t* r) { _root = r; }
protected:
lv_obj_t* _root = nullptr;
};

View File

@ -0,0 +1,20 @@
#include "AppManager.h"
#include <string.h>
AppManager appMgr;
void AppManager::add(App* a) {
if (_n < MAX && a) _apps[_n++] = a;
}
App* AppManager::byId(const char* id) const {
for (int i = 0; i < _n; i++)
if (strcmp(_apps[i]->meta().id, id) == 0) return _apps[i];
return nullptr;
}
int AppManager::indexOf(App* a) const {
for (int i = 0; i < _n; i++)
if (_apps[i] == a) return i;
return -1;
}

View File

@ -0,0 +1,20 @@
#pragma once
// AppManager.h —— 应用注册表
#include "App.h"
class AppManager {
public:
void add(App* a);
int count() const { return _n; }
App* at(int i) const { return (i >= 0 && i < _n) ? _apps[i] : nullptr; }
App* byIndex(uint8_t i) const { return at(i); }
App* byId(const char* id) const;
int indexOf(App* a) const;
private:
static const int MAX = 8;
App* _apps[MAX] = {nullptr};
int _n = 0;
};
extern AppManager appMgr;

12
src/core/Log.h 100644
View File

@ -0,0 +1,12 @@
#pragma once
// Log.h —— 统一日志出口,接 USB 串口
#include <Arduino.h>
#include "../config/AppConfig.h"
#if LOG_ENABLED
#define LOGF(fmt, ...) Serial.printf("[%7lu] " fmt "\n", millis(), ##__VA_ARGS__)
#define LOG(tag, fmt, ...) Serial.printf("[%7lu][%s] " fmt "\n", millis(), tag, ##__VA_ARGS__)
#else
#define LOGF(fmt, ...) do {} while (0)
#define LOG(tag, fmt, ...) do {} while (0)
#endif

View File

@ -0,0 +1,121 @@
#include "Settings.h"
#include "Log.h"
#include "../config/AppConfig.h"
// 序号即 boot 索引:必须与 knob_os.ino 里 appMgr.add() 的注册顺序一致
// (0=时钟 1=相册 2=音乐 3=星盘 4=我的 5=天气 6=设置)
static const SettingDesc TABLE[] = {
// key label group type def min max step unit options defText
{"sys.bright", "亮度", "系统", SType::INT, 80, 10, 100, 5, "%", nullptr, nullptr},
{"sys.screen_to", "自动息屏", "系统", SType::INT, 60, 0, 300, 10, "s", nullptr, nullptr},
{"sys.haptic", "触感强度", "系统", SType::ENUM, 2, 0, 3, 1, nullptr, "关|轻|中|强", nullptr},
{"sys.motor", "马达类型", "系统", SType::ENUM, 1, 0, 1, 1, nullptr, "转子|线性", nullptr},
{"sys.boot", "开机启动", "系统", SType::ENUM, 0, 0, 6, 1, nullptr, "时钟|相册|音乐|星盘|我的|天气|设置", nullptr},
{"sys.accent", "主题色", "系统", SType::ENUM, 0, 0, 5, 1, nullptr, "暖橙|青蓝|薄荷|绛紫|樱粉|石青", nullptr},
{"sys.cal24", "24 小时制", "系统", SType::BOOL, 1, 0, 1, 1, nullptr, nullptr, nullptr},
// 不设时区项:时区跟账号资料走(服务端校时下发),设备侧不再给第二个入口——
// 两处都能改必然打架,曾出现账号改了重庆、设备还按手动值算时间。
{"clk.work", "专注时长", "时钟", SType::INT, 25, 1, 90, 1, "min", nullptr, nullptr},
{"clk.short", "短休息", "时钟", SType::INT, 5, 1, 30, 1, "min", nullptr, nullptr},
{"clk.long", "长休息", "时钟", SType::INT, 15, 1, 60, 1, "min", nullptr, nullptr},
{"clk.rounds", "长休间隔", "时钟", SType::INT, 4, 2, 8, 1, "轮", nullptr, nullptr},
{"clk.auto", "自动续接", "时钟", SType::BOOL, 0, 0, 1, 1, nullptr, nullptr, nullptr},
{"clk.sound", "结束提示", "时钟", SType::BOOL, 1, 0, 1, 1, nullptr, nullptr, nullptr},
{"clk.dial", "表盘样式", "时钟", SType::ENUM, 0, 0, 2, 1, nullptr, "极简|刻度|光环", nullptr},
{"gal.interval", "切换间隔", "相册", SType::INT, 10, 3, 120, 1, "s", nullptr, nullptr},
{"gal.order", "播放顺序", "相册", SType::ENUM, 0, 0, 1, 1, nullptr, "顺序|随机", nullptr},
{"gal.fit", "图片填充", "相册", SType::ENUM, 0, 0, 1, 1, nullptr, "裁切|留白", nullptr},
{"mus.vol", "音量", "音乐", SType::INT, 60, 0, 100, 5, "%", nullptr, nullptr},
// 播放模式只管"一首放完之后接下来放哪首";旋钮切歌永远是手动挑,不受它影响
{"mus.mode", "播放模式", "音乐", SType::ENUM, 0, 0, 1, 1, nullptr, "顺序|随机", nullptr},
// 天气不设城市/经纬度:位置只认账号资料里的"常住地"(服务端解析成经纬度下发)。
// 同一件事在设备里存两份必然打架——曾在设置里留了城市,结果账号改成重庆后
// 天气页还按旧的城市拉数据,看起来像"资料没同步"。
// wx.interval 是**隐藏项**(不在界面上翻),但必须注册:WeatherService 靠它
// 算"多久拉一次",键不存在时 getI() 返回 0,退化成每个 loop 都去请求服务端
// (实测串口每 200ms 一条 WX 日志,等于把设备当 DDOS 客户端用)。
{"wx.interval", "刷新间隔", "天气", SType::INT, 30, 5, 180, 5, "min", nullptr, nullptr},
{"net.ssid", "WiFi 名称", "网络", SType::TEXT, 0, 0, 0, 0, nullptr, nullptr, ""},
{"net.pass", "WiFi 密码", "网络", SType::TEXT, 0, 0, 0, 0, nullptr, nullptr, ""},
{"net.server", "服务端地址", "网络", SType::TEXT, 0, 0, 0, 0, nullptr, nullptr, DEFAULT_SERVER_URL},
// 平台账号:不出现在设置界面(界面只列 系统/时钟/相册/音乐/天气/网络 分组),
// 由 PlatformService 读写,设置里的"关于"页读出来展示。
{"pf.token", "设备令牌", "账号", SType::TEXT, 0, 0, 0, 0, nullptr, nullptr, ""},
{"pf.device", "设备 ID", "账号", SType::TEXT, 0, 0, 0, 0, nullptr, nullptr, ""},
};
static const size_t TABLE_N = sizeof(TABLE) / sizeof(TABLE[0]);
Settings settings;
static int findIdx(const char* key) {
for (size_t i = 0; i < TABLE_N; i++)
if (strcmp(TABLE[i].key, key) == 0) return (int)i;
return -1;
}
const SettingDesc* Settings::table(size_t& count) { count = TABLE_N; return TABLE; }
const SettingDesc* Settings::find(const char* key) {
int i = findIdx(key);
return i < 0 ? nullptr : &TABLE[i];
}
int Settings::indexOf(const char* key) { return findIdx(key); }
void Settings::begin() {
_nvs.begin("knobos", false);
_ready = true;
LOGF("settings loaded, %u items", (unsigned)TABLE_N);
}
void Settings::broadcast(const char* key) {
if (_cb) _cb(key);
}
int32_t Settings::getI(const char* key) {
int i = findIdx(key);
if (i < 0) return 0;
const SettingDesc& d = TABLE[i];
if (d.type == SType::TEXT) return 0;
return _nvs.getInt(key, d.def);
}
void Settings::setI(const char* key, int32_t v) {
int i = findIdx(key);
if (i < 0) return;
const SettingDesc& d = TABLE[i];
if (d.type != SType::TEXT) {
if (v < d.min) v = d.min;
if (v > d.max) v = d.max;
}
if (_nvs.getInt(key, d.def) == v) return; // 无变化不广播
_nvs.putInt(key, v);
broadcast(key);
}
String Settings::getS(const char* key) {
int i = findIdx(key);
if (i < 0) return String();
const SettingDesc& d = TABLE[i];
String def = d.defText ? String(d.defText) : String();
return _nvs.getString(key, def);
}
void Settings::setS(const char* key, const String& v) {
int i = findIdx(key);
if (i < 0) return;
if (_nvs.getString(key, TABLE[i].defText ? String(TABLE[i].defText) : String()) == v) return;
_nvs.putString(key, v);
broadcast(key);
}
void Settings::resetAll() {
_nvs.clear();
broadcast("*");
LOGF("settings reset to default");
}

View File

@ -0,0 +1,68 @@
#pragma once
// Settings.h —— 表驱动的配置系统
//
// 一张描述表同时驱动三处:
// 1. 设备端"设置"应用(自动生成行)
// 2. 应用内下拉设置面板
// 3. Web 门户(自动生成 JSON / 表单)
// 新增一个设置项 = 在 Settings.cpp 的表里加一行,无需改任何 UI 代码。
#include <Arduino.h>
#include <functional>
#include <Preferences.h>
enum class SType : uint8_t {
INT, // 整数,带 min/max/step/unit
BOOL, // 开关
ENUM, // 枚举,options 用 '|' 分隔
TEXT, // 字符串(SSID、经纬度、城市名)
};
struct SettingDesc {
const char* key; // NVS 键,≤15 字符
const char* label; // 中文标签
const char* group; // 分组名
SType type;
int32_t def; // INT/BOOL/ENUM 默认值
int32_t min;
int32_t max;
int32_t step;
const char* unit; // 单位后缀,可 nullptr
const char* options; // ENUM 选项,"顺序|随机"
const char* defText; // TEXT 默认值
};
class Settings {
public:
using ChangeCb = std::function<void(const char* key)>;
void begin();
// 描述表
static const SettingDesc* table(size_t& count);
static const SettingDesc* find(const char* key);
// 取值 / 赋值(写 NVS 并广播,值未变则不广播)
int32_t getI(const char* key);
void setI(const char* key, int32_t v);
String getS(const char* key);
void setS(const char* key, const String& v);
// 便捷封装
bool getB(const char* key) { return getI(key) != 0; }
void setB(const char* key, bool v) { setI(key, v ? 1 : 0); }
void onChange(ChangeCb cb) { _cb = cb; }
// 恢复出厂
void resetAll();
private:
void broadcast(const char* key);
static int indexOf(const char* key);
Preferences _nvs;
ChangeCb _cb;
bool _ready = false;
};
extern Settings settings;

299
src/hal/Display.cpp 100644
View File

@ -0,0 +1,299 @@
#include "Display.h"
#include "../config/AppConfig.h"
#include "../config/BoardPins.h"
#include "../core/Log.h"
#include "../core/Settings.h"
#include <ESP_Panel_Library.h>
#include <esp_heap_caps.h>
namespace hal {
static ESP_PanelLcd* _lcd = nullptr;
static ESP_PanelTouch* _touch = nullptr;
static ESP_PanelBacklight* _bl = nullptr;
static lv_disp_draw_buf_t _drawBuf;
static lv_disp_drv_t _dispDrv;
static lv_color_t* _buf = nullptr;
static uint32_t _lastAct = 0;
static bool _screenOn = true;
static uint8_t _bright = 80;
static TouchHook _touchHook;
static int _lastTouchX = 0;
static int _lastTouchY = 0;
// ST77916 厂商标定初始化序列(源自原厂 demo,勿随意改动)
static const esp_lcd_panel_vendor_init_cmd_t INIT_CMDS[] = {
{0xF0, (uint8_t[]){0x28}, 1, 0}, {0xF2, (uint8_t[]){0x28}, 1, 0},
{0x73, (uint8_t[]){0xF0}, 1, 0}, {0x7C, (uint8_t[]){0xD1}, 1, 0},
{0x83, (uint8_t[]){0xE0}, 1, 0}, {0x84, (uint8_t[]){0x61}, 1, 0},
{0xF2, (uint8_t[]){0x82}, 1, 0}, {0xF0, (uint8_t[]){0x00}, 1, 0},
{0xF0, (uint8_t[]){0x01}, 1, 0}, {0xF1, (uint8_t[]){0x01}, 1, 0},
{0xB0, (uint8_t[]){0x56}, 1, 0}, {0xB1, (uint8_t[]){0x4D}, 1, 0},
{0xB2, (uint8_t[]){0x24}, 1, 0}, {0xB4, (uint8_t[]){0x87}, 1, 0},
{0xB5, (uint8_t[]){0x44}, 1, 0}, {0xB6, (uint8_t[]){0x8B}, 1, 0},
{0xB7, (uint8_t[]){0x40}, 1, 0}, {0xB8, (uint8_t[]){0x86}, 1, 0},
{0xBA, (uint8_t[]){0x00}, 1, 0}, {0xBB, (uint8_t[]){0x08}, 1, 0},
{0xBC, (uint8_t[]){0x08}, 1, 0}, {0xBD, (uint8_t[]){0x00}, 1, 0},
{0xC0, (uint8_t[]){0x80}, 1, 0}, {0xC1, (uint8_t[]){0x10}, 1, 0},
{0xC2, (uint8_t[]){0x37}, 1, 0}, {0xC3, (uint8_t[]){0x80}, 1, 0},
{0xC4, (uint8_t[]){0x10}, 1, 0}, {0xC5, (uint8_t[]){0x37}, 1, 0},
{0xC6, (uint8_t[]){0xA9}, 1, 0}, {0xC7, (uint8_t[]){0x41}, 1, 0},
{0xC8, (uint8_t[]){0x01}, 1, 0}, {0xC9, (uint8_t[]){0xA9}, 1, 0},
{0xCA, (uint8_t[]){0x41}, 1, 0}, {0xCB, (uint8_t[]){0x01}, 1, 0},
{0xD0, (uint8_t[]){0x91}, 1, 0}, {0xD1, (uint8_t[]){0x68}, 1, 0},
{0xD2, (uint8_t[]){0x68}, 1, 0}, {0xF5, (uint8_t[]){0x00, 0xA5}, 2, 0},
{0xDD, (uint8_t[]){0x4F}, 1, 0}, {0xDE, (uint8_t[]){0x4F}, 1, 0},
{0xF1, (uint8_t[]){0x10}, 1, 0}, {0xF0, (uint8_t[]){0x00}, 1, 0},
{0xF0, (uint8_t[]){0x02}, 1, 0},
{0xE0, (uint8_t[]){0xF0, 0x0A, 0x10, 0x09, 0x09, 0x36, 0x35, 0x33, 0x4A, 0x29, 0x15, 0x15, 0x2E, 0x34}, 14, 0},
{0xE1, (uint8_t[]){0xF0, 0x0A, 0x0F, 0x08, 0x08, 0x05, 0x34, 0x33, 0x4A, 0x39, 0x15, 0x15, 0x2D, 0x33}, 14, 0},
{0xF0, (uint8_t[]){0x10}, 1, 0}, {0xF3, (uint8_t[]){0x10}, 1, 0},
{0xE0, (uint8_t[]){0x07}, 1, 0}, {0xE1, (uint8_t[]){0x00}, 1, 0},
{0xE2, (uint8_t[]){0x00}, 1, 0}, {0xE3, (uint8_t[]){0x00}, 1, 0},
{0xE4, (uint8_t[]){0xE0}, 1, 0}, {0xE5, (uint8_t[]){0x06}, 1, 0},
{0xE6, (uint8_t[]){0x21}, 1, 0}, {0xE7, (uint8_t[]){0x01}, 1, 0},
{0xE8, (uint8_t[]){0x05}, 1, 0}, {0xE9, (uint8_t[]){0x02}, 1, 0},
{0xEA, (uint8_t[]){0xDA}, 1, 0}, {0xEB, (uint8_t[]){0x00}, 1, 0},
{0xEC, (uint8_t[]){0x00}, 1, 0}, {0xED, (uint8_t[]){0x0F}, 1, 0},
{0xEE, (uint8_t[]){0x00}, 1, 0}, {0xEF, (uint8_t[]){0x00}, 1, 0},
{0xF8, (uint8_t[]){0x00}, 1, 0}, {0xF9, (uint8_t[]){0x00}, 1, 0},
{0xFA, (uint8_t[]){0x00}, 1, 0}, {0xFB, (uint8_t[]){0x00}, 1, 0},
{0xFC, (uint8_t[]){0x00}, 1, 0}, {0xFD, (uint8_t[]){0x00}, 1, 0},
{0xFE, (uint8_t[]){0x00}, 1, 0}, {0xFF, (uint8_t[]){0x00}, 1, 0},
{0x60, (uint8_t[]){0x40}, 1, 0}, {0x61, (uint8_t[]){0x04}, 1, 0},
{0x62, (uint8_t[]){0x00}, 1, 0}, {0x63, (uint8_t[]){0x42}, 1, 0},
{0x64, (uint8_t[]){0xD9}, 1, 0}, {0x65, (uint8_t[]){0x00}, 1, 0},
{0x66, (uint8_t[]){0x00}, 1, 0}, {0x67, (uint8_t[]){0x00}, 1, 0},
{0x68, (uint8_t[]){0x00}, 1, 0}, {0x69, (uint8_t[]){0x00}, 1, 0},
{0x6A, (uint8_t[]){0x00}, 1, 0}, {0x6B, (uint8_t[]){0x00}, 1, 0},
{0x70, (uint8_t[]){0x40}, 1, 0}, {0x71, (uint8_t[]){0x03}, 1, 0},
{0x72, (uint8_t[]){0x00}, 1, 0}, {0x73, (uint8_t[]){0x42}, 1, 0},
{0x74, (uint8_t[]){0xD8}, 1, 0}, {0x75, (uint8_t[]){0x00}, 1, 0},
{0x76, (uint8_t[]){0x00}, 1, 0}, {0x77, (uint8_t[]){0x00}, 1, 0},
{0x78, (uint8_t[]){0x00}, 1, 0}, {0x79, (uint8_t[]){0x00}, 1, 0},
{0x7A, (uint8_t[]){0x00}, 1, 0}, {0x7B, (uint8_t[]){0x00}, 1, 0},
{0x80, (uint8_t[]){0x48}, 1, 0}, {0x81, (uint8_t[]){0x00}, 1, 0},
{0x82, (uint8_t[]){0x06}, 1, 0}, {0x83, (uint8_t[]){0x02}, 1, 0},
{0x84, (uint8_t[]){0xD6}, 1, 0}, {0x85, (uint8_t[]){0x04}, 1, 0},
{0x86, (uint8_t[]){0x00}, 1, 0}, {0x87, (uint8_t[]){0x00}, 1, 0},
{0x88, (uint8_t[]){0x48}, 1, 0}, {0x89, (uint8_t[]){0x00}, 1, 0},
{0x8A, (uint8_t[]){0x08}, 1, 0}, {0x8B, (uint8_t[]){0x02}, 1, 0},
{0x8C, (uint8_t[]){0xD8}, 1, 0}, {0x8D, (uint8_t[]){0x04}, 1, 0},
{0x8E, (uint8_t[]){0x00}, 1, 0}, {0x8F, (uint8_t[]){0x00}, 1, 0},
{0x90, (uint8_t[]){0x48}, 1, 0}, {0x91, (uint8_t[]){0x00}, 1, 0},
{0x92, (uint8_t[]){0x0A}, 1, 0}, {0x93, (uint8_t[]){0x02}, 1, 0},
{0x94, (uint8_t[]){0xDA}, 1, 0}, {0x95, (uint8_t[]){0x04}, 1, 0},
{0x96, (uint8_t[]){0x00}, 1, 0}, {0x97, (uint8_t[]){0x00}, 1, 0},
{0x98, (uint8_t[]){0x48}, 1, 0}, {0x99, (uint8_t[]){0x00}, 1, 0},
{0x9A, (uint8_t[]){0x0C}, 1, 0}, {0x9B, (uint8_t[]){0x02}, 1, 0},
{0x9C, (uint8_t[]){0xDC}, 1, 0}, {0x9D, (uint8_t[]){0x04}, 1, 0},
{0x9E, (uint8_t[]){0x00}, 1, 0}, {0x9F, (uint8_t[]){0x00}, 1, 0},
{0xA0, (uint8_t[]){0x48}, 1, 0}, {0xA1, (uint8_t[]){0x00}, 1, 0},
{0xA2, (uint8_t[]){0x05}, 1, 0}, {0xA3, (uint8_t[]){0x02}, 1, 0},
{0xA4, (uint8_t[]){0xD5}, 1, 0}, {0xA5, (uint8_t[]){0x04}, 1, 0},
{0xA6, (uint8_t[]){0x00}, 1, 0}, {0xA7, (uint8_t[]){0x00}, 1, 0},
{0xA8, (uint8_t[]){0x48}, 1, 0}, {0xA9, (uint8_t[]){0x00}, 1, 0},
{0xAA, (uint8_t[]){0x07}, 1, 0}, {0xAB, (uint8_t[]){0x02}, 1, 0},
{0xAC, (uint8_t[]){0xD7}, 1, 0}, {0xAD, (uint8_t[]){0x04}, 1, 0},
{0xAE, (uint8_t[]){0x00}, 1, 0}, {0xAF, (uint8_t[]){0x00}, 1, 0},
{0xB0, (uint8_t[]){0x48}, 1, 0}, {0xB1, (uint8_t[]){0x00}, 1, 0},
{0xB2, (uint8_t[]){0x09}, 1, 0}, {0xB3, (uint8_t[]){0x02}, 1, 0},
{0xB4, (uint8_t[]){0xD9}, 1, 0}, {0xB5, (uint8_t[]){0x04}, 1, 0},
{0xB6, (uint8_t[]){0x00}, 1, 0}, {0xB7, (uint8_t[]){0x00}, 1, 0},
{0xB8, (uint8_t[]){0x48}, 1, 0}, {0xB9, (uint8_t[]){0x00}, 1, 0},
{0xBA, (uint8_t[]){0x0B}, 1, 0}, {0xBB, (uint8_t[]){0x02}, 1, 0},
{0xBC, (uint8_t[]){0xDB}, 1, 0}, {0xBD, (uint8_t[]){0x04}, 1, 0},
{0xBE, (uint8_t[]){0x00}, 1, 0}, {0xBF, (uint8_t[]){0x00}, 1, 0},
{0xC0, (uint8_t[]){0x10}, 1, 0}, {0xC1, (uint8_t[]){0x47}, 1, 0},
{0xC2, (uint8_t[]){0x56}, 1, 0}, {0xC3, (uint8_t[]){0x65}, 1, 0},
{0xC4, (uint8_t[]){0x74}, 1, 0}, {0xC5, (uint8_t[]){0x88}, 1, 0},
{0xC6, (uint8_t[]){0x99}, 1, 0}, {0xC7, (uint8_t[]){0x01}, 1, 0},
{0xC8, (uint8_t[]){0xBB}, 1, 0}, {0xC9, (uint8_t[]){0xAA}, 1, 0},
{0xD0, (uint8_t[]){0x10}, 1, 0}, {0xD1, (uint8_t[]){0x47}, 1, 0},
{0xD2, (uint8_t[]){0x56}, 1, 0}, {0xD3, (uint8_t[]){0x65}, 1, 0},
{0xD4, (uint8_t[]){0x74}, 1, 0}, {0xD5, (uint8_t[]){0x88}, 1, 0},
{0xD6, (uint8_t[]){0x99}, 1, 0}, {0xD7, (uint8_t[]){0x01}, 1, 0},
{0xD8, (uint8_t[]){0xBB}, 1, 0}, {0xD9, (uint8_t[]){0xAA}, 1, 0},
{0xF3, (uint8_t[]){0x01}, 1, 0}, {0xF0, (uint8_t[]){0x00}, 1, 0},
{0x21, (uint8_t[]){0x00}, 1, 0},
{0x11, (uint8_t[]){0x00}, 1, 120},
{0x29, (uint8_t[]){0x00}, 1, 0},
};
// ---- 截屏缓冲:一帧的各个矩形在刷屏时拼到这里 ----
static uint16_t* _capBuf = nullptr;
static bool _capOn = false;
static volatile bool _capDone = false;
void captureStart() {
if (!_capBuf) {
_capBuf = (uint16_t*)heap_caps_malloc(SCREEN_W * SCREEN_H * 2, MALLOC_CAP_SPIRAM);
if (!_capBuf) _capBuf = (uint16_t*)malloc(SCREEN_W * SCREEN_H * 2);
}
if (!_capBuf) return;
_capDone = false;
_capOn = true;
}
bool captureDone() { return _capDone; }
const uint16_t* captureBuffer() { return _capBuf; }
void captureStop() { _capOn = false; }
static void flushCb(lv_disp_drv_t* drv, const lv_area_t* area, lv_color_t* px) {
ESP_PanelLcd* lcd = (ESP_PanelLcd*)drv->user_data;
if (_capOn && _capBuf) {
const int w = area->x2 - area->x1 + 1;
const int h = area->y2 - area->y1 + 1;
const uint16_t* src = (const uint16_t*)px;
for (int y = 0; y < h; y++) {
int dy = area->y1 + y;
if (dy < 0 || dy >= SCREEN_H) continue;
int dx = area->x1;
int dw = w;
if (dx < 0) { dw += dx; dx = 0; }
if (dx + dw > SCREEN_W) dw = SCREEN_W - dx;
if (dw <= 0) continue;
memcpy(_capBuf + dy * SCREEN_W + dx, src + (size_t)y * w, (size_t)dw * 2);
}
if (lv_disp_flush_is_last(drv)) _capDone = true;
}
lcd->drawBitmap(area->x1, area->y1, area->x2 - area->x1 + 1,
area->y2 - area->y1 + 1, (const uint8_t*)px);
}
static bool flushDoneCb(void* userData) {
lv_disp_flush_ready((lv_disp_drv_t*)userData);
return false;
}
static void touchReadCb(lv_indev_drv_t* drv, lv_indev_data_t* data) {
ESP_PanelTouch* tp = (ESP_PanelTouch*)drv->user_data;
ESP_PanelTouchPoint p;
static bool lastPressed = false;
static TouchHook hook;
if (tp->readPoints(&p, 1) > 0) {
data->point.x = p.x;
data->point.y = p.y;
data->state = LV_INDEV_STATE_PRESSED;
notifyActivity();
if (!lastPressed) {
lastPressed = true;
hook = _touchHook;
if (hook) hook(true, p.x, p.y);
}
_lastTouchX = p.x;
_lastTouchY = p.y;
} else {
data->state = LV_INDEV_STATE_RELEASED;
if (lastPressed) {
lastPressed = false;
hook = _touchHook;
if (hook) hook(false, _lastTouchX, _lastTouchY);
}
}
}
bool displayBegin() {
// 背光先关,避免上电花屏
_bl = new ESP_PanelBacklight(PIN_LCD_BLK, true, true);
_bl->begin();
_bl->setBrightness(0);
// 触摸
ESP_PanelBus_I2C* i2c = new ESP_PanelBus_I2C(
PIN_TOUCH_SCL, PIN_TOUCH_SDA, ESP_LCD_TOUCH_IO_I2C_CST816S_CONFIG());
i2c->configI2cFreqHz(400000);
if (!i2c->begin()) LOG("HAL", "touch i2c begin failed");
_touch = new ESP_PanelTouch_CST816S(i2c, SCREEN_W, SCREEN_H, PIN_TOUCH_RST, PIN_TOUCH_INT);
if (!_touch->init() || !_touch->begin()) LOG("HAL", "touch init failed");
// 屏幕
ESP_PanelBus_QSPI* qspi = new ESP_PanelBus_QSPI(
PIN_LCD_CS, PIN_LCD_SCK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
qspi->configQspiFreqHz(50 * 1000 * 1000);
if (!qspi->begin()) LOG("HAL", "qspi begin failed");
_lcd = new ESP_PanelLcd_ST77916(qspi, 16, PIN_LCD_RST);
_lcd->configVendorCommands(INIT_CMDS, sizeof(INIT_CMDS) / sizeof(INIT_CMDS[0]));
if (!_lcd->init() || !_lcd->reset() || !_lcd->begin()) LOG("HAL", "lcd init failed");
_lcd->invertColor(true);
_lcd->displayOn();
// LVGL
_buf = (lv_color_t*)heap_caps_malloc(
LV_BUF_ROWS * SCREEN_W * sizeof(lv_color_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
if (!_buf) { LOG("HAL", "lvgl draw buffer alloc failed"); return false; }
lv_init();
lv_disp_draw_buf_init(&_drawBuf, _buf, nullptr, SCREEN_W * LV_BUF_ROWS);
lv_disp_drv_init(&_dispDrv);
_dispDrv.hor_res = SCREEN_W;
_dispDrv.ver_res = SCREEN_H;
_dispDrv.flush_cb = flushCb;
_dispDrv.draw_buf = &_drawBuf;
_dispDrv.user_data = (void*)_lcd;
lv_disp_t* disp = lv_disp_drv_register(&_dispDrv);
_lcd->attachDrawBitmapFinishCallback(flushDoneCb, (void*)disp->driver);
static lv_indev_drv_t indevDrv;
lv_indev_drv_init(&indevDrv);
indevDrv.type = LV_INDEV_TYPE_POINTER;
indevDrv.read_cb = touchReadCb;
indevDrv.user_data = (void*)_touch;
lv_indev_drv_register(&indevDrv);
_bright = (uint8_t)settings.getI("sys.bright");
setBrightness(_bright);
_lastAct = millis();
LOG("HAL", "display ready (%dx%d, bright=%u)", SCREEN_W, SCREEN_H, _bright);
return true;
}
void setBrightness(uint8_t pct) {
if (pct < 5) pct = 5;
if (pct > 100) pct = 100;
_bright = pct;
if (_bl && _screenOn) _bl->setBrightness(pct);
}
uint8_t brightness() { return _bright; }
void screenOff() {
if (!_screenOn) return;
_screenOn = false;
if (_bl) _bl->setBrightness(0);
LOG("HAL", "screen off");
}
void screenOn() {
_screenOn = true;
if (_bl) _bl->setBrightness(_bright);
_lastAct = millis();
}
bool screenIsOn() { return _screenOn; }
void notifyActivity() {
_lastAct = millis();
if (!_screenOn) screenOn();
}
void setTouchHook(TouchHook hook) { _touchHook = hook; }
void displayLoop() {
lv_timer_handler();
uint32_t timeout = (uint32_t)settings.getI("sys.screen_to");
if (timeout > 0 && _screenOn && millis() - _lastAct > timeout * 1000UL) {
screenOff();
// 息屏后立即唤醒 LVGL 渲染一帧,避免下次点亮残留旧画面
lv_timer_handler();
}
}
} // namespace hal

37
src/hal/Display.h 100644
View File

@ -0,0 +1,37 @@
#pragma once
// Display.h —— ST77916 QSPI 圆屏 + CST816S 触摸 + LVGL 绑定
#include <Arduino.h>
#include <functional>
#include <lvgl.h>
namespace hal {
bool displayBegin();
// 每帧泵:LVGL 处理 + 自动息屏
void displayLoop();
void setBrightness(uint8_t pct); // 10~100
uint8_t brightness();
void screenOff();
void screenOn();
bool screenIsOn();
// 任何用户交互都调用,用于刷新息屏计时
void notifyActivity();
// 触摸状态变化钩子(按下/抬起 + 坐标),供 Shell 做手势识别。
// LVGL 自身的点击照常工作,这里只旁路监听。
using TouchHook = std::function<void(bool pressed, int x, int y)>;
void setTouchHook(TouchHook hook);
// ---- 截屏(调试通道)----
// 不引入 lv_snapshot:那需要一整块额外图层,内存池放不下。
// 这里直接在刷屏回调里把一帧的各个矩形拼进一张全屏底图,几乎零额外开销。
void captureStart();
bool captureDone();
const uint16_t* captureBuffer(); // 360×360,LVGL 的 BGR565 排列
void captureStop();
} // namespace hal

View File

@ -0,0 +1,49 @@
#include "Encoder.h"
#include "bidi_switch_knob.h"
#include "../config/BoardPins.h"
#include "../core/Log.h"
#include "Display.h"
#include <atomic>
namespace hal {
static knob_handle_t _knob = nullptr;
static KnobCb _cb;
static std::atomic<int32_t> _pending{0};
static void onLeft(void* arg, void* data) {
(void)arg; (void)data;
_pending.fetch_add(-1, std::memory_order_relaxed);
}
static void onRight(void* arg, void* data) {
(void)arg; (void)data;
_pending.fetch_add(1, std::memory_order_relaxed);
}
bool encoderBegin(KnobCb cb) {
_cb = cb;
knob_config_t cfg = {
.gpio_encoder_a = PIN_ENC_A,
.gpio_encoder_b = PIN_ENC_B,
};
_knob = iot_knob_create(&cfg);
if (!_knob) {
LOG("HAL", "encoder create failed");
return false;
}
iot_knob_register_cb(_knob, KNOB_LEFT, onLeft, nullptr);
iot_knob_register_cb(_knob, KNOB_RIGHT, onRight, nullptr);
LOG("HAL", "encoder ready (A=%d B=%d)", PIN_ENC_A, PIN_ENC_B);
return true;
}
int32_t encoderTake() {
return _pending.exchange(0, std::memory_order_relaxed);
}
void encoderInject(int32_t diff) {
_pending.fetch_add(diff, std::memory_order_relaxed);
}
} // namespace hal

22
src/hal/Encoder.h 100644
View File

@ -0,0 +1,22 @@
#pragma once
// Encoder.h —— 旋转编码器(GPIO8/7)
//
// 驱动沿用原厂 bidi_switch_knob(esp_timer 周期扫描 + 双向去抖),
// 回调发生在定时器任务中,因此这里只做原子累加,由主循环取用。
#include <Arduino.h>
#include <functional>
namespace hal {
using KnobCb = std::function<void(int32_t diff)>;
bool encoderBegin(KnobCb cb);
// 取出自上次调用以来累积的刻度并清零(正值顺时针)
int32_t encoderTake();
// 调试用:凭空塞进来几格,等价于转了一下旋钮。
// 主机端调 UI 时没法真的去拧设备,靠它验证"旋钮 → 界面"这条链路。
void encoderInject(int32_t diff);
} // namespace hal

139
src/hal/Haptic.cpp 100644
View File

@ -0,0 +1,139 @@
#include "Haptic.h"
#include "../core/Log.h"
#include "../core/Settings.h"
#include "../config/BoardPins.h"
#include <Arduino.h>
#include <driver/i2c.h>
namespace hal {
// ---------------- DRV2605L 寄存器 ----------------
static const uint8_t REG_STATUS = 0x00;
static const uint8_t REG_MODE = 0x01;
static const uint8_t REG_LIBRARY = 0x03;
static const uint8_t REG_WAVESEQ1 = 0x04;
static const uint8_t REG_WAVESEQ2 = 0x05;
static const uint8_t REG_GO = 0x0C;
static const uint8_t REG_RATEDV = 0x16;
static const uint8_t REG_CLAMPV = 0x17;
static const uint8_t REG_FEEDBACK = 0x1A;
static const uint8_t REG_CONTROL3 = 0x1D;
// 触摸总线由 ESP32_Display_Panel 用 legacy i2c 驱动安装在 port 0 上。
// 同一 port 上可以对任意从地址发起传输,所以这里不再 Wire.begin()(那会抢引脚),
// 而是直接在已安装的 port 上跑命令链。
static const i2c_port_t BUS = I2C_NUM_0;
static bool _ready = false;
static uint8_t _level = 2;
static bool _isLra = true;
static uint32_t _lastTick = 0;
static uint32_t _lastAny = 0;
static bool wr(uint8_t reg, uint8_t val) {
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (HAPTIC_I2C_ADDR << 1) | I2C_MASTER_WRITE, true);
i2c_master_write_byte(cmd, reg, true);
i2c_master_write_byte(cmd, val, true);
i2c_master_stop(cmd);
esp_err_t err = i2c_master_cmd_begin(BUS, cmd, pdMS_TO_TICKS(40));
i2c_cmd_link_delete(cmd);
return err == ESP_OK;
}
static bool rd(uint8_t reg, uint8_t* out) {
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (HAPTIC_I2C_ADDR << 1) | I2C_MASTER_WRITE, true);
i2c_master_write_byte(cmd, reg, true);
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (HAPTIC_I2C_ADDR << 1) | I2C_MASTER_READ, true);
i2c_master_read_byte(cmd, out, I2C_MASTER_NACK);
i2c_master_stop(cmd);
esp_err_t err = i2c_master_cmd_begin(BUS, cmd, pdMS_TO_TICKS(40));
i2c_cmd_link_delete(cmd);
return err == ESP_OK;
}
// 播放 ROM 库里的一个效果
static void play(uint8_t effect) {
if (!_ready) return;
wr(REG_WAVESEQ1, effect);
wr(REG_WAVESEQ2, 0);
wr(REG_GO, 1);
}
// LRA / ERM 两套参数:本板是线性马达优先,ERM 由设置项兜底
static void configure(bool lra) {
_isLra = lra;
wr(REG_MODE, 0x00); // 内部触发模式
wr(REG_LIBRARY, lra ? 0x06 : 0x01); // 6=LRA 库,1=ERM 库
wr(REG_FEEDBACK, lra ? 0xB6 : 0x36); // 闭环反馈系数
wr(REG_RATEDV, lra ? 0x5A : 0x3F); // 额定电压
wr(REG_CLAMPV, lra ? 0x97 : 0x80); // 钳位电压
uint8_t c3 = 0;
rd(REG_CONTROL3, &c3);
wr(REG_CONTROL3, (uint8_t)(c3 | 0x20)); // 开环驱动,跳过自动谐振校准
LOG("HAP", "configured as %s", lra ? "LRA" : "ERM");
}
bool hapticBegin() {
pinMode(PIN_HAPTIC_EN, OUTPUT);
digitalWrite(PIN_HAPTIC_EN, HIGH);
delay(8);
uint8_t st = 0xFF;
if (!rd(REG_STATUS, &st)) {
LOG("HAP", "DRV2605 not found on 0x%02X", HAPTIC_I2C_ADDR);
_ready = false;
return false;
}
wr(REG_MODE, 0x80); // 软复位
delay(3);
wr(REG_MODE, 0x00);
_level = (uint8_t)settings.getI("sys.motor");
configure(_level != 0); // sys.motor: 0=ERM 1=LRA
_level = (uint8_t)settings.getI("sys.haptic");
_ready = true;
LOG("HAP", "ready, status=0x%02X level=%u", st, _level);
// 上电给一下确认感
play(1);
return true;
}
void hapticSetLevel(uint8_t level) {
if (level > 3) level = 3;
_level = level;
}
uint8_t hapticLevel() { return _level; }
bool hapticReady() { return _ready; }
void hapticTick() {
if (!_ready || _level == 0) return;
uint32_t now = millis();
if (now - _lastTick < 35) return; // 快转时别糊成一团
_lastTick = now;
_lastAny = now;
play(_level >= 3 ? 24 : 26); // Sharp Tick 100% / 30%
}
void hapticClick() {
if (!_ready || _level == 0) return;
_lastAny = millis();
play(_level >= 3 ? 10 : (_level == 2 ? 1 : 2)); // Double Click / Strong Click
}
void hapticBuzz() {
if (!_ready || _level == 0) return;
_lastAny = millis();
play(47); // Buzz
}
} // namespace hal

28
src/hal/Haptic.h 100644
View File

@ -0,0 +1,28 @@
#pragma once
// Haptic.h —— 触觉反馈(DRV2605L)
//
// 板载 DRV2605L 与触摸共用 I2C(GPIO11/12),从地址 0x5A,EN 由 GPIO38 控制。
// 它内置波形库(TS2200),我们只用 ROM 效果做"刻度感"和"确认感",不需要上传自定义波形。
#include <stdint.h>
namespace hal {
// 返回值:是否找到芯片
bool hapticBegin();
// 力度 0=关 1=轻 2=中 3=强(对应设置项 sys.haptic)
void hapticSetLevel(uint8_t level);
uint8_t hapticLevel();
// 旋钮每格:极轻的一下(内部自动节流,连续快转不会糊成一片)
void hapticTick();
// 点击/确认:比 tick 明显
void hapticClick();
// 长震(用于提示音替代,如番茄钟结束)
void hapticBuzz();
bool hapticReady();
} // namespace hal

42
src/hal/Power.cpp 100644
View File

@ -0,0 +1,42 @@
#include "Power.h"
#include "../config/BoardPins.h"
#include "../core/Log.h"
namespace hal {
static uint16_t _cachedMv = 0;
static uint32_t _lastRead = 0;
void powerBegin() {
analogReadResolution(12);
analogSetPinAttenuation(PIN_BATT_ADC, ADC_11db);
_cachedMv = batteryMilliVolts();
LOG("PWR", "battery %u mV (%u%%), ext=%d",
_cachedMv, batteryPercent(), (int)externalPower());
}
uint16_t batteryMilliVolts() {
// 200ms 缓存,避免频繁采样
if (millis() - _lastRead < 200 && _cachedMv) return _cachedMv;
_lastRead = millis();
uint32_t acc = 0;
for (int i = 0; i < 8; i++) acc += analogReadMilliVolts(PIN_BATT_ADC);
uint32_t mv = (acc / 8) * (uint32_t)BATT_DIVIDER;
_cachedMv = (uint16_t)mv;
return _cachedMv;
}
bool externalPower() {
return batteryMilliVolts() > 4300;
}
uint8_t batteryPercent() {
if (externalPower()) return 100; // 插 USB 时电压被顶高,不代表电量
uint16_t mv = batteryMilliVolts();
// 单节锂电近似曲线:4200→100%,3300→0%
if (mv >= 4200) return 100;
if (mv <= 3300) return 0;
return (uint8_t)((mv - 3300) * 100L / 900L);
}
} // namespace hal

16
src/hal/Power.h 100644
View File

@ -0,0 +1,16 @@
#pragma once
// Power.h —— 电池电压与供电状态
//
// 硬件限制(已实测):BATT_ADC 经 10K/10K 分压接在 5V/VCC 主轨上,
// 未插 USB 时读数×2 ≈ 电池电压;插 USB 时 ≈ 5000mV。
// 充电状态(CHRG)未接 MCU,无库仑计,因此"是否在充"只能推断。
#include <Arduino.h>
namespace hal {
void powerBegin();
uint16_t batteryMilliVolts(); // 已按分压还原
uint8_t batteryPercent(); // 电压线性插值估算
bool externalPower(); // 是否接着 USB
} // namespace hal

View File

@ -0,0 +1,60 @@
#include "Storage.h"
#include "../core/Log.h"
#include "../config/BoardPins.h"
#include <SD_MMC.h>
#include <mutex>
namespace hal {
static SemaphoreHandle_t _mtx = nullptr;
static bool _ready = false;
bool storageBegin() {
if (!_mtx) _mtx = xSemaphoreCreateRecursiveMutex();
SD_MMC.setPins(PIN_SD_CLK, PIN_SD_CMD, PIN_SD_D0, PIN_SD_D1, PIN_SD_D2, PIN_SD_D3);
// 1-bit 模式在部分卡上更稳;这里用 4-bit,失败再回落
if (!SD_MMC.begin("/sdcard", false, false, 20000)) {
LOG("HAL", "SD 4-bit mount failed, retry 1-bit");
SD_MMC.end();
if (!SD_MMC.begin("/sdcard", true, false, 20000)) {
LOG("HAL", "SD mount failed (no card?)");
_ready = false;
return false;
}
}
_ready = true;
LOG("HAL", "SD mounted: %llu MB total, %llu MB used",
SD_MMC.totalBytes() / (1024ULL * 1024ULL),
SD_MMC.usedBytes() / (1024ULL * 1024ULL));
return true;
}
bool storageReady() { return _ready; }
uint64_t storageTotalBytes() { return _ready ? SD_MMC.totalBytes() : 0; }
uint64_t storageUsedBytes() { return _ready ? SD_MMC.usedBytes() : 0; }
void storageLock() { if (_mtx) xSemaphoreTakeRecursive(_mtx, portMAX_DELAY); }
void storageUnlock() { if (_mtx) xSemaphoreGiveRecursive(_mtx); }
std::vector<String> listDir(const String& dirPath) {
std::vector<String> out;
if (!_ready) return out;
StorageLock guard;
File dir = SD_MMC.open(dirPath);
if (!dir || !dir.isDirectory()) return out;
File f = dir.openNextFile();
while (f) {
String name = f.name();
int slash = name.lastIndexOf('/');
if (slash >= 0) name = name.substring(slash + 1);
if (!name.startsWith(".")) out.push_back(name); // 过滤 macOS 的 ._ 垃圾文件
f.close();
f = dir.openNextFile();
}
dir.close();
return out;
}
} // namespace hal

28
src/hal/Storage.h 100644
View File

@ -0,0 +1,28 @@
#pragma once
// Storage.h —— TF 卡挂载与互斥
//
// TF 卡同一时刻只能被一个"持有者"访问:UI 线程读图、Web 线程传文件。
// 这里用递归互斥锁把并发访问串起来,锁粒度由调用方决定(整文件操作请持有到结束)。
#include <Arduino.h>
#include <vector>
namespace hal {
bool storageBegin(); // 挂载失败不阻塞启动,只记日志
bool storageReady();
uint64_t storageTotalBytes();
uint64_t storageUsedBytes();
void storageLock();
void storageUnlock();
// 目录列举(名字不含路径),失败返回空
std::vector<String> listDir(const String& dirPath);
// 带锁的 RAII 守卫
struct StorageLock {
StorageLock() { storageLock(); }
~StorageLock() { storageUnlock(); }
};
} // namespace hal

View File

@ -0,0 +1,291 @@
/*
* SPDX-FileCopyrightText: 2016-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*
*
*
* Modified by planevina 2025-01-20
*/
#include <stdio.h>
#include "driver/gpio.h"
#include "esp_attr.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "bidi_switch_knob.h"
static const char *TAG = "Knob";
#define TICKS_INTERVAL 3
#define DEBOUNCE_TICKS 2
#define KNOB_CHECK(a, str, ret_val) \
if (!(a)) \
{ \
ESP_LOGE(TAG, "%s(%d): %s", __FUNCTION__, __LINE__, str); \
return (ret_val); \
}
#define KNOB_CHECK_GOTO(a, str, label) \
if (!(a)) \
{ \
ESP_LOGE(TAG, "%s:%d (%s):%s", __FILE__, __LINE__, __FUNCTION__, str); \
goto label; \
}
#define CALL_EVENT_CB(ev) \
if (knob->cb[ev]) \
knob->cb[ev](knob, knob->usr_data[ev])
typedef struct Knob
{
bool encoder_a_change; /*<! true means Encoder A phase Inverted*/
bool encoder_b_change; /*<! true means Encoder B phase Inverted*/
uint8_t debounce_a_cnt; /*!< Encoder A phase debounce count */
uint8_t debounce_b_cnt; /*!< Encoder B phase debounce count */
uint8_t encoder_a_level; /*!< Encoder A phase current level */
uint8_t encoder_b_level; /*!< Encoder B phase current Level */
knob_event_t event; /*!< Current event */
int count_value; /*!< Knob count */
uint8_t (*hal_knob_level)(void *hardware_data); /*!< Get current level */
void *encoder_a; /*!< Encoder A phase gpio number */
void *encoder_b; /*!< Encoder B phase gpio number */
void *usr_data[KNOB_EVENT_MAX]; /*!< User data for event */
knob_cb_t cb[KNOB_EVENT_MAX]; /*!< Event callback */
struct Knob *next; /*!< Next pointer */
} knob_dev_t;
static knob_dev_t *s_head_handle = NULL;
static esp_timer_handle_t s_knob_timer_handle;
static bool s_is_timer_running = false;
// 判定函数
static void process_knob_channel(uint8_t current_level, uint8_t *prev_level,
uint8_t *debounce_cnt, int *count_value,
knob_event_t event, bool is_increment, knob_dev_t *knob)
{
if (current_level == 0)
{
if (current_level != *prev_level)
*debounce_cnt = 0;
else
(*debounce_cnt)++;
}
else
{
if (current_level != *prev_level && ++(*debounce_cnt) >= DEBOUNCE_TICKS)
{
*debounce_cnt = 0;
*count_value += is_increment ? 1 : -1;
knob->event = event;
CALL_EVENT_CB(event);
}
else
*debounce_cnt = 0;
}
*prev_level = current_level;
}
static void knob_handler(knob_dev_t *knob)
{
uint8_t pha_value = knob->hal_knob_level(knob->encoder_a);
uint8_t phb_value = knob->hal_knob_level(knob->encoder_b);
process_knob_channel(pha_value, &knob->encoder_a_level,
&knob->debounce_a_cnt, &knob->count_value,
KNOB_RIGHT, true, knob);
process_knob_channel(phb_value, &knob->encoder_b_level,
&knob->debounce_b_cnt, &knob->count_value,
KNOB_LEFT, false, knob);
}
// 这是timer的回调函数,定期执行
static void knob_cb(void *args)
{
knob_dev_t *target;
for (target = s_head_handle; target; target = target->next)
{
knob_handler(target);
}
}
knob_handle_t iot_knob_create(const knob_config_t *config)
{
KNOB_CHECK(NULL != config, "config pointer can't be NULL!", NULL)
KNOB_CHECK(config->gpio_encoder_a != config->gpio_encoder_b, "encoder A can't be the same as encoder B", NULL);
knob_dev_t *knob = (knob_dev_t *)calloc(1, sizeof(knob_dev_t));
KNOB_CHECK(NULL != knob, "alloc knob failed", NULL);
esp_err_t ret = ESP_OK;
ret = knob_gpio_init(config->gpio_encoder_a);
KNOB_CHECK(ESP_OK == ret, "encoder A gpio init failed", NULL);
ret = knob_gpio_init(config->gpio_encoder_b);
KNOB_CHECK_GOTO(ESP_OK == ret, "encoder B gpio init failed", _encoder_deinit);
knob->hal_knob_level = knob_gpio_get_key_level;
knob->encoder_a = (void *)(long)config->gpio_encoder_a;
knob->encoder_b = (void *)(long)config->gpio_encoder_b;
knob->encoder_a_level = knob->hal_knob_level(knob->encoder_a);
knob->encoder_b_level = knob->hal_knob_level(knob->encoder_b);
knob->event = KNOB_NONE;
knob->next = s_head_handle;
s_head_handle = knob;
if (!s_knob_timer_handle)
{
esp_timer_create_args_t knob_timer = {0};
knob_timer.arg = NULL;
knob_timer.callback = knob_cb;
knob_timer.dispatch_method = ESP_TIMER_TASK;
knob_timer.name = "knob_timer";
esp_timer_create(&knob_timer, &s_knob_timer_handle);
}
if (!s_is_timer_running)
{
esp_timer_start_periodic(s_knob_timer_handle, TICKS_INTERVAL * 1000U);
s_is_timer_running = true;
}
ESP_LOGI(TAG, "Iot Knob Config Succeed, encoder A:%d, encoder B:%d", config->gpio_encoder_a, config->gpio_encoder_b);
return (knob_handle_t)knob;
_encoder_deinit:
knob_gpio_deinit(config->gpio_encoder_b);
knob_gpio_deinit(config->gpio_encoder_a);
return NULL;
}
esp_err_t iot_knob_delete(knob_handle_t knob_handle)
{
esp_err_t ret = ESP_OK;
KNOB_CHECK(NULL != knob_handle, "Pointer of handle is invalid", ESP_ERR_INVALID_ARG);
knob_dev_t *knob = (knob_dev_t *)knob_handle;
ret = knob_gpio_deinit((int)(knob->usr_data));
KNOB_CHECK(ESP_OK == ret, "knob deinit failed", ESP_FAIL);
knob_dev_t **curr;
for (curr = &s_head_handle; *curr;)
{
knob_dev_t *entry = *curr;
if (entry == knob)
{
*curr = entry->next;
free(entry);
}
else
{
curr = &entry->next;
}
}
uint16_t number = 0;
knob_dev_t *target = s_head_handle;
while (target)
{
target = target->next;
number++;
}
ESP_LOGD(TAG, "remain knob number=%d", number);
if (0 == number && s_is_timer_running)
{
esp_timer_stop(s_knob_timer_handle);
esp_timer_delete(s_knob_timer_handle);
s_is_timer_running = false;
}
return ESP_OK;
}
esp_err_t iot_knob_register_cb(knob_handle_t knob_handle, knob_event_t event, knob_cb_t cb, void *usr_data)
{
KNOB_CHECK(NULL != knob_handle, "Pointer of handle is invalid", ESP_ERR_INVALID_ARG);
KNOB_CHECK(event < KNOB_EVENT_MAX, "event is invalid", ESP_ERR_INVALID_ARG);
knob_dev_t *knob = (knob_dev_t *)knob_handle;
knob->cb[event] = cb;
knob->usr_data[event] = usr_data;
return ESP_OK;
}
esp_err_t iot_knob_unregister_cb(knob_handle_t knob_handle, knob_event_t event)
{
KNOB_CHECK(NULL != knob_handle, "Pointer of handle is invalid", ESP_ERR_INVALID_ARG);
KNOB_CHECK(event < KNOB_EVENT_MAX, "event is invalid", ESP_ERR_INVALID_ARG);
knob_dev_t *knob = (knob_dev_t *)knob_handle;
knob->cb[event] = NULL;
knob->usr_data[event] = NULL;
return ESP_OK;
}
knob_event_t iot_knob_get_event(knob_handle_t knob_handle)
{
KNOB_CHECK(NULL != knob_handle, "Pointer of handle is invalid", ESP_ERR_INVALID_ARG);
knob_dev_t *knob = (knob_dev_t *)knob_handle;
return knob->event;
}
int iot_knob_get_count_value(knob_handle_t knob_handle)
{
KNOB_CHECK(NULL != knob_handle, "Pointer of handle is invalid", ESP_ERR_INVALID_ARG);
knob_dev_t *knob = (knob_dev_t *)knob_handle;
return knob->count_value;
}
esp_err_t iot_knob_clear_count_value(knob_handle_t knob_handle)
{
KNOB_CHECK(NULL != knob_handle, "Pointer of handle is invalid", ESP_ERR_INVALID_ARG);
knob_dev_t *knob = (knob_dev_t *)knob_handle;
knob->count_value = 0;
return ESP_OK;
}
esp_err_t iot_knob_resume(void)
{
KNOB_CHECK(s_knob_timer_handle, "knob timer handle is invalid", ESP_ERR_INVALID_STATE);
KNOB_CHECK(!s_is_timer_running, "knob timer is already running", ESP_ERR_INVALID_STATE);
esp_err_t err = esp_timer_start_periodic(s_knob_timer_handle, TICKS_INTERVAL * 1000U);
KNOB_CHECK(ESP_OK == err, "knob timer start failed", ESP_FAIL);
s_is_timer_running = true;
return ESP_OK;
}
esp_err_t iot_knob_stop(void)
{
KNOB_CHECK(s_knob_timer_handle, "knob timer handle is invalid", ESP_ERR_INVALID_STATE);
KNOB_CHECK(s_is_timer_running, "knob timer is not running", ESP_ERR_INVALID_STATE);
esp_err_t err = esp_timer_stop(s_knob_timer_handle);
KNOB_CHECK(ESP_OK == err, "knob timer stop failed", ESP_FAIL);
s_is_timer_running = false;
return ESP_OK;
}
esp_err_t knob_gpio_init(uint32_t gpio_num)
{
gpio_config_t gpio_cfg = {
.pin_bit_mask = (1ULL << gpio_num),
.mode = GPIO_MODE_INPUT,
.intr_type = GPIO_INTR_DISABLE,
.pull_up_en = 1,
};
esp_err_t ret = gpio_config(&gpio_cfg);
return ret;
}
esp_err_t knob_gpio_deinit(uint32_t gpio_num)
{
return gpio_reset_pin(gpio_num);
}
uint8_t knob_gpio_get_key_level(void *gpio_num)
{
return (uint8_t)gpio_get_level((uint32_t)gpio_num);
}

View File

@ -0,0 +1,175 @@
/*
* SPDX-FileCopyrightText: 2016-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*
*
* Modified by planevina 2025-01-20
*/
#pragma once
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C"
{
#endif
typedef void (*knob_cb_t)(void *, void *);
typedef void *knob_handle_t;
/**
* @brief Knob events
*
*/
typedef enum
{
KNOB_LEFT = 0, /*!< EVENT: Rotate to the left */
KNOB_RIGHT, /*!< EVENT: Rotate to the right */
KNOB_EVENT_MAX, /*!< EVENT: Number of events */
KNOB_NONE, /*!< EVENT: No event */
} knob_event_t;
/**
* @brief Knob config
*
*/
typedef struct
{
uint8_t gpio_encoder_a; /*!< Encoder Pin A */
uint8_t gpio_encoder_b; /*!< Encoder Pin B */
} knob_config_t;
/**
* @brief create a knob
*
* @param config pointer of knob configuration
*
* @return A handle to the created knob
*/
knob_handle_t iot_knob_create(const knob_config_t *config);
/**
* @brief Delete a knob
*
* @param knob_handle A knob handle to delete
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t iot_knob_delete(knob_handle_t knob_handle);
/**
* @brief Register the knob event callback function
*
* @param knob_handle A knob handle to register
* @param event Knob event
* @param cb Callback function
* @param usr_data user data
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t iot_knob_register_cb(knob_handle_t knob_handle, knob_event_t event, knob_cb_t cb, void *usr_data);
/**
* @brief Unregister the knob event callback function
*
* @param knob_handle A knob handle to register
* @param event Knob event
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t iot_knob_unregister_cb(knob_handle_t knob_handle, knob_event_t event);
/**
* @brief Get knob event
*
* @param knob_handle A knob handle to register
* @return knob_event_t Knob event
*/
knob_event_t iot_knob_get_event(knob_handle_t knob_handle);
/**
* @brief Get knob count value
*
* @param knob_handle A knob handle to register
*
* @return int count_value
*/
int iot_knob_get_count_value(knob_handle_t knob_handle);
/**
* @brief Clear knob cout value to zero
*
* @param knob_handle A knob handle to register
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t iot_knob_clear_count_value(knob_handle_t knob_handle);
/**
* @brief resume knob timer, if knob timer is stopped. Make sure iot_knob_create() is called before calling this API.
*
* @return
* - ESP_OK on success
* - ESP_ERR_INVALID_STATE timer state is invalid.
*/
esp_err_t iot_knob_resume(void);
/**
* @brief stop knob timer, if knob timer is running. Make sure iot_knob_create() is called before calling this API.
*
* @return
* - ESP_OK on success
* - ESP_ERR_INVALID_STATE timer state is invalid
*/
esp_err_t iot_knob_stop(void);
/**
* @brief Initialize a GPIO pin for knob input.
*
* This function configures a specified GPIO pin as an input for knob control.
* It sets the pin mode, disables interrupts, and enables the pull-up resistor.
*
* @param gpio_num The GPIO number to be configured.
* @return
* - ESP_OK: Configuration successful.
* - ESP_ERR_INVALID_ARG: Parameter error.
* - ESP_FAIL: Configuration failed.
*/
esp_err_t knob_gpio_init(uint32_t gpio_num);
/**
* @brief Deinitialize a GPIO pin for knob input.
*
* This function resets the specified GPIO pin.
*
* @param gpio_num The GPIO number to be deinitialized.
* @return
* - ESP_OK: Reset successful.
* - ESP_FAIL: Reset failed.
*/
esp_err_t knob_gpio_deinit(uint32_t gpio_num);
/**
* @brief Get the level of a GPIO pin.
*
* This function returns the current level (high or low) of the specified GPIO pin.
*
* @param gpio_num The GPIO number to read the level from.
* @return The level of the GPIO pin (0 or 1).
*/
uint8_t knob_gpio_get_key_level(void *gpio_num);
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,163 @@
#include "AstroService.h"
#include "PlatformService.h"
#include "OtaService.h"
#include "../core/Log.h"
#include <WiFi.h>
#include <ArduinoJson.h>
namespace svc {
AstroService astro;
// 运势是月级数据,6 小时刷新一次足够;进应用时也可手动强制刷新
static const uint32_t REFRESH_MS = 6UL * 3600UL * 1000UL;
struct FetchResult {
bool ok = false;
AstroData d;
String err;
};
// 同 WeatherService:静态区的 String 起来时可能不是干净空态(实测 buff=0x80000000),
// 用"全局结构体拷贝赋值"会踩非法 memmove,所以改成堆对象 + 指针交接。
static FetchResult* s_pending = nullptr;
static volatile bool s_ready = false;
static volatile bool s_busy = false;
void AstroService::begin() {
memset(&_d, 0, sizeof(_d));
_nextTryMs = millis() + 4000; // 等网络与绑定状态就绪
}
static void fetchTask(void* arg) {
((AstroService*)arg)->doFetch();
s_ready = true;
s_busy = false;
vTaskDelete(nullptr);
}
void AstroService::doFetch() {
FetchResult* r = new FetchResult();
if (!r) return;
if (!platform.bound()) {
r->err = "设备未绑定";
s_pending = r;
return;
}
if (WiFi.status() != WL_CONNECTED) {
r->err = "未联网";
s_pending = r;
return;
}
String body;
int status = 0;
if (!platform.get("/device/v1/astro?lang=zh", body, status)) {
r->err = "连不上服务端";
s_pending = r;
return;
}
if (status == 401) {
platform.noteRevoked();
r->err = "绑定已失效";
s_pending = r;
return;
}
if (status != 200) {
r->err = String("服务端 ") + status;
s_pending = r;
return;
}
JsonDocument doc;
if (deserializeJson(doc, body)) {
r->err = "解析失败";
s_pending = r;
return;
}
auto sign = [&](JsonObject o, AstroSign& s) {
s.valid = true;
s.name = String((const char*)(o["name"] | ""));
s.symbol = String((const char*)(o["symbol"] | ""));
s.element = String((const char*)(o["element"] | ""));
s.degree = o["degree"] | 0.0f;
};
sign(doc["sun"].as<JsonObject>(), r->d.sun);
sign(doc["moon"].as<JsonObject>(), r->d.moon);
r->d.period = String((const char*)(doc["period"] | ""));
JsonObject f = doc["fortune"].as<JsonObject>();
if (!f.isNull()) {
r->d.fortuneTitle = String((const char*)(f["title"] | ""));
r->d.fortuneBody = String((const char*)(f["content"] | ""));
}
r->d.updatedMs = millis();
r->ok = true;
LOG("ASTRO", "%s ☉%s ☽%s", r->d.period.c_str(), r->d.sun.name.c_str(), r->d.moon.name.c_str());
s_pending = r;
}
bool AstroService::requestUpdate(bool force) {
if (_d.updating || s_busy) return false;
if (ota.active()) return false; // 升级期间让路
if (!platform.bound()) {
_d.error = "设备未绑定";
return false;
}
if (WiFi.status() != WL_CONNECTED) {
_d.error = "未联网";
return false;
}
if (!force && _d.valid && millis() - _d.updatedMs < REFRESH_MS) return false;
_d.updating = true;
s_busy = true;
// JSON 文档 + HTTP:12KB 踩到过栈底(同天气),给 16KB
if (xTaskCreatePinnedToCore(fetchTask, "astro_http", 16384, this, 1, nullptr, 0) != pdPASS) {
s_busy = false;
_d.updating = false;
// 堆碎片化时 16KB 连续栈申请不到。失败了就别每 5ms 重试——
// 30 秒后再试(同 PlatformService::dispatch 的节流写法)
static uint32_t s_retryAt = 0;
if (millis() >= s_retryAt) {
LOG("ASTRO", "task create failed (heap low), retry in 30s");
s_retryAt = millis() + 30000;
}
_nextTryMs = millis() + 30000;
return false;
}
return true;
}
void AstroService::applyResult() {
s_ready = false;
FetchResult* p = s_pending;
s_pending = nullptr;
if (!p) return;
if (p->ok) {
AstroData nd = p->d;
nd.valid = true;
nd.updating = false;
nd.error = "";
_d = nd;
} else {
_d.updating = false;
_d.error = p->err;
}
delete p;
_nextTryMs = millis() + REFRESH_MS;
}
void AstroService::loop() {
if (s_ready) applyResult();
if (millis() < _nextTryMs) return;
if (!platform.bound() || WiFi.status() != WL_CONNECTED) {
_nextTryMs = millis() + 30000;
return;
}
requestUpdate();
}
} // namespace svc

View File

@ -0,0 +1,57 @@
#pragma once
// AstroService.h —— 星盘数据(太阳/月亮星座 + 本月运势)
//
// 数据源:nex_buddy 平台 /device/v1/astro?lang=zh。
// 服务端负责:按出生地时区算星盘、按居住时区定"当月"、
// 按优先级取运势文案(指定年月 → 通用月度 → 内置模板)。
// 设备只做展示;运势是月级数据,6 小时拉一次足够。
//
// 线程约定与 WeatherService 相同:网络在独立任务,结果经
// "待合并区"回主线程,任务绝不碰 LVGL / Settings。
#include <Arduino.h>
namespace svc {
struct AstroSign {
bool valid = false;
String name; // "双子座"(服务端按星座码表给的中文名)
String symbol; // "♊"
String element; // "风"
float degree = 0; // 星座内度数 0~30
};
struct AstroData {
bool valid = false;
bool updating = false;
AstroSign sun;
AstroSign moon;
String period; // "2026-11"
String fortuneTitle; // 本月运势标题
String fortuneBody; // 本月运势正文(几十字)
uint32_t updatedMs = 0;
String error;
};
class AstroService {
public:
void begin();
void loop();
bool requestUpdate(bool force = false);
bool busy() const { return _d.updating; }
const AstroData& data() const { return _d; }
// 供后台任务调用(AstroApp 之外不要调)
void doFetch();
private:
void applyResult();
AstroData _d;
uint32_t _nextTryMs = 0;
};
extern AstroService astro;
} // namespace svc

View File

@ -0,0 +1,160 @@
#include "AudioLink.h"
#include "LinkService.h"
#include "../config/BoardPins.h"
#include "../core/Log.h"
#include <SD_MMC.h>
namespace svc {
AudioLink audioLink;
static const uint8_t HDR0 = 0xAA;
static const uint8_t HDR1 = 0x55;
static const uint8_t CMD_START = 0x01;
static const uint8_t CMD_DATA = 0x02;
static const uint8_t CMD_END = 0x03;
static const uint8_t CMD_PAUSE = 0x04;
static const uint8_t CMD_VOL = 0x05;
static const uint8_t CMD_STOP = 0x06;
static const uint8_t CMD_STAT = 0x30;
static const size_t CHUNK = 512; // 一帧码流大小:512B ≈ 4.4ms @921600
static const uint16_t FLOW_LOW = 6; // 副控缓冲低于 6KB 就暂停塞
void AudioLink::begin() {
// 音频要跑 921600:128kbps 的 MP3 才 16KB/s,这样余量足够
Serial1.setRxBufferSize(2048);
Serial1.begin(UART_BAUD, SERIAL_8N1, PIN_UART_RX, PIN_UART_TX);
LOG("AUD", "uart1 @%d (audio link ready)", UART_BAUD);
}
uint8_t AudioLink::crc8(const uint8_t* d, size_t n) {
uint8_t c = 0x00;
for (size_t i = 0; i < n; i++) {
c ^= d[i];
for (int b = 0; b < 8; b++) c = (c & 0x80) ? (uint8_t)((c << 1) ^ 0x07) : (uint8_t)(c << 1);
}
return c;
}
void AudioLink::sendFrame(uint8_t cmd, const uint8_t* p, uint16_t n) {
uint8_t head[5] = {HDR0, HDR1, cmd, (uint8_t)(n & 0xFF), (uint8_t)(n >> 8)};
uint8_t c = crc8(head + 2, 3);
for (uint16_t i = 0; i < n; i++) {
c ^= p[i];
for (int b = 0; b < 8; b++) c = (c & 0x80) ? (uint8_t)((c << 1) ^ 0x07) : (uint8_t)(c << 1);
}
Serial1.write(head, sizeof(head));
if (n) Serial1.write(p, n);
Serial1.write(c);
}
bool AudioLink::play(const String& path) {
stop();
if (path.length() == 0) { _err = "no path"; return false; }
_f = SD_MMC.open(path, FILE_READ);
if (!_f) { _err = "open failed"; LOG("AUD", "open %s failed", path.c_str()); return false; }
// 跳过 ID3v2 头:解码器不该拿标签当码流
uint8_t id3[10];
if (_f.read(id3, 10) == 10 && id3[0] == 'I' && id3[1] == 'D' && id3[2] == '3') {
uint32_t sz = ((uint32_t)(id3[6] & 0x7F) << 21) | ((uint32_t)(id3[7] & 0x7F) << 14) |
((uint32_t)(id3[8] & 0x7F) << 7) | (uint32_t)(id3[9] & 0x7F);
_f.seek(10 + sz);
LOG("AUD", "skip id3 %u bytes", (unsigned)sz);
} else {
_f.seek(0);
}
_err = "ok";
_eos = false;
_paused = false;
_sent = 0;
_active = true;
sendFrame(CMD_START, nullptr, 0);
uint8_t vol = 80;
sendFrame(CMD_VOL, &vol, 1);
LOG("AUD", "play %s", path.c_str());
return true;
}
void AudioLink::setPaused(bool on) {
if (!_active) return;
_paused = on;
uint8_t v = on ? 1 : 0;
sendFrame(CMD_PAUSE, &v, 1);
}
void AudioLink::stop() {
if (_active) sendFrame(CMD_STOP, nullptr, 0);
if (_f) _f.close();
_active = false;
_paused = false;
_eos = false;
_freeKb = 0;
}
void AudioLink::drain() {
while (Serial1.available()) {
uint8_t b = (uint8_t)Serial1.read();
if (_rxn < sizeof(_rx)) _rx[_rxn++] = b;
// 边收边找帧头,够一帧就解
while (_rxn >= 5) {
if (_rx[0] != HDR0 || _rx[1] != HDR1) {
memmove(_rx, _rx + 1, --_rxn);
continue;
}
uint16_t len = (uint16_t)_rx[3] | ((uint16_t)_rx[4] << 8);
if (len > sizeof(_rx) - 6) { // 不可能的长度,丢一个字节重新同步
memmove(_rx, _rx + 1, --_rxn);
continue;
}
size_t total = 5 + len + 1;
if (_rxn < total) break; // 还没收全
uint8_t c = crc8(_rx + 2, 3 + len);
if (c == _rx[total - 1]) {
if (_rx[2] == CMD_STAT && len >= 3) {
_gotStatus = true;
_freeKb = (uint16_t)((_rx[5] << 8) | _rx[6]);
}
memmove(_rx, _rx + total, _rxn - total);
_rxn -= total;
} else {
memmove(_rx, _rx + 1, --_rxn);
}
}
if (_rxn == sizeof(_rx)) _rxn = 0;
}
}
void AudioLink::loop() {
drain();
if (!_active || _paused || _eos) return;
// 副控缓冲快满了就先别塞,等它回状态
if (_gotStatus && _freeKb < FLOW_LOW) return;
if (Serial1.availableForWrite() < (int)(CHUNK + 32)) return;
static uint8_t buf[CHUNK];
size_t n = _f.read(buf, CHUNK);
if (n == 0) {
sendFrame(CMD_END, nullptr, 0);
_eos = true;
LOG("AUD", "eos, sent %u KB", (unsigned)(_sent / 1024));
return;
}
sendFrame(CMD_DATA, buf, (uint16_t)n);
_sent += n;
if (millis() - _lastLog > 5000) {
_lastLog = millis();
LOG("AUD", "sent %u KB, slave free=%u KB", (unsigned)(_sent / 1024), _freeKb);
}
}
} // namespace svc

View File

@ -0,0 +1,56 @@
#pragma once
// AudioLink.h —— 把 TF 卡里的 MP3 码流推给副控去解码出声
//
// 为什么这么绕:主控 ESP32-S3 的 I2S 没有一根线连到 PCM5100,
// DAC 挂在副控 ESP32-U4WDH 的 GPIO25(BCK)/26(DIN)/27(LRCK) 上。
// 所以主控只负责"读文件 + 封包 + 控流",解码和出声都在副控。
//
// 帧格式(与 slave_audio/slave_audio.ino 严格一致):
// AA 55 | cmd | len_lo len_hi | payload... | crc8
// crc8 覆盖 cmd/len/payload,多项式 0x07、初值 0x00
//
// 流控:副控每 250ms 回 0x30 状态帧(state + 剩余缓冲 KB),
// 主控只在剩余空间 >= 6KB 时继续塞,避免 UART 把副控 RX 缓冲压爆。
#include <Arduino.h>
#include <FS.h>
namespace svc {
class AudioLink {
public:
void begin();
void loop();
// path 为空或打不开时返回 false,并在 lastError() 里留下原因
bool play(const String& path);
void setPaused(bool on);
void stop();
bool active() const { return _active; }
bool paused() const { return _paused; }
uint16_t freeKb() const { return _freeKb; }
bool slaveAlive() const { return _gotStatus; }
const char* lastError() const { return _err; }
private:
void sendFrame(uint8_t cmd, const uint8_t* p, uint16_t n);
void drain(); // 收副控状态帧
static uint8_t crc8(const uint8_t* d, size_t n);
File _f;
bool _active = false;
bool _paused = false;
bool _eos = false;
bool _gotStatus = false;
uint16_t _freeKb = 0;
uint32_t _sent = 0;
uint32_t _lastLog = 0;
const char* _err = "idle";
uint8_t _rx[64];
size_t _rxn = 0;
};
extern AudioLink audioLink;
} // namespace svc

View File

@ -0,0 +1,92 @@
#include "LinkService.h"
#include "../config/BoardPins.h"
#include "../config/AppConfig.h"
#include "../core/Log.h"
namespace svc {
LinkService link;
// 自定义帧:AA 55 | cmd | len | payload... | checksum
// 副控若使用别的格式,改这里即可,上层无感。
static const uint8_t HDR0 = 0xAA;
static const uint8_t HDR1 = 0x55;
void LinkService::begin() {
Serial1.begin(UART_BAUD, SERIAL_8N1, PIN_UART_RX, PIN_UART_TX);
LOG("LINK", "uart1 ready tx=%d rx=%d @%d", PIN_UART_TX, PIN_UART_RX, UART_BAUD);
}
void LinkService::sendRaw(const uint8_t* data, size_t len) {
Serial1.write(data, len);
Serial1.flush();
}
static void hexAppend(String& s, const uint8_t* d, size_t n) {
char b[4];
for (size_t i = 0; i < n; i++) {
snprintf(b, sizeof(b), "%02X ", d[i]);
s += b;
}
}
void LinkService::setVolume(uint8_t vol) {
uint8_t f[6] = {HDR0, HDR1, 0x10, 0x01, vol, (uint8_t)(0x10 + vol)};
sendRaw(f, sizeof(f));
LOG("LINK", "tx vol=%u", vol);
}
void LinkService::playPause() {
uint8_t f[5] = {HDR0, HDR1, 0x11, 0x00, 0x11};
sendRaw(f, sizeof(f));
LOG("LINK", "tx play/pause");
}
void LinkService::next() {
uint8_t f[5] = {HDR0, HDR1, 0x12, 0x00, 0x12};
sendRaw(f, sizeof(f));
}
void LinkService::prev() {
uint8_t f[5] = {HDR0, HDR1, 0x13, 0x00, 0x13};
sendRaw(f, sizeof(f));
}
void LinkService::feed(uint8_t b) {
_rxCount++;
_lastRxMs = millis();
if (_bufLen < sizeof(_buf)) _buf[_bufLen++] = b;
else {
memmove(_buf, _buf + 1, sizeof(_buf) - 1);
_buf[sizeof(_buf) - 1] = b;
}
// 留一份可读日志给调试页看(最多 512 字节的十六进制)
if (_rxLog.length() < 1024) {
hexAppend(_rxLog, &b, 1);
} else {
_rxLog = _rxLog.substring(64);
}
}
void LinkService::parse() {
// 第一版只做帧头探测,用来确认副控是否在主动上报
for (size_t i = 0; i + 1 < _bufLen; i++) {
if (_buf[i] == HDR0 && _buf[i + 1] == HDR1) {
_gotAnyPacket = true;
break;
}
}
}
void LinkService::loop() {
bool got = false;
while (Serial1.available()) {
feed((uint8_t)Serial1.read());
got = true;
if (_bufLen > 8) break;
}
if (got) parse();
}
} // namespace svc

View File

@ -0,0 +1,48 @@
#pragma once
// LinkService.h —— 与副控 ESP32 的串口链路
//
// 硬件事实:主控 ESP32-S3 没有经典蓝牙,A2DP 音频在副控(ESP32-U4WDH)上。
// 主控想控制播放,只能通过 UART(GPIO40/39) 给副控发指令。
//
// 原厂这套 UART 协议尚未逆向(副控固件无符号表),所以本版先做两件事:
// 1. 把主控发出去的指令按自定义格式封包,便于日后对齐;
// 2. 持续监听副控的原始回包并留存最近 512 字节,方便用 Web/串口抓协议。
// 等协议摸清后,只需要改本文件的 parse() 与命令表,上层 UI 不用动。
#include <Arduino.h>
namespace svc {
class LinkService {
public:
void begin();
void loop();
// 高层命令(内部转成帧)
void setVolume(uint8_t vol); // 0~100
void playPause();
void next();
void prev();
void sendRaw(const uint8_t* data, size_t len);
// 状态(协议未通时均为"未知")
bool connected() const { return _gotAnyPacket; }
uint32_t rxBytes() const { return _rxCount; }
const String& rxLog() const { return _rxLog; }
uint32_t lastRxMs() const { return _lastRxMs; }
private:
void feed(uint8_t b);
void parse();
uint8_t _buf[128];
size_t _bufLen = 0;
uint32_t _rxCount = 0;
uint32_t _lastRxMs = 0;
bool _gotAnyPacket = false;
String _rxLog;
};
extern LinkService link;
} // namespace svc

View File

@ -0,0 +1,517 @@
#include "MediaSync.h"
#include "PlatformService.h"
#include "NetService.h"
#include "MusicLibrary.h"
#include "../hal/Storage.h"
#include "../core/Log.h"
#include <SD_MMC.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
namespace svc {
MediaSync mediaSync;
static const char* LOCAL_MANIFEST = "/nexbuddy/media.json";
static const char* PART_FILE = "/nexbuddy/.part";
static const char* MUSIC_DIR = "/music";
static const char* PIC_DIR = "/pic";
// ------------------------------ crc32 ------------------------------
// 表驱动,256 项(1KB):5MB 文件比逐位快一个数量级,同步期间省出来的
// 时间都给了 UART/解码任务。
static uint32_t s_crcTable[256];
static bool s_crcReady = false;
static void crcInit() {
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int k = 0; k < 8; k++) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : (c >> 1);
s_crcTable[i] = c;
}
s_crcReady = true;
}
static uint32_t crc32Update(uint32_t c, const uint8_t* d, size_t n) {
if (!s_crcReady) crcInit();
c ^= 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) c = s_crcTable[(c ^ d[i]) & 0xFF] ^ (c >> 8);
return c ^ 0xFFFFFFFFu;
}
// ------------------------------ 工具 ------------------------------
static String dirFor(const String& kind) { return kind == "music" ? MUSIC_DIR : PIC_DIR; }
// 统一的「拿 Bearer 的 HTTP GET」:探测/清单都走这里
static bool httpGetJson(const String& path, String& out, int& status) {
String base = net.serverUrl();
if (base.isEmpty()) { status = -1; return false; }
WiFiClient plain;
WiFiClientSecure tls;
HTTPClient http;
http.setTimeout(10000);
http.setConnectTimeout(5000);
bool https = base.startsWith("https");
bool ok = https ? (tls.setInsecure(), http.begin(tls, base + path))
: http.begin(plain, base + path);
if (!ok) { status = -2; return false; }
http.addHeader("Authorization", "Bearer " + platform.token());
status = http.GET();
if (status == 200) out = http.getString();
http.end();
return status == 200;
}
// ------------------------------ begin / loop ------------------------------
void MediaSync::begin() {
// TF 上同步所需的目录一次建齐;卡没挂上时后面文件操作会报错
hal::StorageLock lock;
SD_MMC.mkdir("/nexbuddy");
SD_MMC.mkdir(MUSIC_DIR);
SD_MMC.mkdir(PIC_DIR);
LOG("MS", "media sync ready (device-confirmed; local manifest=%s)",
SD_MMC.exists(LOCAL_MANIFEST) ? "yes" : "no");
}
void MediaSync::force() {
_force = true;
}
void MediaSync::loop() {
if (_running) return;
if (!platform.bound() || !net.online() || !hal::storageReady()) return;
if (_force) { // 串口调试:不弹窗,直接同步
_force = false;
dispatchSync();
return;
}
// 同步任务创建失败后的定时重试(dispatchSync 里置 _syncRetryAt)
if (_syncRetryAt && millis() >= _syncRetryAt) {
_syncRetryAt = 0;
dispatchSync();
}
}
// 应用进入模块时调用:起后台任务查一次待同步状态
void MediaSync::checkNow() {
if (_running || _checkRequested) return;
if (!platform.bound() || !net.online() || !hal::storageReady()) {
_checkReady = false; // 离线时不弹窗:清掉旧结果,应用不会拿陈旧数据问用户
return;
}
_checkRequested = true;
_checkReady = false;
dispatchCheck();
}
// 用户点了「同步」。
// 注意:这里是"排队必达"——应用刚进页面时可能正在跑一次 checkNow(),
// 早先版本在这里直接 return,同步请求就被悄悄丢掉了,界面只能报
// "同步未开始,稍后自动重试"(而实际上什么都没做)。现在改成置 _force,
// loop() 会在当前任务结束后立刻派发,用户看到的就是遮罩一直在转。
void MediaSync::confirmSync() {
if (!platform.bound() || !net.online() || !hal::storageReady()) return;
if (_running) { _force = true; return; }
dispatchSync();
}
// 起任务的统一入口。
// 注:这版 arduino-esp32 没有 xTaskCreatePinnedToCoreWithCaps(栈不能放 PSRAM),
// 所以只能省内部堆:LV_BUF_ROWS 从 72 降到 40,腾出 23KB 给任务栈。
// 栈一旦申请失败旧代码直接放弃,用户看到的就是"点了同步没反应"——现在改成退避重试。
static bool startWorker(TaskFunction_t fn, const char* name, uint32_t stack, void* arg) {
return xTaskCreatePinnedToCore(fn, name, stack, arg, 1, nullptr, 0) == pdPASS;
}
void MediaSync::dispatchCheck() {
_running = true;
_st = SyncState::Working;
_err = "";
if (!startWorker([](void* arg) {
((MediaSync*)arg)->runCheck();
((MediaSync*)arg)->_running = false;
vTaskDelete(nullptr);
}, "ms_check", 12288, this)) {
_running = false;
_checkRequested = false;
_checkReady = true;
_st = SyncState::Failed;
_err = "task create failed";
}
}
void MediaSync::dispatchSync() {
_running = true;
_job = true;
_st = SyncState::Working;
_err = "";
_progress = "checking";
if (!startWorker([](void* arg) {
MediaSync* m = (MediaSync*)arg;
m->runJob();
m->_job = false;
m->_running = false;
vTaskDelete(nullptr);
}, "ms_sync", 16384, this)) {
_running = false;
_job = false;
_st = SyncState::Failed;
_err = "内存不足,稍后重试";
// 指数退避:3s、6s、12s,最多 5 次后停(避免堆长期紧张时无休止重试)
if (++_syncRetries <= 5) {
_syncRetryAt = millis() + (uint32_t)(3000 << (_syncRetries - 1));
LOG("MS", "sync task create failed, retry in %ums",
(unsigned)(3000 << (_syncRetries - 1)));
} else {
_syncRetries = 0;
LOG("MS", "sync task create failed, giving up");
}
return;
}
_syncRetries = 0;
}
// ------------------------------ 本地清单 ------------------------------
struct LocalItem {
String id;
String kind;
String name;
uint32_t size;
uint32_t crc;
};
static bool readLocalItems(std::vector<LocalItem>& items, String& rev) {
hal::StorageLock lock;
File f = SD_MMC.open(LOCAL_MANIFEST, FILE_READ);
if (!f) return false;
JsonDocument doc;
DeserializationError e = deserializeJson(doc, f);
f.close();
if (e) return false;
rev = doc["rev"].as<String>();
for (JsonObject it : doc["items"].as<JsonArray>()) {
items.push_back(LocalItem{it["id"].as<String>(), it["kind"].as<String>(),
it["name"].as<String>(), (uint32_t)(it["size"].as<uint32_t>())});
}
return true;
}
// ------------------------------ HTTP ------------------------------
bool MediaSync::fetchPending(int& pending, int& pic, int& music, String& rev, String& syncedRev, String& err) {
String body;
int status = 0;
if (!httpGetJson("/device/v1/media/pending", body, status)) {
err = "pending http " + String(status);
return false;
}
JsonDocument doc;
if (deserializeJson(doc, body) != DeserializationError::Ok) {
err = "bad pending json";
return false;
}
pending = doc["pending"].as<int>();
pic = doc["pending_pic"].as<int>(); // 旧服务端没有这两个字段时是 0,
music = doc["pending_music"].as<int>(); // 退化成总口径,不会更差
rev = doc["rev"].as<String>();
syncedRev = doc["synced_rev"].as<String>();
return true;
}
bool MediaSync::fetchManifest(String& out, int& status) {
return httpGetJson("/device/v1/media/manifest", out, status);
}
bool MediaSync::downloadOne(const String& url, const String& dest, uint32_t size, uint32_t crc, String& err) {
String base = net.serverUrl();
WiFiClient plain;
WiFiClientSecure tls;
HTTPClient http;
http.setTimeout(15000);
http.setConnectTimeout(5000);
bool https = base.startsWith("https");
bool ok = https ? (tls.setInsecure(), http.begin(tls, base + url))
: http.begin(plain, base + url);
if (!ok) { err = "begin failed"; return false; }
http.addHeader("Authorization", "Bearer " + platform.token());
int code = http.GET();
if (code != 200) { http.end(); err = "http " + String(code); return false; }
int len = http.getSize();
if (len > 0 && (uint32_t)len != size) {
http.end(); err = "size mismatch"; return false;
}
bool success = false;
// 注意:**不能**把整段下载包在一把 SD 锁里。
// 以前是 `StorageLock lock;` 罩住从 open 到 rename 的全过程,一个 10MB 的
// mp3 在慢网下要几十秒,这几十秒里主线程只要碰卡(相册解码、曲库扫描)
// 就会卡在 storageLock() 上——用户看到的就是"点同步界面卡死"。
// 现在只在真正访问卡的瞬间加锁(每次 4KB 写入),UI 最多等几毫秒。
File f;
{
hal::StorageLock lock;
if (SD_MMC.exists(PART_FILE)) SD_MMC.remove(PART_FILE);
f = SD_MMC.open(PART_FILE, FILE_WRITE);
}
if (!f) { http.end(); err = "open part failed"; return false; }
WiFiClient* s = http.getStreamPtr();
static uint8_t buf[4096];
uint32_t got = 0, c = 0;
uint32_t lastData = millis();
while (got < size) {
int avail = s->available();
if (avail <= 0) {
if (millis() - lastData > 15000) { err = "read timeout"; break; }
vTaskDelay(pdMS_TO_TICKS(20));
continue;
}
int n = s->readBytes(buf, min((size_t)avail, sizeof(buf)));
if (n <= 0) { err = "read failed"; break; }
bool wok;
{
hal::StorageLock lock;
wok = (f.write(buf, n) == (size_t)n);
}
if (!wok) { err = "card write failed"; break; }
c = crc32Update(c, buf, n);
got += n;
lastData = millis();
}
{
hal::StorageLock lock;
f.close();
if (got == size && c == crc) {
// 先删目标再 rename:FAT32 的 rename 对已存在文件行为不保证
if (SD_MMC.exists(dest)) SD_MMC.remove(dest);
success = SD_MMC.rename(PART_FILE, dest);
if (!success) err = "rename failed";
} else if (got == size) {
err = "crc mismatch";
}
if (!success) SD_MMC.remove(PART_FILE); // 没成功就清掉半截文件
}
http.end();
return success;
}
bool MediaSync::report(const String& json) {
String base = net.serverUrl();
if (base.isEmpty()) return false;
WiFiClient plain;
WiFiClientSecure tls;
HTTPClient http;
http.setTimeout(10000);
http.setConnectTimeout(5000);
bool https = base.startsWith("https");
bool ok = https ? (tls.setInsecure(), http.begin(tls, base + "/device/v1/media/report"))
: http.begin(plain, base + "/device/v1/media/report");
if (!ok) return false;
http.addHeader("Authorization", "Bearer " + platform.token());
http.addHeader("Content-Type", "application/json");
int code = http.POST(json);
http.end();
return code == 200;
}
// ------------------------------ 探测任务 ------------------------------
// 只回答两个问题:有几首新的没同步?清单有没有删除/改名类变更?
void MediaSync::runCheck() {
_progress = "checking";
int pending = 0, pic = 0, music = 0;
String rev, syncedRev, err;
if (!fetchPending(pending, pic, music, rev, syncedRev, err)) {
_st = SyncState::Failed;
_err = err;
_checkPending = 0;
_checkPic = 0;
_checkMusic = 0;
_checkRevChanged = false;
_checkRequested = false;
_checkReady = true;
_progress = "";
LOG("MS", "check failed: %s", err.c_str());
return;
}
_checkPending = pending;
_checkPic = pic;
_checkMusic = music;
// 清单变更(删除/改名) detection:服务端 rev vs 设备本地清单 rev。
// 服务端 synced_rev 是设备上次回报的指纹,本地读出来的应该一致;
// 直接跟本地比,卡上清单被手动改过也能发现。
String localRev;
std::vector<LocalItem> local;
readLocalItems(local, localRev);
_checkRevChanged = (!localRev.isEmpty() || !local.empty()) && (localRev != rev || syncedRev != rev);
_checkRequested = false;
_checkReady = true;
_st = SyncState::Idle;
_err = "";
_progress = "";
LOG("MS", "check: pending=%d pic=%d music=%d rev=%s local=%s changed=%d",
pending, pic, music, rev.c_str(), localRev.c_str(), (int)_checkRevChanged);
}
// ------------------------------ 同步任务 ------------------------------
void MediaSync::runJob() {
std::vector<LocalItem> local;
String localRev;
readLocalItems(local, localRev);
String body;
int status = 0;
if (!fetchManifest(body, status)) {
_st = SyncState::Failed;
_err = "manifest http " + String(status);
LOG("MS", "%s", _err.c_str());
return;
}
JsonDocument doc;
if (deserializeJson(doc, body) != DeserializationError::Ok) {
_st = SyncState::Failed;
_err = "bad manifest json";
return;
}
String remoteRev = doc["rev"].as<String>();
// 清单没变且本地清单在 → 什么都不用做,回报推进游标即可
if (remoteRev == localRev && SD_MMC.exists(LOCAL_MANIFEST)) {
String rep = "{\"synced\":[],\"deleted\":[],\"seq\":0,\"rev\":\"" + remoteRev + "\"}";
report(rep);
_st = SyncState::Idle;
_err = "";
_progress = "up to date";
LOG("MS", "up to date (rev %s)", remoteRev.c_str());
return;
}
// 清单 → 目标状态:/music 与 /pic 最终和它完全一致
std::vector<LocalItem> remote;
for (JsonObject it : doc["items"].as<JsonArray>()) {
remote.push_back(LocalItem{it["id"].as<String>(), it["kind"].as<String>(),
it["name"].as<String>(), (uint32_t)(it["size"].as<uint32_t>()),
(uint32_t)(it["crc32"].as<uint32_t>())});
}
JsonDocument rep;
JsonArray rSynced = rep["synced"].to<JsonArray>();
JsonArray rDeleted = rep["deleted"].to<JsonArray>();
bool musicChanged = false;
int failCount = 0;
int idx = 0, total = 0;
for (auto& r : remote) {
bool have = false;
for (auto& l : local) if (l.id == r.id && l.size == r.size) { have = true; break; }
if (have) continue;
total++;
}
for (auto& r : remote) {
bool have = false;
for (auto& l : local) if (l.id == r.id && l.size == r.size) { have = true; break; }
if (have) { rSynced.add(r.id); continue; }
idx++;
_progress = String(idx) + "/" + String(total) + " " + r.name;
LOG("MS", "download %s (%u KB)", r.name.c_str(), (unsigned)(r.size / 1024));
String dest = dirFor(r.kind) + "/" + r.name;
String err;
if (downloadOne("/device/v1/media/" + r.id + "/file", dest, r.size, r.crc, err)) {
rSynced.add(r.id);
if (r.kind == "music") musicChanged = true;
LOG("MS", "ok %s", r.name.c_str());
} else {
failCount++;
LOG("MS", "fail %s: %s", r.name.c_str(), err.c_str());
}
}
// 删除:两个托管目录扫一遍,凡是不在清单里的文件都删(包括手动拷进去的散文件)
{
hal::StorageLock lock;
for (const char* dir : {MUSIC_DIR, PIC_DIR}) {
File d = SD_MMC.open(dir);
if (!d || !d.isDirectory()) continue;
File f;
while ((f = d.openNextFile())) {
String fname = f.name();
f.close();
if (fname.startsWith(".")) continue; // 隐藏/临时文件不动
// ESP32 的 File::name() 可能带目录前缀,取最后一段
int slash = fname.lastIndexOf('/');
if (slash >= 0) fname = fname.substring(slash + 1);
bool keep = false;
for (auto& r : remote) {
if (dirFor(r.kind) == dir && r.name == fname) { keep = true; break; }
}
if (keep) continue;
if (SD_MMC.remove(String(dir) + "/" + fname)) {
LOG("MS", "removed stray %s/%s", dir, fname.c_str());
} else {
LOG("MS", "!! remove failed %s/%s", dir, fname.c_str());
}
}
d.close();
}
// 本地清单里有、服务端没有的:回报 id(网页端「已同步」徽标要收敛)
for (auto& l : local) {
bool keep = false;
for (auto& r : remote) if (r.id == l.id) { keep = true; break; }
if (!keep) {
rDeleted.add(l.id);
if (l.kind == "music") musicChanged = true;
}
}
}
// 写新本地清单
{
hal::StorageLock lock;
JsonDocument ld;
ld["rev"] = remoteRev;
JsonArray arr = ld["items"].to<JsonArray>();
for (auto& r : remote) {
JsonObject o = arr.add<JsonObject>();
o["id"] = r.id; o["kind"] = r.kind; o["name"] = r.name; o["size"] = r.size;
}
File f = SD_MMC.open(LOCAL_MANIFEST, FILE_WRITE);
if (f) { serializeJson(ld, f); f.close(); }
else LOG("MS", "!! save local manifest failed");
}
rep["seq"] = 0; // 设备自发同步:不动服务端 seq/ack 游标
rep["rev"] = remoteRev;
String repJson;
serializeJson(rep, repJson);
if (report(repJson)) LOG("MS", "reported (%d synced, %d deleted, %d failed)",
(int)rep["synced"].size(), (int)rep["deleted"].size(), failCount);
if (musicChanged) musicLib.scanAsync(); // 曲库变了就重扫,唱片机自己会刷新
if (failCount > 0) {
_st = SyncState::Failed;
_err = String(failCount) + " 个文件失败,可再同步一次";
} else {
_st = SyncState::Idle;
_err = "";
_progress = "synced";
// 同步成功后把探测结果清零:应用 onTick 拿旧结果会再弹一次确认框,
// 用户看着就像"同步没完"。下次进应用 checkNow 会重新探测。
_checkPending = 0;
_checkPic = 0;
_checkMusic = 0;
_checkRevChanged = false;
_checkReady = false;
}
}
} // namespace svc

View File

@ -0,0 +1,94 @@
#pragma once
// MediaSync.h —— TF 卡媒体同步(设备端用户确认触发,无定时同步)
//
// 数据流:网页上传/删除 → 服务端媒体库 → 用户进「音乐」或「相册」
// → 应用调 checkNow() 探测(GET /media/pending,几百字节)
// → 有待同步就弹 LVGL 确认框 → 用户点「同步」→ confirmSync()
// → 拉 manifest → 与 TF 卡对齐 → 回报。
//
// 同步语义:/music 与 /pic 两个目录由服务端清单**全权管理**——
// 同步完成后目录内容与清单完全一致:清单有就保留/补齐,清单没有就删除
// (包括手动拷进去的散文件)。想放自己的文件请走网页上传。
//
// 事务性:下载先写 /nexbuddy/.part,crc32 对上才 rename 到目标目录——
// 中途断电只会留下一个 .part,下次同步覆盖它,不会污染 /music /pic。
//
// 线程约定(与 PlatformService 相同):网络与写卡都在后台任务里跑,
// 主线程 loop()/onTick() 只读状态;任务里绝不碰 LVGL。
#include <Arduino.h>
namespace svc {
enum class SyncState : uint8_t {
Idle, // 空闲
Working, // 任务在跑(探测/同步)
Failed, // 上一轮失败(看 lastError,可再确认一次同步)
};
class MediaSync {
public:
void begin();
void loop();
SyncState state() const { return _st; }
// 进度提示("3/10 a.mp3"),UI 想显示就拿去
const String& progress() const { return _progress; }
const char* lastError() const { return _err.c_str(); }
// ---------- 应用进入时的检查 ----------
// 后台查一次待同步状态;结果回来后 checkReady() 为 true。
// 重复调用安全:正在跑或有新结果未消费时不再起任务。
void checkNow();
bool checkReady() const { return _checkReady; }
int pendingCount() const { return _checkPending; } // 总待同步数(兼容旧显示)
int pendingPic() const { return _checkPic; } // 其中图片:相册弹窗只报这个
int pendingMusic() const { return _checkMusic; } // 其中音乐:同上
bool revChanged() const { return _checkRevChanged; } // 清单有删除/改名类变更(不含新增)
bool needsSync() const { return _checkPending > 0 || _checkRevChanged; }
bool busy() const { return _running; } // 探测/同步任务在跑
// 只有"真的在写卡"的同步任务为 true(探测任务不算)。
// 界面靠它决定要不要盖进度层:进应用时的探测只花几百毫秒,
// 不该让用户看到"正在同步音乐"闪一下。
bool syncingJob() const { return _job; }
// 用户在确认框里点了「同步」
void confirmSync();
void force(); // 立即同步一次(串口调试用,不弹窗不确认)
private:
void dispatchCheck(); // 起后台探测任务(单飞)
void dispatchSync(); // 起后台同步任务(单飞)
void runCheck(); // 探测任务:pending 数 + 清单指纹对比
void runJob(); // 同步任务主体:拉清单 → 对齐目录 → 回报
bool fetchPending(int& pending, int& pic, int& music, String& rev, String& syncedRev, String& err);
bool fetchManifest(String& out, int& status);
bool downloadOne(const String& url, const String& dest, uint32_t size, uint32_t crc, String& err);
bool report(const String& json);
SyncState _st = SyncState::Idle;
String _progress;
String _err;
volatile bool _running = false;
volatile bool _force = false;
volatile bool _job = false; // 当前跑的是同步任务(不是探测)
// checkNow 的结果(主线程读,任务里写)
volatile bool _checkReady = false;
volatile bool _checkRequested = false;
int _checkPending = 0;
int _checkPic = 0;
int _checkMusic = 0;
bool _checkRevChanged = false;
// 同步任务创建失败时的重试:堆紧张(任务栈压力大)时 20KB 的栈
// 常常一口气申请不到,直接放弃就是用户看到的「点了同步没动静」。
// 失败后隔几秒再试,给前面的任务留出退出的时间。
uint32_t _syncRetryAt = 0;
uint8_t _syncRetries = 0;
};
extern MediaSync mediaSync;
} // namespace svc

View File

@ -0,0 +1,339 @@
#include "MusicLibrary.h"
#include "../hal/Storage.h"
#include "../core/Log.h"
#include <SD_MMC.h>
#include <string.h>
#include <ctype.h>
namespace svc {
MusicLibrary musicLib;
// ================================================================ ID3 解析
// 只读不搬运:文本帧整帧读入(都很少),APIC 只读帧头几十字节定位图片数据。
static inline uint32_t be32(const uint8_t* p) {
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
}
static inline uint32_t synchsafe(const uint8_t* p) {
return ((uint32_t)(p[0] & 0x7F) << 21) | ((uint32_t)(p[1] & 0x7F) << 14) |
((uint32_t)(p[2] & 0x7F) << 7) | (p[3] & 0x7F);
}
// 文本帧负载 → UTF-8。编码字节:0=ISO-8859-1 1=UTF-16 2=UTF-16BE 3=UTF-8
static String decodeText(const uint8_t* d, size_t n) {
if (n == 0) return "";
uint8_t enc = d[0];
d++; n--;
if (n == 0) return "";
String out;
if (enc == 3) { // UTF-8
while (n > 0 && d[n - 1] == 0) n--; // 单字节终结符
out.reserve(n);
for (size_t i = 0; i < n; i++) out += (char)d[i];
} else if (enc == 0) { // Latin-1 → UTF-8
while (n > 0 && d[n - 1] == 0) n--;
out.reserve(n);
for (size_t i = 0; i < n; i++) {
if (d[i] < 0x80) out += (char)d[i];
else { out += (char)(0xC0 | (d[i] >> 6)); out += (char)(0x80 | (d[i] & 0x3F)); }
}
} else { // UTF-16 / UTF-16BE
// 只能按"两个 0"成对去掉结尾:按单字节去掉会让长度变奇数,
// 最后一对字节被截断,表现就是每个标题都少了最后一个字符。
while (n >= 2 && d[n - 1] == 0 && d[n - 2] == 0) n -= 2;
bool be = (enc == 2);
size_t i = 0;
if (n >= 2 && d[0] == 0xFF && d[1] == 0xFE) { be = false; i = 2; }
else if (n >= 2 && d[0] == 0xFE && d[1] == 0xFF) { be = true; i = 2; }
for (; i + 1 < n; i += 2) {
uint32_t c = be ? ((uint32_t)d[i] << 8) | d[i + 1]
: ((uint32_t)d[i + 1] << 8) | d[i];
if (c >= 0xD800 && c <= 0xDBFF && i + 3 < n) { // 代理对
uint32_t lo = be ? ((uint32_t)d[i + 2] << 8) | d[i + 3]
: ((uint32_t)d[i + 3] << 8) | d[i + 2];
if (lo >= 0xDC00 && lo <= 0xDFFF) {
c = 0x10000 + ((c - 0xD800) << 10) + (lo - 0xDC00);
i += 2;
}
}
if (c < 0x80) out += (char)c;
else if (c < 0x800) {
out += (char)(0xC0 | (c >> 6)); out += (char)(0x80 | (c & 0x3F));
} else if (c < 0x10000) {
out += (char)(0xE0 | (c >> 12)); out += (char)(0x80 | ((c >> 6) & 0x3F));
out += (char)(0x80 | (c & 0x3F));
} else {
out += (char)(0xF0 | (c >> 18)); out += (char)(0x80 | ((c >> 12) & 0x3F));
out += (char)(0x80 | ((c >> 6) & 0x3F)); out += (char)(0x80 | (c & 0x3F));
}
}
}
return out;
}
struct Id3Info {
String title, artist;
uint32_t coverOff = 0, coverLen = 0;
bool coverJpeg = false, coverPng = false;
uint32_t tagEnd = 0; // 音频数据起点(估时长用)
};
// APIC 帧负载布局:enc(1) mime(z串) picType(1) desc(按 enc 终结) data…
// 返回 data 相对帧负载的偏移;mime 里识别 jpeg/png
static int apicDataOffset(const uint8_t* d, size_t n, const char*& mime) {
if (n < 4) return -1;
uint8_t enc = d[0];
size_t i = 1;
while (i < n && d[i] != 0) i++;
static char mimeBuf[24];
size_t mlen = i - 1;
if (mlen >= sizeof(mimeBuf)) mlen = sizeof(mimeBuf) - 1;
memcpy(mimeBuf, d + 1, mlen);
mimeBuf[mlen] = 0;
for (char* c = mimeBuf; *c; c++) *c = (char)tolower(*c);
mime = mimeBuf;
i++; // 过 mime 的 \0
i++; // pic type
if (enc == 1 || enc == 2) { // UTF-16 描述,双 0 终结
while (i + 1 < n && !(d[i] == 0 && d[i + 1] == 0)) i += 2;
i += 2;
} else {
while (i < n && d[i] != 0) i++;
i++;
}
return (int)i;
}
static bool parseId3(File& f, Id3Info& info) {
uint8_t hdr[10];
if (f.read(hdr, 10) != 10) return false;
if (memcmp(hdr, "ID3", 3) != 0) return false;
uint8_t ver = hdr[3];
bool isFooter = hdr[5] & 0x10;
uint32_t tagSize = synchsafe(hdr + 6);
info.tagEnd = 10 + tagSize + (isFooter ? 10 : 0);
if (info.tagEnd > f.size()) info.tagEnd = f.size();
uint32_t pos = 10;
// v2.3/2.4 的扩展头:v2.3 记 4 字节长度(不含自身),v2.4 是 synchsafe 全长
if (hdr[5] & 0x40 && ver >= 3) {
uint8_t eh[4];
if (f.seek(pos) && f.read(eh, 4) == 4) {
uint32_t ehSize = (ver == 4) ? synchsafe(eh) : be32(eh);
pos += 4 + ((ver == 4) ? 0 : ehSize);
}
}
const uint32_t idLen = (ver == 2) ? 3 : 4;
const uint32_t hdLen = idLen + ((ver == 2) ? 3 : 6);
while (pos + hdLen < info.tagEnd) {
uint8_t fh[10];
if (!f.seek(pos) || f.read(fh, hdLen) != hdLen) break;
if (fh[0] == 0) break; // padding
uint32_t fsize;
if (ver == 2) fsize = ((uint32_t)fh[3] << 16) | ((uint32_t)fh[4] << 8) | fh[5];
else if (ver == 4) fsize = synchsafe(fh + 4);
else fsize = be32(fh + 4);
char id[5] = {0};
memcpy(id, fh, idLen);
uint32_t dataPos = pos + hdLen;
if (fsize == 0 || dataPos + fsize > info.tagEnd) break;
String t = id;
bool isTitle = (t == "TIT2" || t == "TT2");
bool isArtist = (t == "TPE1" || t == "TP1");
if (isTitle || isArtist) {
uint8_t buf[256];
uint32_t rd = fsize < sizeof(buf) ? fsize : sizeof(buf);
if (f.seek(dataPos) && f.read(buf, rd) == rd) {
String s = decodeText(buf, rd);
if (s.length()) {
if (isTitle) info.title = s;
else info.artist = s;
}
}
} else if ((t == "APIC" || t == "PIC") && info.coverLen == 0) {
uint8_t buf[96];
uint32_t rd = fsize < sizeof(buf) ? fsize : sizeof(buf);
if (f.seek(dataPos) && f.read(buf, rd) >= 4) {
const char* mime = "";
int off = apicDataOffset(buf, rd, mime);
if (off > 0 && (uint32_t)off < fsize) {
bool jpeg = strstr(mime, "jpeg") || strstr(mime, "jpg");
bool png = strstr(mime, "png");
if (jpeg || png) {
info.coverOff = dataPos + off;
info.coverLen = fsize - off;
if (jpeg) info.coverJpeg = true;
else info.coverPng = true;
}
}
}
}
pos = dataPos + fsize;
}
// ID3v1 兜底:尾部 128 字节
if (info.title.length() == 0 && f.size() >= 128) {
uint8_t v1[128];
if (f.seek(f.size() - 128) && f.read(v1, 128) == 128 && memcmp(v1, "TAG", 3) == 0) {
char t[31] = {0}, a[31] = {0};
memcpy(t, v1 + 3, 30); memcpy(a, v1 + 33, 30);
info.title = String(t); info.artist = String(a);
info.title.trim(); info.artist.trim();
}
}
return true;
}
// 由首个 MP3 帧头的码率估算时长(秒)。Layer III 专表,够用。
static uint32_t estimateMp3Duration(File& f, uint32_t from) {
static const uint16_t BR_V1L3[16] = {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0};
static const uint16_t BR_V2L3[16] = {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0};
uint32_t size = f.size();
if (from + 4 > size) return 0;
const uint32_t WIN = 8192;
uint8_t buf[WIN];
if (!f.seek(from)) return 0;
uint32_t rd = f.read(buf, WIN);
if (rd < 4) return 0;
for (uint32_t i = 0; i + 4 <= rd; i++) {
if (buf[i] != 0xFF || (buf[i + 1] & 0xE0) != 0xE0) continue;
uint8_t verBits = (buf[i + 1] >> 3) & 0x03; // 3=v1 2=v2 0=v2.5
uint8_t layer = (buf[i + 1] >> 1) & 0x03; // 1=Layer III
uint8_t brIdx = (buf[i + 2] >> 4) & 0x0F;
if (layer != 1 || brIdx == 0 || brIdx == 15) continue;
uint16_t kbps = (verBits == 3) ? BR_V1L3[brIdx] : BR_V2L3[brIdx];
if (!kbps) continue;
return (uint32_t)((uint64_t)(size - from) * 8 / (kbps * 1000));
}
return 0;
}
// ================================================================ 扫描
static const char* AUDIO_EXT[] = {".mp3", ".wav", ".flac", ".m4a", ".aac", ".ogg"};
static bool isAudio(const String& low) {
for (auto e : AUDIO_EXT)
if (low.endsWith(e)) return true;
return false;
}
static void scanDir(File dir, int depth, std::vector<Track>& out) {
File f = dir.openNextFile();
while (f) {
String nm = f.name();
int slash = nm.lastIndexOf('/');
if (slash >= 0) nm = nm.substring(slash + 1);
bool hidden = nm.startsWith(".");
if (!hidden) {
if (f.isDirectory()) {
if (depth > 0) scanDir(f, depth - 1, out);
} else {
String low = nm;
low.toLowerCase();
if (isAudio(low)) {
Track t;
t.path = f.path();
int dot = nm.lastIndexOf('.');
t.title = (dot > 0) ? nm.substring(0, dot) : nm;
Id3Info info;
if (parseId3(f, info)) {
if (info.title.length()) t.title = info.title;
t.artist = info.artist;
t.coverOff = info.coverOff;
t.coverLen = info.coverLen;
t.coverJpeg = info.coverJpeg;
if (info.coverLen && !info.coverJpeg) t.coverJpeg = false;
if (low.endsWith(".mp3"))
t.durationSec = estimateMp3Duration(f, info.tagEnd);
}
out.push_back(t);
LOG("MUS", "found %s | %s - %s | cover=%u%s | %us",
t.path.c_str(), t.title.c_str(), t.artist.c_str(),
(unsigned)t.coverLen, t.coverJpeg ? "(jpg)" : "", (unsigned)t.durationSec);
}
}
}
f.close();
f = dir.openNextFile();
}
}
void MusicLibrary::scan() {
std::vector<Track> fresh;
if (hal::storageReady()) {
hal::StorageLock guard;
File root = SD_MMC.open("/");
if (root) {
// 约定目录优先(网页上传到 /music),根目录散文件也收
File m = SD_MMC.open("/music");
if (m && m.isDirectory()) scanDir(m, 2, fresh);
scanDir(root, 0, fresh); // depth 0:只收根目录散文件
root.close();
}
}
LOG("MUS", "scan done: %u tracks", (unsigned)fresh.size());
if (!_lock) _lock = xSemaphoreCreateMutex();
xSemaphoreTake(_lock, portMAX_DELAY);
_tracks.swap(fresh); // 整体换入,读侧永远拿到完整快照
xSemaphoreGive(_lock);
_ready = true;
_scanning = false;
vTaskDelete(nullptr);
}
void MusicLibrary::scanAsync() {
if (_scanning) return;
_scanning = true;
_ready = false;
// 栈 12KB:ID3 解析的局部缓冲都在堆/静态区,这里足够
if (xTaskCreatePinnedToCore([](void* arg) { ((MusicLibrary*)arg)->scan(); },
"mus_scan", 12288, this, 1, nullptr, 0) != pdPASS) {
_scanning = false;
_ready = true;
}
}
int MusicLibrary::count() const {
if (!_ready) return 0;
SemaphoreHandle_t lk = _lock;
if (lk) xSemaphoreTake(lk, portMAX_DELAY);
int n = (int)_tracks.size();
if (lk) xSemaphoreGive(lk);
return n;
}
Track MusicLibrary::at(int i) const {
Track t;
SemaphoreHandle_t lk = _lock;
if (lk) xSemaphoreTake(lk, portMAX_DELAY);
if (i >= 0 && i < (int)_tracks.size()) t = _tracks[i];
if (lk) xSemaphoreGive(lk);
return t;
}
size_t readCover(const Track& t, uint8_t* buf, size_t cap) {
if (!t.coverLen || !hal::storageReady()) return 0;
size_t len = t.coverLen < cap ? t.coverLen : cap;
hal::StorageLock guard;
File f = SD_MMC.open(t.path, FILE_READ);
if (!f) return 0;
bool ok = f.seek(t.coverOff);
size_t rd = ok ? f.read(buf, len) : 0;
f.close();
return rd;
}
} // namespace svc

View File

@ -0,0 +1,50 @@
#pragma once
// MusicLibrary.h —— TF 卡本地曲库
//
// 音乐方向已定(见 服务平台/01-总体设计.md M5):
// TF 卡本地文件 → 封面/标题读文件内嵌 ID3 → 播放机 UI;
// 发声链路(MP3 软解 → I2S/副控)属后续里程碑,本模块只负责"曲库与元数据"。
//
// ID3 覆盖:v2.2 / v2.3 / v2.4 的 TIT2/TPE1/APIC(含 v2.2 的 TT2/TP1/PIC),
// 外加 ID3v1 兜底。APIC 只记录偏移和长度,不搬运数据——封面按需从文件里读。
#include <Arduino.h>
#include <vector>
#include <freertos/semphr.h>
namespace svc {
struct Track {
String path; // 完整路径,如 /music/xxx.mp3
String title; // 内嵌标题;没有就用文件名
String artist;
uint32_t coverOff = 0; // APIC 图片数据在文件中的偏移
uint32_t coverLen = 0;
bool coverJpeg = false; // true=JPEG 可直接解码;PNG 暂不支持,走黑胶底纹
uint32_t durationSec = 0; // 由 MP3 帧头码率估算;估不出为 0
};
class MusicLibrary {
public:
// 后台任务扫卡(不阻塞 UI),完成或失败都会置 ready
void scanAsync();
bool ready() const { return _ready; }
bool scanning() const { return _scanning; }
int count() const;
Track at(int i) const; // 返回拷贝:调用方拿到的是快照,不怕后台重扫
private:
void scan();
std::vector<Track> _tracks;
SemaphoreHandle_t _lock = nullptr; // 换曲库 vs 读曲库在两个任务,要互斥
volatile bool _ready = false;
volatile bool _scanning = false;
};
// 从文件里读出封面位图数据(调用方持锁;读入 buf,返回字节数,0=失败)
size_t readCover(const Track& t, uint8_t* buf, size_t cap);
extern MusicLibrary musicLib;
} // namespace svc

View File

@ -0,0 +1,313 @@
#include "NetService.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../config/AppConfig.h"
#include <ESPmDNS.h>
#include <time.h>
#include <ArduinoJson.h>
namespace svc {
NetService net;
// STA 连接看门狗:一次尝试给 15 秒。15 秒还没连上,先 WiFi.disconnect() 把
// 底层那个"connecting"状态强行打断再重来;三次都不行就退回纯 AP。
// 为什么必须打断:esp_wifi 的 connect 在**找不到目标 AP 时不会超时**,
// 它会无限扫下去,状态永远停在 "sta is connecting"。此后任何 WiFi.begin()
// 都返回 ESP_ERR_WIFI_STATE(日志里那句 `sta is connecting, return error`),
// 更糟的是这个扫描会一直抢射频,把同芯片上的 softAP 信标挤掉——
// 现象就是"热点在扫描列表里一闪就没,手机怎么都连不上"。
static const uint32_t STA_TRY_MS = 15000;
static const uint8_t STA_TRIES_MAX = 3;
void NetService::begin() {
_bootMs = millis();
// 把断开原因打进日志:一是 201 找不到 AP(2.4G 关掉/太远),
// 二是 15/204/205 握手失败(密码变了 / 路由器要求 WPA3)。
// 过去只有一句 "connecting to ..." 然后永远沉默,根本没法判断是哪一种。
WiFi.onEvent([](arduino_event_id_t ev, arduino_event_info_t info) {
if (ev == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) {
LOG("NET", "sta disconnected, reason=%u", (unsigned)info.wifi_sta_disconnected.reason);
}
}, ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
String ssid = settings.getS("net.ssid");
String pass = settings.getS("net.pass");
if (ssid.length() == 0) {
LOG("NET", "no saved ssid -> AP mode");
startApPure();
return;
}
WiFi.mode(WIFI_STA);
WiFi.setHostname(MDNS_HOSTNAME);
WiFi.disconnect(false, false); // 清掉可能残留的 connecting 状态
WiFi.begin(ssid.c_str(), pass.c_str());
_mode = NetMode::Sta;
_staTries = 1;
_retryMs = millis();
LOG("NET", "connecting to %s ...", ssid.c_str());
}
void NetService::applySta() {
String ssid = settings.getS("net.ssid");
String pass = settings.getS("net.pass");
if (ssid.length() == 0) {
startApPure();
return;
}
// 从热点里提交的配网:切 AP+STA,热点先别关。
// 手机浏览器还挂在热点上,配网页要靠它轮询到新 IP 才能把「已连接」弹出来。
bool fromAp = (_mode == NetMode::Ap);
if (fromAp) {
WiFi.mode(WIFI_AP_STA);
_apGrace = true;
_apGraceUntil = millis() + AP_GRACE_MS;
} else {
WiFi.mode(WIFI_STA);
_apGrace = false;
}
WiFi.setHostname(MDNS_HOSTNAME);
// 先打断旧状态:上一次连接可能还卡在 connecting,不清掉 begin() 会直接失败
WiFi.disconnect(false, false);
WiFi.begin(ssid.c_str(), pass.c_str());
_mode = NetMode::Sta;
_staTries = 1;
_apFallback = false;
_retryMs = millis();
LOG("NET", "reconnect to %s ...%s", ssid.c_str(), fromAp ? " (AP kept for grace)" : "");
}
void NetService::startAp() {
// 有凭据就 AP_STA:设备其实已经联网,开热点只是为了配网/查看,
// 这时候不能把 STA 拆掉(拆了后台同步全断)。
bool hasCred = settings.getS("net.ssid").length() > 0;
applyApMode(hasCred || WiFi.status() == WL_CONNECTED);
}
void NetService::startApPure() {
// 纯 AP:一个网口都不留 STA。用于"连不上路由器"的兜底——
// AP_STA 里那个一直重连的 STA 会把信道反复扫,热点等于摆设。
applyApMode(false);
}
void NetService::applyApMode(bool withSta) {
if (_mode == NetMode::Ap && apUp() && !withSta) {
LOG("NET", "AP already on (%s)", WiFi.softAPIP().toString().c_str());
startDns();
return;
}
// 关键:不要用 WIFI_AP 硬切。
// 设备在 STA 已联网状态下点「配网」时,WiFi.mode(WIFI_AP) 会把 STA 的
// netif 整个拆掉重建;如果此刻后台任务(platform / weather / media)正握着
// 一条 TLS 连接,lwIP 那边就会踩到已经释放的 netif —— 现象是
// "一点配网设备就重启"。改成 AP_STA 叠加:热点起来,STA 保持不动,
// 两个网口并存,配网页照样能用 192.168.4.1 访问。
LOG("NET", "start AP (mode=%s, sta=%d)", withSta ? "AP_STA" : "AP", (int)WiFi.status());
WiFi.mode(withSta ? WIFI_AP_STA : WIFI_AP);
// 固定热点名,与平台文档/用户说明保持一致(不再追加 MAC 后缀)
const char *apName = DEFAULT_AP_SSID;
if (!WiFi.softAP(apName, DEFAULT_AP_PASS)) {
LOG("NET", "softAP() failed");
}
_mode = NetMode::Ap;
_apFallback = true;
_apGrace = false;
LOG("NET", "AP mode: %s / %s, ip=%s", apName, DEFAULT_AP_PASS,
WiFi.softAPIP().toString().c_str());
startDns();
}
// ---------------------------------------------------------------- 强制门户
// iOS / Android / Windows 连上一个新 WiFi 后都会去请求一个"我通不通"的探针地址
// (captive.apple.com/hotspot-detect.html、connectivitycheck.gstatic.com/generate_204 …)。
// 只要这两件事成立,系统就会自己弹出"登录到网络"的窗口,把我们的配网页显示出来:
// 1. 探针域名能解析 —— 热点没有上游 DNS,所以这里起一个通配 DNS,全指回本机;
// 2. 探针请求的响应不像"正常联网" —— 由 WebPortal 那边 302 到门户首页。
// 少任何一条,iOS 只会把网络标成"无互联网连接",不会弹窗。
void NetService::startDns() {
if (_dnsOn) return;
IPAddress ip = WiFi.softAPIP();
if ((uint32_t)ip == 0) return;
_dns.setErrorReplyCode(DNSReplyCode::NoError);
_dnsOn = _dns.start(53, "*", ip);
LOG("NET", "captive dns :53 -> %s (%s)", ip.toString().c_str(), _dnsOn ? "ok" : "fail");
}
void NetService::stopDns() {
if (!_dnsOn) return;
_dns.stop();
_dnsOn = false;
LOG("NET", "captive dns stopped");
}
void NetService::startMdns() {
if (MDNS.begin(MDNS_HOSTNAME)) {
MDNS.addService("http", "tcp", 80);
LOG("NET", "mdns: http://%s.local", MDNS_HOSTNAME);
}
}
void NetService::startSntp() {
// 时区固定东八区:设置里已经没有时区项(跟账号资料走,服务端校时后
// 由 applyClock 用 TZ 环境变量接管),SNTP 只在还没校时前兑个底。
configTime(8 * 3600, 0, "ntp.aliyun.com", "cn.pool.ntp.org", "pool.ntp.org");
LOG("NET", "sntp started, tz=UTC+8");
}
void NetService::applyTz() {
// POSIX 时区符号是反的:UTC+8 要写成 "UTC-8"
char buf[24];
snprintf(buf, sizeof(buf), "UTC-8:00");
setenv("TZ", buf, 1);
tzset();
LOG("NET", "tz applied: %s", buf);
}
void NetService::connect(const String& ssid, const String& pass) {
settings.setS("net.ssid", ssid);
settings.setS("net.pass", pass);
applySta();
}
void NetService::forget() {
settings.setS("net.ssid", "");
settings.setS("net.pass", "");
// 走请求队列:这个接口通常是浏览器点的,要先把响应发完再切网口
requestAp();
}
String NetService::serverUrl() const {
String u = settings.getS("net.server");
while (u.endsWith("/")) u.remove(u.length() - 1);
return u;
}
String NetService::ip() const {
if (_mode == NetMode::Ap) return WiFi.softAPIP().toString();
return WiFi.localIP().toString();
}
String NetService::ssid() const {
if (_mode == NetMode::Ap) return WiFi.softAPSSID();
return WiFi.SSID();
}
int NetService::rssi() const {
return (_mode == NetMode::Sta) ? WiFi.RSSI() : 0;
}
String NetService::scanJson() {
JsonDocument doc;
JsonArray arr = doc.to<JsonArray>();
int n = WiFi.scanNetworks();
for (int i = 0; i < n && i < 20; i++) {
JsonObject o = arr.add<JsonObject>();
o["ssid"] = WiFi.SSID(i);
o["rssi"] = WiFi.RSSI(i);
o["enc"] = WiFi.encryptionType(i) != WIFI_AUTH_OPEN;
}
WiFi.scanDelete();
String out;
serializeJson(doc, out);
return out;
}
void NetService::loop() {
static bool sntpDone = false;
static bool mdnsDone = false;
// 配网请求只在这里执行:绝不在 LVGL 的点击回调里同步切 WiFi 模式。
// 回调跑在 UI 任务上,切模式要停/起网口(几百毫秒到几秒),
// 既容易撞上后台 TLS 请求,也会让界面卡住一瞬。
if (_apReq) {
_apReq = false;
_stopApReq = false;
startAp();
return;
}
// 「完成」:宽限期不用等了,立刻收热点,只留 STA。
// 只在 STA 真的联网时才关——没连上的话关热点等于把人锁在门外。
if (_stopApReq) {
_stopApReq = false;
if (_apGrace && WiFi.status() == WL_CONNECTED) {
stopDns();
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
_apGrace = false;
LOG("NET", "ap closed by user");
}
}
// 热点开着就服务 DNS:配网宽限期里手机还挂在热点上,探针也得继续能解析
if (_dnsOn) _dns.processNextRequest();
if (_mode == NetMode::Sta) {
if (WiFi.status() == WL_CONNECTED) {
_staTries = 0;
if (!sntpDone) {
startSntp();
sntpDone = true;
}
if (!mdnsDone) {
startMdns();
mdnsDone = true;
}
// 配网后的宽限期到了就关热点,只留 STA
if (_apGrace && (int32_t)(millis() - _apGraceUntil) >= 0) {
stopDns();
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
_apGrace = false;
LOG("NET", "ap grace over, hotspot closed");
} else if (!_apGrace && apUp() && _apFallback) {
// 热点模式下的自动重试成功了:热点没事干了,收掉省电
stopDns();
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
_apFallback = false;
LOG("NET", "sta recovered, hotspot closed");
}
} else if (millis() - _retryMs > STA_TRY_MS) {
// 注意这里按"本次连接开始时刻"计时,不能按开机时刻:
// 配网提交发生在开机 20 秒之后时,按 _bootMs 判会立刻成立,
// 刚发起的连接会被 startAp() 当场掐掉,表现为"点了连接没反应"。
if (_staTries < STA_TRIES_MAX) {
_staTries++;
// 必须 disconnect:不然底层还停在 "sta is connecting",
// begin() 会直接返回错误,等于什么都没做(0.1.4 及以前就是这个死法)
LOG("NET", "sta try %u/%u timeout, reconnect",
(unsigned)_staTries, (unsigned)STA_TRIES_MAX);
WiFi.disconnect(false, false);
WiFi.begin(settings.getS("net.ssid").c_str(), settings.getS("net.pass").c_str());
_retryMs = millis();
} else {
LOG("NET", "sta failed after %u tries -> pure AP (radio freed)",
(unsigned)STA_TRIES_MAX);
startApPure();
}
}
} else if (_mode == NetMode::Ap) {
// 热点期间每 5 分钟再试一次 STA:路由器重启、2.4G 恢复后能自己回网。
// 关键是**只试一次**(AP_STA 里 15 秒),失败立刻退回纯 AP。
// 以前的写法挂在 AP 状态里再也不重连,或者一直 AP_STA 挂着,
// 结果是热点被重连扫描挤得连不上。
if (!_apGrace && settings.getS("net.ssid").length() &&
millis() - _retryMs > AP_RETRY_MS) {
_retryMs = millis();
LOG("NET", "ap idle: one STA attempt");
WiFi.mode(WIFI_AP_STA);
WiFi.disconnect(false, false);
WiFi.begin(settings.getS("net.ssid").c_str(), settings.getS("net.pass").c_str());
_mode = NetMode::Sta;
_staTries = 1;
}
}
}
} // namespace svc

View File

@ -0,0 +1,81 @@
#pragma once
// NetService.h —— 联网与配网
//
// 策略:
// 1. NVS 里有 SSID → 先按 STA 连,15 秒连不上就开热点兜底;
// 2. 没有 SSID → 直接开热点,手机连上后进配网页;
// 3. 连上后启动 mDNS(nexbuddy.local)与 SNTP 对时。
//
// 热点期间同时跑一个通配 DNS(所有域名都解析到 192.168.4.1),
// 配合 WebPortal 里的探针重定向,手机连上就会自己弹出配网页。
#include <Arduino.h>
#include <WiFi.h>
#include <DNSServer.h>
namespace svc {
enum class NetMode : uint8_t { Offline, Sta, Ap };
class NetService {
public:
void begin();
void loop();
NetMode mode() const { return _mode; }
// 只看"有没有上网链路":配网时热点与 STA 并存(AP_STA),此时网还是通的,
// 平台/天气/媒体同步不该因为"正在配网"就全部停摆。
bool online() const { return WiFi.status() == WL_CONNECTED; }
// 热点是否真的开着(配网宽限期内 mode 已经是 Sta,但 AP 还在)
bool apUp() const { return (uint32_t)WiFi.softAPIP() != 0; }
String ip() const;
String ssid() const;
int rssi() const;
// 保存并连接;连不上会自动开热点
void connect(const String& ssid, const String& pass);
void startAp();
// 请求开热点:只置标志,真正的模式切换放在 loop() 里做。
// UI 回调里不要直接调 startAp()——切网口要停/起 WiFi,几秒钟的事,
// 放在 LVGL 事件里既会卡界面,也容易撞上后台正在跑的 TLS 请求。
void requestAp() { _apReq = true; }
// 请求立刻关热点(配网页点了「完成」):宽限期还剩几十秒也照样关,
// 手机已经连上新 WiFi,热点留着只是耗电。
void requestStopAp() { _stopApReq = true; }
void forget();
// 服务端地址(NVS 的 net.server,读出来顺手去掉末尾斜杠)
String serverUrl() const;
// 把东八区应用到 TZ 环境变量(服务端校时成功后会被 applyClock 覆盖成账号时区)
void applyTz();
// 站点扫描(配网页用)
String scanJson();
private:
void applySta();
void applyApMode(bool withSta); // 热点底层实现:要不要同时留 STA
void startApPure(); // 只开热点、不碰 STA:射频全给 AP,保证手机连得上
void startMdns();
void startSntp();
void startDns();
void stopDns();
NetMode _mode = NetMode::Offline;
uint32_t _bootMs = 0;
uint32_t _retryMs = 0; // 本次 STA 连接开始时刻
bool _apFallback = false;
uint8_t _staTries = 0; // 这一轮已经试了几次(见 STA_TRIES_MAX)
// 配网成功后热点再保留一会儿(见 AppConfig.h 的 AP_GRACE_MS)
bool _apGrace = false;
uint32_t _apGraceUntil = 0;
DNSServer _dns;
bool _dnsOn = false;
bool _apReq = false; // UI 请求开热点,等 loop() 执行
bool _stopApReq = false; // UI 请求关热点,同样等 loop() 执行
};
extern NetService net;
} // namespace svc

View File

@ -0,0 +1,468 @@
#include "OtaService.h"
#include "NetService.h"
#include "PlatformService.h"
#include "../core/Log.h"
#include "../config/AppConfig.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <Update.h>
#include <ArduinoJson.h>
#include <Preferences.h>
#include <esp_ota_ops.h>
#include <esp_partition.h>
#include <mbedtls/sha256.h>
namespace svc {
OtaService ota;
// ============================ 后台 → 主线程的交接 ============================
// 和 WeatherService 同一套做法:任务把结果建成堆对象塞进 s_pending,主线程取走再 delete。
// 绝不让任务直接写成员里的 String——两个线程同时析构同一个 String 会踩到
// 之前那类 LoadProhibited(见 ARCHITECTURE 里 bootloop 那段)。
struct OtaJob {
OtaState st = OtaState::Idle;
String err;
OtaRelease rel;
};
static OtaJob* s_pending = nullptr;
static volatile int s_pct = 0;
// 上报升级结果(后台跑,绝不阻塞 UI / 不能拖慢重启)
// 服务端契约:POST /device/v1/firmware/report {version,status,error,slot}
static void reportAsync(const String& ver, bool ok, const String& err) {
struct Rep { String v; bool ok; String e; };
Rep* r = new Rep();
if (!r) return;
r->v = ver; r->ok = ok; r->e = err;
xTaskCreate([](void* arg) {
Rep* p = (Rep*)arg;
JsonDocument doc;
doc["version"] = p->v;
doc["status"] = p->ok ? "success" : "failed";
doc["error"] = p->e;
doc["slot"] = OtaService::runningSlot();
String payload, out;
int status = 0;
serializeJson(doc, payload);
platform.post("/device/v1/firmware/report", payload, out, status);
LOG("OTA", "report %s %s -> HTTP %d", p->ok ? "success" : "failed",
p->v.c_str(), status);
delete p;
vTaskDelete(nullptr);
}, "ota_rep", 8192, r, 1, nullptr);
}
// ============================ 槽位工具 ============================
static const esp_partition_t* slotPart(int idx) {
return esp_partition_find_first(ESP_PARTITION_TYPE_APP,
(esp_partition_subtype_t)(ESP_PARTITION_SUBTYPE_APP_OTA_0 + idx),
nullptr);
}
static int runningIndex() {
const esp_partition_t* p = esp_ota_get_running_partition();
if (!p) return 0;
int idx = (int)p->subtype - (int)ESP_PARTITION_SUBTYPE_APP_OTA_0;
return (idx == 0 || idx == 1) ? idx : 0;
}
const char* OtaService::runningSlot() { return runningIndex() == 0 ? "app0" : "app1"; }
const char* OtaService::otherSlot() { return runningIndex() == 0 ? "app1" : "app0"; }
bool OtaService::otherSlotHasImage() {
const esp_partition_t* p = slotPart(1 - runningIndex());
if (!p) return false;
uint8_t magic = 0;
// ESP 镜像第一个字节固定是 0xE9。空分区是全 0xFF,擦干净的槽读出来不是 0xE9。
if (esp_partition_read(p, 0, &magic, 1) != ESP_OK) return false;
return magic == 0xE9;
}
uint32_t OtaService::slotSizeKB(int idx) {
const esp_partition_t* p = slotPart(idx);
return p ? (uint32_t)(p->size / 1024) : 0;
}
// ============================ 开机守卫 ============================
void OtaService::begin() {
Preferences prefs;
prefs.begin("ota", false);
String pending = prefs.getString("pending", "");
uint32_t tries = 0;
// 只有"刚升级完还没验收"的那几次启动才计数。
// 无条件累加会把日常的断电/复位也攒进去:开发时连按几次复位,设备就
// 自己"回滚"到另一个槽,看着像固件丢了——那是比它要防的问题更糟的体验。
if (pending.length()) {
tries = prefs.getUInt("try", 0) + 1;
prefs.putUInt("try", tries);
} else if (prefs.getUInt("try", 0) != 0) {
prefs.putUInt("try", 0);
}
prefs.end();
LOG("OTA", "slot=%s v%s try=%u other=%s(%s)%s", runningSlot(), BRAND_VERSION, tries,
otherSlot(), otherSlotHasImage() ? "image" : "empty",
pending.length() ? " pending-check" : "");
// 连续 3 次没跑到"稳定运行"就被重启了 → 认定新固件有问题,切回另一个槽。
// 前提是那个槽真的有可启动镜像,否则切过去就是砖,宁可在坏固件里等人来救。
if (tries > 3) {
if (otherSlotHasImage()) {
LOG("OTA", "boot fail x%u -> rollback to %s", tries, otherSlot());
Preferences p2;
p2.begin("ota", false);
p2.putUInt("try", 0);
p2.end();
const esp_partition_t* other = slotPart(1 - runningIndex());
if (other && esp_ota_set_boot_partition(other) == ESP_OK) {
delay(200);
ESP.restart();
}
LOG("OTA", "rollback failed");
} else {
LOG("OTA", "boot fail x%u, but %s has no image", tries, otherSlot());
}
}
}
// ============================ 主线程 ============================
void OtaService::loop() {
// 1) 合并后台结果
OtaJob* j = s_pending;
if (j) {
s_pending = nullptr;
_st = j->st;
_err = j->err;
if (j->rel.version.length()) _rel = j->rel;
delete j;
if (_st == OtaState::Ready) {
_readyAt = millis();
Preferences prefs;
prefs.begin("ota", false);
prefs.putString("pending", _rel.version); // 重启后由 begin() 打印,便于串口确认
prefs.end();
LOG("OTA", "image written, rebooting into %s", _rel.version.c_str());
} else if (_st == OtaState::Failed) {
LOG("OTA", "failed: %s", _err.c_str());
} else if (_st == OtaState::Available) {
LOG("OTA", "available: %s (%u bytes)", _rel.version.c_str(), _rel.size);
} else if (_st == OtaState::UpToDate) {
LOG("OTA", "up to date (%s)", BRAND_VERSION);
}
}
_pct = s_pct;
// 2) 校验通过 → 停 1.5 秒让人看见"即将重启",然后重启进新固件
if (_st == OtaState::Ready && millis() - _readyAt > 1500) ESP.restart();
// 3) 稳定运行 60 秒且联网 → 这次启动算成功,清掉尝试计数
static bool cleared = false;
if (!cleared && millis() > 60000 && net.online()) {
cleared = true;
Preferences prefs;
prefs.begin("ota", false);
const String pendingVer = prefs.getString("pending", "");
if (prefs.getUInt("try", 0) != 0) prefs.putUInt("try", 0);
prefs.putString("good", BRAND_VERSION);
prefs.putString("goodslot", runningSlot());
if (pendingVer.length()) prefs.remove("pending");
prefs.end();
LOG("OTA", "boot ok, good=%s slot=%s", BRAND_VERSION, runningSlot());
// 这一版是从升级来的,而且活过了 60 秒 → 告诉服务端这次推送成功
if (pendingVer.length()) reportAsync(BRAND_VERSION, true, "");
}
}
// ============================ 检查更新 ============================
String OtaService::absoluteUrl(const String& u) const {
if (u.startsWith("http://") || u.startsWith("https://")) return u;
String base = net.serverUrl();
if (u.startsWith("/")) return base + u;
return base + "/" + u;
}
void OtaService::dispatchCheck() {
_st = OtaState::Checking;
_err = "";
xTaskCreate([](void*) { ota.doCheck(); vTaskDelete(nullptr); },
"ota_check", 8192, nullptr, 1, nullptr);
}
bool OtaService::check() {
if (active()) return false;
if (!platform.bound()) { _st = OtaState::Failed; _err = "设备未绑定"; return false; }
if (WiFi.status() != WL_CONNECTED) { _st = OtaState::Failed; _err = "设备未联网"; return false; }
dispatchCheck();
return true;
}
void OtaService::doCheck() {
OtaJob* j = new OtaJob();
if (!j) return;
// 契约(服务端 app/api/device_v1.py::check_firmware):
// GET /device/v1/firmware/check?current=<ver>&lang=zh
// → {"update":false} 或 {"update":true, "version","size","sha256","notes","url","mandatory","reason"}
// url 是相对路径,设备自己拼 serverUrl——换域名/端口不用改服务端数据。
String path = String("/device/v1/firmware/check?current=") + BRAND_VERSION + "&lang=zh";
String body;
int status = 0;
platform.get(path, body, status);
if (status == 204 || status == 404) {
j->st = OtaState::UpToDate;
s_pending = j;
return;
}
if (status != 200) {
j->st = OtaState::Failed;
j->err = String("HTTP ") + status;
s_pending = j;
return;
}
JsonDocument doc;
DeserializationError err = deserializeJson(doc, body);
if (err) {
j->st = OtaState::Failed;
j->err = "响应解析失败";
s_pending = j;
return;
}
// update 是布尔位;顺便兼容把它写成对象的旧形状({"update":{...}})
bool hasUpdate = false;
JsonVariant uv = doc["update"];
if (uv.is<bool>()) hasUpdate = uv.as<bool>();
else if (uv.is<JsonObject>()) hasUpdate = true;
if (!hasUpdate) {
j->st = OtaState::UpToDate;
s_pending = j;
return;
}
JsonObject o = uv.is<JsonObject>() ? uv.as<JsonObject>() : doc.as<JsonObject>();
j->rel.version = String((const char*)(o["version"] | ""));
j->rel.url = String((const char*)(o["url"] | ""));
j->rel.sha256 = String((const char*)(o["sha256"] | ""));
j->rel.notes = String((const char*)(o["notes"] | ""));
j->rel.size = (uint32_t)(o["size"] | 0);
j->rel.mandatory = o["mandatory"] | false;
if (!j->rel.valid() || j->rel.version == BRAND_VERSION) {
j->st = OtaState::UpToDate;
} else {
j->st = OtaState::Available;
}
s_pending = j;
}
// ============================ 下载并写入非运行槽 ============================
bool OtaService::start() {
if (_st != OtaState::Available || active()) return false;
dispatchDownload();
return true;
}
void OtaService::startFromUrl(const String& url, const String& version) {
if (active()) return;
_rel = OtaRelease();
_rel.url = url;
_rel.version = version.length() ? version : "manual";
_rel.size = 0;
s_pct = 0;
dispatchDownload();
}
void OtaService::dispatchDownload() {
_st = OtaState::Downloading;
_err = "";
_pct = 0;
s_pct = 0;
_startedAt = millis();
xTaskCreate([](void*) { ota.doDownload(); vTaskDelete(nullptr); },
"ota_dl", 12288, nullptr, 1, nullptr);
}
void OtaService::fail(const String& msg) {
// 下载阶段的失败要回报服务端(管理端「升级失败」那一列才有内容);
// 检查更新阶段失败(没网、没绑定)不上报,否则只是噪音。
const bool duringDownload = (_st == OtaState::Downloading || _st == OtaState::Verifying);
const String ver = _rel.version;
OtaJob* j = new OtaJob();
if (!j) return;
j->st = OtaState::Failed;
j->err = msg;
s_pending = j;
if (duringDownload) reportAsync(ver, false, msg);
}
void OtaService::doDownload() {
const String url = absoluteUrl(_rel.url);
WiFiClient plain;
WiFiClientSecure tls;
HTTPClient http;
const bool https = url.startsWith("https");
if (https) tls.setInsecure(); // 与 PlatformService 保持一致:暂不校验证书链
bool ok = https ? http.begin(tls, url) : http.begin(plain, url);
if (!ok) { fail("连接失败"); return; }
http.setTimeout(15000);
http.setConnectTimeout(8000);
http.addHeader("Accept", "application/octet-stream");
if (platform.token().length()) http.addHeader("Authorization", "Bearer " + platform.token());
int code = http.GET();
if (code != 200) {
http.end();
fail(String("下载失败 HTTP ") + code);
return;
}
int total = http.getSize(); // chunked 传输时是 -1
size_t want = (total > 0) ? (size_t)total : (size_t)_rel.size;
if (want == 0) {
http.end();
fail("服务端没给大小");
return;
}
if (want > (size_t)slotSizeKB(0) * 1024) {
http.end();
fail("固件超过槽位容量");
return;
}
// 写入前把"要写哪个槽"落到日志里,并且**拒绝写当前正在运行的槽**。
// 这不是防御性编程洁癖:Update.begin() 会先把目标分区擦掉,一旦擦的是
// 正在运行的那个槽,升级中途断电/复位就是真砖(实测踩到过 app0 被擦成 0xFF)。
const esp_partition_t* tgt = esp_ota_get_next_update_partition(nullptr);
const esp_partition_t* run = esp_ota_get_running_partition();
if (!tgt) {
http.end();
fail("找不到可写槽位");
return;
}
if (run && tgt->address == run->address) {
http.end();
LOG("OTA", "abort: target == running (%s)", runningSlot());
fail("目标槽与运行槽相同,拒绝写入");
return;
}
LOG("OTA", "writing %s @0x%06X size=%u (from %s)",
tgt->subtype == ESP_PARTITION_SUBTYPE_APP_OTA_0 ? "app0" : "app1",
(unsigned)tgt->address, (unsigned)want, runningSlot());
if (!Update.begin(want)) {
http.end();
fail(String("无法写入槽位: ") + Update.errorString());
return;
}
mbedtls_sha256_context ctx;
mbedtls_sha256_init(&ctx);
mbedtls_sha256_starts(&ctx, 0);
WiFiClient* stream = http.getStreamPtr();
uint8_t buf[4096];
size_t got = 0;
uint32_t lastDataMs = millis();
bool aborted = false;
const char* why = nullptr;
while (http.connected() && got < want) {
size_t avail = stream->available();
if (avail == 0) {
// 20 秒没有任何字节 → 网络断了,别把槽写成半成品
if (millis() - lastDataMs > 20000) { aborted = true; why = "下载超时"; break; }
vTaskDelay(pdMS_TO_TICKS(20));
continue;
}
int n = stream->readBytes(buf, avail > sizeof(buf) ? sizeof(buf) : avail);
if (n <= 0) continue;
if (Update.write(buf, (size_t)n) != (size_t)n) {
aborted = true; why = "写入 flash 失败"; break;
}
mbedtls_sha256_update(&ctx, buf, (size_t)n);
got += (size_t)n;
lastDataMs = millis();
s_pct = (int)((uint64_t)got * 100 / want);
}
unsigned char digest[32];
mbedtls_sha256_finish(&ctx, digest);
mbedtls_sha256_free(&ctx);
if (!aborted && got < want) { aborted = true; why = "连接提前结束"; }
if (!aborted && _rel.sha256.length()) {
char hex[65] = {0};
for (int i = 0; i < 32; i++) snprintf(hex + i * 2, 3, "%02x", digest[i]);
if (!_rel.sha256.equalsIgnoreCase(hex)) {
aborted = true;
}
if (aborted) {
// 校验不过就别让这个镜像有机会被启动
Update.abort();
http.end();
fail("sha256 校验失败");
return;
}
}
if (aborted) {
Update.abort();
http.end();
fail(why ? why : "下载中断");
return;
}
s_pct = 100;
if (!Update.end(true)) { // true = 收尾并写好 otadata
http.end();
fail(String("收尾失败: ") + Update.errorString());
return;
}
http.end();
OtaJob* j = new OtaJob();
if (!j) return;
j->st = OtaState::Ready;
j->rel = _rel; // 带上版本号给主线程打日志 / 落 NVS
s_pending = j;
}
// ============================ 手动回滚 ============================
bool OtaService::rollback() {
if (active()) return false;
if (!otherSlotHasImage()) {
_err = String(otherSlot()) + " 里没有可启动的镜像";
return false;
}
const esp_partition_t* other = slotPart(1 - runningIndex());
if (!other) return false;
if (esp_ota_set_boot_partition(other) != ESP_OK) {
_err = "切换启动分区失败";
return false;
}
Preferences prefs;
prefs.begin("ota", false);
prefs.putUInt("try", 0); // 换过去的那一版也要重新计数,别一开机又被判失败
prefs.end();
LOG("OTA", "rollback -> %s, rebooting", otherSlot());
delay(200);
ESP.restart();
return true;
}
} // namespace svc

View File

@ -0,0 +1,92 @@
#pragma once
// OtaService.h —— 固件在线升级(A/B 双槽)
//
// 设计前提(见根目录 partitions.csv):app0 / app1 是两个对等的 ota 槽。
// - 运行时固件只写"非当前运行"的那个槽,写完把 otadata 指过去;
// - 所以另一个槽天然留着上一个能跑的版本,这就是回滚的本钱;
// - 能不能回滚不看"我以为它在",而是读槽首字节 0xE9(ESP 镜像魔数)确认。
//
// 为什么不用 IDF 的 rollback(esp_ota_mark_app_*):
// Arduino 的 sdkconfig 没开 CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE,
// 那套 API 直接返回 ESP_ERR_OTA_INVALID_STATE。所以自己做"开机尝试计数":
// 每启动一次 +1,稳定运行 60 秒后清零;连续 3 次没稳住就切回另一个槽。
//
// 线程约定(和 WeatherService / PlatformService 一致):
// 网络与 flash 写入都在后台任务里;状态只写 s_* 待合并区,
// 主线程 loop() 合并、驱动 LVGL、决定何时重启。
#include <Arduino.h>
namespace svc {
enum class OtaState : uint8_t {
Idle, // 没查过
Checking, // 正在问服务端有没有新版
UpToDate, // 已是最新
Available, // 有新版本,等用户确认
Downloading, // 下载中
Verifying, // 校验 sha256
Ready, // 校验通过,即将重启
Failed, // 出错(看 error())
};
struct OtaRelease {
String version;
String url; // 绝对地址或相对服务端根的路径
String sha256; // 十六进制,小写;空表示服务端没给(不推荐)
String notes;
uint32_t size = 0; // 字节能为 0(服务端没给)
bool mandatory = false;
bool valid() const { return version.length() > 0 && url.length() > 0; }
};
class OtaService {
public:
// 开机最早调用:自增尝试计数、必要时自动切槽回滚
void begin();
// 主线程每帧调用:合并进度、到点重启
void loop();
bool check(); // 后台检查更新
bool start(); // 开始下载(Available 时)
void startFromUrl(const String& url, const String& version); // 手工指定地址(串口/调试)
bool rollback(); // 切回另一个槽并重启
OtaState state() const { return _st; }
const OtaRelease& release() const { return _rel; }
int progress() const { return _pct; }
const String& error() const { return _err; }
// 正在下载/校验:其它网络任务(天气/星盘/资料)要主动让路
bool active() const {
return _st == OtaState::Downloading || _st == OtaState::Verifying;
}
// ---- 槽位信息(静态,UI 直接用)----
static const char* runningSlot(); // "app0" / "app1"
static const char* otherSlot();
static bool otherSlotHasImage(); // 另一槽有可启动镜像
static uint32_t slotSizeKB(int idx);
// 后台任务入口(由 dispatch 创建,外部不要调)
void doCheck();
void doDownload();
private:
void dispatchCheck();
void dispatchDownload();
void applyResult(); // 主线程合并
void fail(const String& msg);
String absoluteUrl(const String& u) const;
OtaState _st = OtaState::Idle;
OtaRelease _rel;
String _err;
volatile int _pct = 0;
uint32_t _readyAt = 0;
uint32_t _startedAt = 0;
bool _dirty = false; // 后台写了结果,等主线程合并
};
extern OtaService ota;
} // namespace svc

View File

@ -0,0 +1,540 @@
#include "PlatformService.h"
#include "NetService.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../config/AppConfig.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <time.h>
#include <sys/time.h>
#include <esp_system.h>
namespace svc {
PlatformService platform;
// 服务端设备表里登记的型号(与 01-总体设计.md 一致)
static const char* kModel = "JC3636K518C_I_W";
enum OpCode : uint8_t { OP_NONE = 0, OP_CODE, OP_STATUS, OP_CLAIM, OP_PROFILE, OP_PING, OP_PROBE };
// 单飞:同一时刻只允许一个请求在飞。任务只写 s_job,主线程读完清 done。
struct Job {
uint8_t op = OP_NONE;
bool done = false;
int status = 0;
String body;
};
static Job s_job;
static volatile bool s_running = false;
// 服务端可达性:最近一次走 httpDo 的请求有没有拿到 HTTP 应答(status>0,
// 4xx/5xx 也算——能回错说明服务端活着)。记住地址本身:用户在网页/设备上
// 改了 net.server 后,旧地址的"可达"结论不能算数,serverOk() 自动失效。
static String s_srvBase;
static volatile bool s_srvOk = false;
// ============================ 时间工具 ============================
// 公历 → 距离 1970-01-01 的天数(Howard Hinnant 算法,无时区依赖)
static int64_t daysFromCivil(int y, unsigned m, unsigned d) {
y -= m <= 2;
const int64_t era = (y >= 0 ? y : y - 399) / 400;
const unsigned yoe = (unsigned)(y - era * 400);
const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + (int64_t)doe - 719468;
}
// 解析 "2026-11-04T13:20:32+08:00" / "...Z",同时取出偏移分钟数。
// 服务端返回的是本地时区的 isoformat,一趟就能拿到"时刻 + 时区"两件事。
static bool parseIso(const char* s, time_t& utc, int& offMin) {
if (!s || !*s) return false;
int Y = 0, M = 0, D = 0, h = 0, mi = 0, sec = 0;
if (sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2d", &Y, &M, &D, &h, &mi, &sec) != 6) return false;
offMin = 0;
const char* p = strchr(s, 'T');
if (p) {
p += 9; // 跳过 "hh:mm:ss"
if (*p == '+' || *p == '-') {
char sign = *p++;
int oh = 0, om = 0;
if (sscanf(p, "%2d:%2d", &oh, &om) >= 1) {
offMin = (oh * 60 + om) * (sign == '-' ? -1 : 1);
}
}
}
int64_t days = daysFromCivil(Y, (unsigned)M, (unsigned)D);
utc = (time_t)(days * 86400 + h * 3600 + mi * 60 + sec - (int64_t)offMin * 60);
return true;
}
// 落表 + 设时区:settimeofday 写的是 UTC,本地时间靠 TZ 环境变量换算
static void applyClock(time_t utc, int offMin) {
struct timeval tv;
tv.tv_sec = utc;
tv.tv_usec = 0;
settimeofday(&tv, nullptr);
int hh = offMin / 60;
int mm = abs(offMin % 60);
char tz[24];
// POSIX 的符号是反的:UTC+8 写成 "UTC-8"
snprintf(tz, sizeof(tz), "UTC%+d:%02d", -hh, mm);
setenv("TZ", tz, 1);
tzset();
// 时区设置项已删(跟账号资料走);TZ 环境变量上面已经设好,
// 设备侧不再维护第二份偏移。
LOG("PF", "clock set, tz UTC%+d:%02d", hh, mm);
}
// ============================ HTTP ============================
// 所有设备侧 HTTP 串行化:天气/星盘/资料三个任务本来是各起一个,
// 开机时几乎同时打,既抢堆又并发读 NVS(Preferences 不是线程安全的)。
// 一把互斥锁把它们排成队,单次请求几百毫秒,对体验没有影响。
static SemaphoreHandle_t s_httpMux = nullptr;
static bool httpDo(const char* method, const String& path, const String& payload,
const String& token, String& out, int& status) {
if (!s_httpMux) s_httpMux = xSemaphoreCreateMutex();
if (s_httpMux) xSemaphoreTake(s_httpMux, portMAX_DELAY);
struct Unlock {
~Unlock() { if (s_httpMux) xSemaphoreGive(s_httpMux); }
} unlockGuard;
String base = net.serverUrl();
if (base.isEmpty()) { status = -1; return false; }
s_srvBase = base;
String url = base + path;
bool https = base.startsWith("https");
WiFiClient plain;
WiFiClientSecure tls;
HTTPClient http;
http.setTimeout(8000);
http.setConnectTimeout(5000);
bool started = https ? (tls.setInsecure(), http.begin(tls, url)) : http.begin(plain, url);
if (!started) { status = -2; return false; }
http.addHeader("Accept", "application/json");
if (payload.length()) http.addHeader("Content-Type", "application/json");
if (token.length()) http.addHeader("Authorization", "Bearer " + token);
status = (strcmp(method, "POST") == 0) ? http.POST(payload) : http.GET();
if (status > 0) out = http.getString();
http.end();
s_srvOk = (status > 0);
return status > 0;
}
bool PlatformService::serverOk() const {
return s_srvOk && s_srvBase == net.serverUrl();
}
bool PlatformService::get(const String& path, String& body, int& status) {
return httpDo("GET", path, "", _token, body, status);
}
bool PlatformService::post(const String& path, const String& json, String& body, int& status) {
return httpDo("POST", path, json, _token, body, status);
}
// ============================ 后台任务 ============================
bool PlatformService::dispatch(uint8_t op) {
if (s_running) return false; // 单飞,本轮先不排;loop 兜底会补发
s_running = true;
_busy = true;
s_job.op = op;
s_job.done = false;
s_job.body = "";
if (xTaskCreatePinnedToCore([](void* arg) {
((PlatformService*)arg)->runJob();
vTaskDelete(nullptr);
}, "pf_http", 16384, this, 1, nullptr, 0) != pdPASS) {
s_running = false;
_busy = false;
// 堆碎片化时 16KB 连续栈申请不到。失败了就别每秒重试——
// 刷屏会把真正的报错挤没,30 秒后再试一次就够
static uint32_t retryAt = 0;
if (millis() >= retryAt) {
LOG("PF", "task create failed (heap low), retry in 30s");
retryAt = millis() + 30000;
}
return false;
}
return true;
}
void PlatformService::runJob() {
String path, payload, out;
int status = 0;
switch (s_job.op) {
case OP_CODE: {
JsonDocument doc;
doc["chip_id"] = _chip;
doc["model"] = kModel;
doc["fw_version"] = KNOBOS_VERSION;
serializeJson(doc, payload);
path = "/device/v1/pair/code";
httpDo("POST", path, payload, "", out, status);
break;
}
case OP_STATUS:
path = "/device/v1/pair/status?code=" + _code + "&chip_id=" + _chip;
httpDo("GET", path, "", "", out, status);
break;
case OP_CLAIM: {
JsonDocument doc;
doc["code"] = _code;
doc["chip_id"] = _chip;
serializeJson(doc, payload);
path = "/device/v1/pair/claim";
httpDo("POST", path, payload, "", out, status);
break;
}
case OP_PROFILE:
httpDo("GET", "/device/v1/profile", "", _token, out, status);
break;
case OP_PING:
httpDo("GET", "/device/v1/ping", "", _token, out, status);
break;
case OP_PROBE:
// 未绑定时也要能判断"服务端到底通没通":/healthz 不需要鉴权,
// 回什么码都算服务端活着。没有这一步,未绑定的设备永远不会向
// 服务端发请求,界面就只能永远停在"正在连接服务端…"。
httpDo("GET", "/healthz", "", "", out, status);
break;
default:
break;
}
s_job.status = status;
s_job.body = out;
s_job.done = true;
s_running = false;
_busy = false;
}
// ============================ 生命周期 ============================
void PlatformService::begin() {
uint64_t mac = ESP.getEfuseMac();
char buf[20];
snprintf(buf, sizeof(buf), "%012llX", (unsigned long long)(mac & 0xFFFFFFFFFFFFULL));
_chip = buf;
_token = settings.getS("pf.token");
_device = settings.getS("pf.device");
if (_token.length()) _ps = PairState::Bound;
LOG("PF", "chip=%s bound=%d", _chip.c_str(), (int)bound());
}
void PlatformService::loop() {
if (_revoked) { // token 被吊销:回主线程再做清理
_revoked = false;
unpair();
}
if (s_job.done) {
s_job.done = false;
apply();
}
// 绑定页开着:每 5 秒问一次"用户在网页上确认了吗"
if (_ps == PairState::Waiting && millis() - _lastPollMs > 5000) {
pollPair();
}
// 码到期:自动换一张,用户不用手动刷新
if (_ps == PairState::Waiting && _codeExpireMs &&
(int32_t)(millis() - _codeExpireMs) > 0) {
LOG("PF", "pair code expired, asking new one");
startPairing(true);
}
// 取码兑底一:Asking 停留太久且没有请求在飞,说明请求被丢/任务丢了,
// 重发一次。_busy 由 dispatch 置位,能区分"请求在飞"和"压根没发出去"。
if (_ps == PairState::Asking && !_busy && millis() - _askMs > 3000UL) {
LOG("PF", "pair code request lost, retrying");
dispatch(OP_CODE);
_askMs = millis();
}
// 取码兑底二:失败自动重试(绑定页开着时用户不该自己点屏幕)。
// 409 这类致命错误(服务端认为已绑定)不重试——要用户先去网页解绑。
if (_ps == PairState::Failed && !_noRetry && net.online() &&
millis() - _askMs > 8000UL) {
LOG("PF", "pair code failed, auto retry");
startPairing(true);
}
// 已绑定但资料还没拿到(刚开机):联网后补一次
if (bound() && !_pf.valid && net.online() && millis() > 6000) {
requestProfile();
}
// 未绑定 + 联网了:每 15 秒探一次服务端是否活着。
// 探到了界面才敢说"未绑定";探不到就继续显示"正在连接服务端…"。
if (!bound() && net.online() && !serverOk() && millis() - _lastProbeMs > 15000UL) {
_lastProbeMs = millis();
dispatch(OP_PROBE);
}
// 开机还没对过时:WiFi 连上往往比时钟页首帧晚好几秒,
// onEnter 里那次 syncTime() 会因为"还没联网"空手而回。
// 这里补上:没对过时就一直重试(syncTime 自带 1 分钟节流),别等 10 分钟心跳。
if (bound() && net.online() && !_timeSynced && millis() > 6000) {
syncTime();
}
// 静默心跳:10 分钟一次,顺带把时钟拉正
if (bound() && net.online() && millis() - _lastPingMs > 600000UL) {
syncTime();
}
}
// ============================ 配对 ============================
// 取码流程有两类卡死,这里都兑住:
// 1. dispatch 被单飞丢掉:取码请求撞上在飞的探活/资料请求时会被静默丢弃,
// 以前没人补发,绑定页就永远停在"正在取码…",点屏幕也没用(Asking 挡回)。
// 2. 失败后不重试:以前取码失败进 Failed 就只能等用户点屏幕,而且
// 绑定页对 Failed 也显示"正在取码…",看起来像卡死。
void PlatformService::startPairing(bool forceNewCode) {
if (bound()) { _ps = PairState::Bound; return; }
if (!net.online()) {
_ps = PairState::Failed;
_err = "设备未联网,先配网";
_noRetry = true; // 没联网重试也没用,先去配网
return;
}
if (_ps == PairState::Asking || _ps == PairState::Claiming) return;
if (!forceNewCode && _code.length() && pairLeftSec() > 0) {
_ps = PairState::Waiting;
return;
}
_code = "";
_err = "";
_noRetry = false;
_askMs = millis();
_ps = PairState::Asking;
_codeExpireMs = 0;
if (!dispatch(OP_CODE)) {
// 单飞被占(探活/资料在飞):请求被丢。不留在 Asking——loop 里的
// Failed 重试会在几秒后自动再试,用户只需等一下,不用点屏幕。
_ps = PairState::Failed;
_err = "服务端忙,稍后自动重试";
}
}
void PlatformService::pollPair() {
if (_ps != PairState::Waiting || _code.isEmpty()) return;
_lastPollMs = millis();
dispatch(OP_STATUS);
}
void PlatformService::cancelPairing() {
if (_ps == PairState::Bound) return;
_ps = PairState::Idle;
_code = "";
_noRetry = false;
}
void PlatformService::unpair() {
settings.setS("pf.token", "");
settings.setS("pf.device", "");
_token = "";
_device = "";
_pf = PlatformProfile();
_ps = PairState::Idle;
_code = "";
LOG("PF", "unpaired locally");
}
uint32_t PlatformService::pairLeftSec() const {
if (!_codeExpireMs) return 0;
int32_t left = (int32_t)(_codeExpireMs - millis());
return left > 0 ? (uint32_t)(left / 1000) : 0;
}
const char* PlatformService::pairHint() const {
switch (_ps) {
case PairState::Asking: return "正在取码…";
case PairState::Waiting: return "在网页端输入此码";
case PairState::Claiming: return "正在绑定…";
case PairState::Bound: return "绑定成功";
case PairState::Failed: return _err.length() ? _err.c_str() : "配对失败";
default: return "未绑定";
}
}
const char* PlatformService::stateHint() const {
if (!net.online()) return "等待网络连接…";
if (!serverOk()) return "正在连接服务端…";
if (!bound()) return "设备未绑定 · 请先完成配对";
return "";
}
// ============================ 结果合并(主线程) ============================
void PlatformService::apply() {
switch (s_job.op) {
case OP_CODE: handlePairCode(s_job.body, s_job.status); break;
case OP_STATUS: handlePairStatus(s_job.body); break;
case OP_CLAIM: handlePairClaim(s_job.body, s_job.status); break;
case OP_PROFILE: handleProfile(s_job.body, s_job.status); break;
case OP_PING: handlePing(s_job.body); break;
default: break;
}
}
void PlatformService::handlePairCode(const String& body, int status) {
if (status == 409) {
// 服务端认为这台机已绑定:重试也是 409,得用户先去网页解绑。
_ps = PairState::Failed;
_err = "服务端显示已绑定,请先在网页解绑";
_noRetry = true;
return;
}
if (status != 200) {
_ps = PairState::Failed;
_err = String("取码失败 HTTP ") + status;
_noRetry = false; // 网络/服务端临时故障,过几秒自动重试
LOG("PF", "pair/code -> %d %s", status, body.c_str());
return;
}
JsonDocument doc;
if (deserializeJson(doc, body)) {
_ps = PairState::Failed;
_err = "返回解析失败";
return;
}
_code = String((const char*)(doc["code"] | ""));
int ttl = doc["expires_in"] | 600;
_codeExpireMs = millis() + (uint32_t)ttl * 1000UL;
_lastPollMs = 0;
_ps = PairState::Waiting;
// 取码响应里就带服务端时间,顺手把钟对准
const char* st = doc["server_time"] | "";
time_t utc; int off = 0;
if (parseIso(st, utc, off)) {
applyClock(utc, off);
_timeSynced = true;
}
LOG("PF", "pair code=%s ttl=%ds", _code.c_str(), ttl);
}
void PlatformService::handlePairStatus(const String& body) {
if (_ps != PairState::Waiting && _ps != PairState::Claiming) return;
JsonDocument doc;
if (deserializeJson(doc, body)) return;
const char* st = doc["status"] | "";
if (strcmp(st, "bound") == 0) {
LOG("PF", "user confirmed -> claim");
_ps = PairState::Claiming;
dispatch(OP_CLAIM);
} else if (strcmp(st, "expired") == 0) {
// 服务端说码没了:立刻触发换码(loop 里的过期分支会接手)
_codeExpireMs = millis();
}
}
void PlatformService::handlePairClaim(const String& body, int status) {
if (status == 409) { // 网页还没确认,退回等待
_ps = PairState::Waiting;
return;
}
if (status != 200) {
_ps = PairState::Failed;
_err = (status == 404) ? "配对码已过期,请重新取码" : String("换 token 失败 ") + status;
LOG("PF", "claim -> %d %s", status, body.c_str());
return;
}
JsonDocument doc;
if (deserializeJson(doc, body)) { _ps = PairState::Failed; _err = "返回解析失败"; return; }
_token = String((const char*)(doc["token"] | ""));
_device = String((const char*)(doc["device_id"] | ""));
if (_token.isEmpty()) { _ps = PairState::Failed; _err = "token 为空"; return; }
settings.setS("pf.token", _token);
settings.setS("pf.device", _device);
_ps = PairState::Bound;
_code = "";
_codeExpireMs = 0;
// 换 token 的响应里就带 user 对象,直接吃下来,省一次 profile 请求
JsonObjectConst u = doc["user"];
_pf.valid = true;
_pf.nickname = String((const char*)(u["nickname"] | ""));
_pf.sunName = String((const char*)(u["sun_sign_name"] | ""));
_pf.sunSymbol= String((const char*)(u["sun_symbol"] | ""));
LOG("PF", "bound device=%s user=%s", _device.c_str(), _pf.nickname.c_str());
requestProfile(true); // 再刷一次,确保字段完整
}
void PlatformService::handleProfile(const String& body, int status) {
if (status == 401) { // token 被吊销(网页解绑 / 停用)
LOG("PF", "token revoked -> unpair");
unpair();
return;
}
if (status != 200) {
_err = String("资料同步失败 ") + status;
return;
}
JsonDocument doc;
if (deserializeJson(doc, body)) return;
_pf.nickname = String((const char*)(doc["nickname"] | ""));
_pf.sunName = String((const char*)(doc["sun_sign_name"] | ""));
_pf.sunSymbol = String((const char*)(doc["sun_symbol"] | ""));
// 用户页要展示的三样:生日 / 常住地 / 时区(都在 web 端改,设备只读)
_pf.birthday = String((const char*)(doc["birthday"] | ""));
const char* place = doc["residence_place"] | (const char*)(doc["residence_city"] | "");
_pf.residence = String(place);
_pf.timezone = String((const char*)(doc["timezone"] | ""));
_pf.valid = true;
LOG("PF", "profile: %s %s", _pf.nickname.c_str(), _pf.sunName.c_str());
}
void PlatformService::handlePing(const String& body) {
if (body.isEmpty()) return;
JsonDocument doc;
if (deserializeJson(doc, body)) return;
const char* ts = doc["ts"] | "";
time_t utc; int off = 0;
if (parseIso(ts, utc, off)) {
applyClock(utc, off);
_timeSynced = true;
}
}
void PlatformService::requestProfile(bool force) {
if (!bound() || !net.online()) return;
if (!force && _pf.valid && millis() - _lastProfileMs < 60000UL) return;
_lastProfileMs = millis();
_err = ""; // 清掉上次的错,好让"我的"页按本次结果给反馈
dispatch(OP_PROFILE);
}
void PlatformService::syncTime() {
if (!bound() || !net.online()) return;
// 一分钟内不重复打:进时钟页、开绑定页都会顺手调它
if (millis() - _lastPingMs < 60000UL) return;
_lastPingMs = millis();
dispatch(OP_PING);
}
} // namespace svc

View File

@ -0,0 +1,119 @@
#pragma once
// PlatformService.h —— 与 nex_buddy 平台的所有联动都收在这里
//
// 职责边界:
// 1. 设备身份:chip_id(efuse MAC)+ 长期 token(NVS: pf.token / pf.device)
// 2. 配对状态机:取码 → 等用户在网页确认 → 换 token → 落 NVS
// 3. 资料同步:/device/v1/profile(昵称、太阳星座…)
// 4. 校时:任何响应里的 server_time / ts → settimeofday + TZ
// 5. 给 WeatherService 提供带鉴权的 GET
//
// 线程约定(和 WeatherService 一样):
// 网络请求全部在后台任务里跑;结果只写 s_res,主线程在 loop() 里合并,
// 任务绝不碰 LVGL / Settings(NVS 写也在主线程做)。
#include <Arduino.h>
namespace svc {
enum class PairState : uint8_t {
Idle, // 没在配对
Asking, // 正在向服务端要码
Waiting, // 码已上屏,等用户在网页输入
Claiming, // 用户已确认,正在换 token
Bound, // 绑定完成
Failed, // 出错(看 lastError)
};
struct PlatformProfile {
bool valid = false;
String nickname;
String birthday; // "YYYY-MM-DD",没填为空
String residence; // 常住地(place 优先,退 city)
String timezone; // IANA 名,如 "Asia/Shanghai"
String sunName; // 太阳星座中文名,如"天蝎座"
String sunSymbol; // 符号,如"♏"
};
class PlatformService {
public:
void begin();
void loop();
// ---- 身份 ----
bool bound() const { return _token.length() > 0; }
// 服务端最近是否有 HTTP 应答。地址变更后自动失效——UI 用它区分
// 「服务端还没连上」和「服务端确认了:没绑定」,不许在没问过服务端
// 之前就把"未绑定"三个字顶到屏幕上。
bool serverOk() const;
const String& chipId() const { return _chip; }
const String& token() const { return _token; }
const String& deviceId() const { return _device; }
// ---- 配对 ----
void startPairing(bool forceNewCode = false);
void pollPair(); // 绑定页内每 5 秒调一次
void cancelPairing();
void unpair(); // 清本地 token(服务端解绑后调用)
PairState pairState() const { return _ps; }
const String& pairCode() const { return _code; }
uint32_t pairLeftSec() const; // 码剩余秒数(上屏倒计时用)
const char* pairHint() const; // 上屏的一句话状态
// 未绑定/未联网时的统一空态文案(各模块共用,保证口径一致):
// 等待网络连接… / 正在连接服务端… / 设备未绑定 · 请先完成配对
// 已绑定返回空串(页面此时不该显示这行)。
const char* stateHint() const;
// ---- 资料 ----
void requestProfile(bool force = false);
const PlatformProfile& profile() const { return _pf; }
// ---- 校时 ----
void syncTime(); // 拉一次 /ping,用服务端时间校准
bool timeSynced() const { return _timeSynced; }
// 给 WeatherService 用:带 Bearer 的 GET。返回是否拿到了 HTTP 响应
bool get(const String& path, String& body, int& status);
// 给 OtaService 上报进度用:带 Bearer 的 POST(JSON 体)
bool post(const String& path, const String& json, String& body, int& status);
bool busy() const { return _busy; }
const String& lastError() const { return _err; }
// 内部:后台任务入口(由 dispatch 创建,外部不要调)
void runJob();
// 后台任务发现 token 被吊销时只能置个标记:
// NVS 写入和 UI 通知都要回主线程做,任务里直接改会踩到 Settings 的回调。
void noteRevoked() { _revoked = true; }
private:
// 返回是否真的排上了(单飞被占/建任务失败返回 false,调用方据此兜底)
bool dispatch(uint8_t op);
void apply();
void handlePairCode(const String& body, int status);
void handlePairStatus(const String& body);
void handlePairClaim(const String& body, int status);
void handleProfile(const String& body, int status);
void handlePing(const String& body);
String _token, _device, _chip;
String _code;
String _err;
uint32_t _codeExpireMs = 0;
uint32_t _lastPollMs = 0;
uint32_t _lastProfileMs = 0;
uint32_t _lastPingMs = 0;
uint32_t _lastProbeMs = 0; // 未绑定时探服务端活着的节流
uint32_t _askMs = 0; // 最近一次取码尝试时刻(Asking 兑底/失败重试用)
bool _noRetry = false; // 致命错误(如 409 已绑定):重试无意义,要用户先去网页解绑
PairState _ps = PairState::Idle;
PlatformProfile _pf;
bool _timeSynced = false;
bool _busy = false;
volatile bool _revoked = false;
};
extern PlatformService platform;
} // namespace svc

View File

@ -0,0 +1,288 @@
#include "RemoteDebug.h"
#include "../hal/Display.h"
#include "../hal/Encoder.h"
#include "../hal/Storage.h"
#include "../ui/Shell.h"
#include "../ui/Splash.h"
#include "../ui/QrScreen.h"
#include "../core/AppManager.h"
#include "../core/Log.h"
#include "../config/AppConfig.h"
#include "../services/MusicLibrary.h"
#include "../services/NetService.h"
#include "../services/OtaService.h"
#include "../services/MediaSync.h"
#include "../core/Settings.h"
#include "../apps/MusicApp.h"
#include "../apps/SettingsApp.h"
#include <Arduino.h>
#include <SD_MMC.h>
namespace svc {
RemoteDebug remoteDbg;
void RemoteDebug::begin() {
LOG("DBG", "console: 1-8=app u=menu d=sheet c=close s=shot +/-=knob v/x=splash m=music F=putfile W=wifi U=server A=ap M=sta V=ota C=check I=install O=fwurl R=rollback Q=qr N=net K=scan ?=stat");
}
static void shoot() {
hal::captureStart();
lv_obj_invalidate(lv_scr_act());
lv_refr_now(nullptr); // 强制刷一帧,刷屏回调里顺便拼图
if (!hal::captureDone()) {
Serial.println("SHOT_FAIL");
hal::captureStop();
return;
}
const uint16_t* buf = hal::captureBuffer();
const uint32_t n = (uint32_t)SCREEN_W * SCREEN_H * 2;
Serial.printf("SHOT %d %d %u\n", SCREEN_W, SCREEN_H, (unsigned)n);
Serial.write((const uint8_t*)buf, n);
Serial.flush();
hal::captureStop();
LOG("DBG", "shot sent (%u bytes)", (unsigned)n);
}
// 列出本地曲库(元数据走的是真 ID3 解析路径,能直接看出解析对不对)
static void musicList() {
int n = svc::musicLib.count();
Serial.printf("MUS ready=%d scanning=%d count=%d\n",
(int)svc::musicLib.ready(), (int)svc::musicLib.scanning(), n);
for (int i = 0; i < n; i++) {
svc::Track t = svc::musicLib.at(i);
Serial.printf("MUS %d|%s|%s|%s|cov=%u,%u,%d|dur=%u\n", i,
t.path.c_str(), t.title.c_str(), t.artist.c_str(),
(unsigned)t.coverOff, (unsigned)t.coverLen, (int)t.coverJpeg,
(unsigned)t.durationSec);
}
Serial.println("MUS_END");
}
// F <name> <size>\n + 原始字节:把主机上的文件塞进 TF 卡(测试图片/音乐用)
static void putFile() {
String hdr = Serial.readStringUntil('\n');
hdr.trim();
// 只有"路径 大小"两段:按最后一个空格切,indexOf 和 lastIndexOf 会重合
int sp = hdr.lastIndexOf(' ');
if (sp <= 0) { Serial.println("PUT_ERR header"); return; }
String name = hdr.substring(0, sp);
uint32_t size = hdr.substring(sp + 1).toInt();
if (name.length() == 0 || name.indexOf("..") >= 0 || !name.startsWith("/") || size == 0 || size > 1024 * 1024) {
Serial.println("PUT_ERR arg");
return;
}
Serial.println("PUT_RDY");
hal::storageLock();
File f = SD_MMC.open(name, FILE_WRITE);
if (!f) {
hal::storageUnlock();
Serial.println("PUT_ERR open");
return;
}
uint32_t got = 0;
uint8_t buf[512];
uint8_t page[4096];
size_t pageLen = 0;
uint32_t last = millis();
// 用 readBytes 阻塞等数据,不要用 available() 轮询:
// 写 SD 的那几毫秒里 USB CDC 还在来数据,轮询会漏字节,最后表现为 PUT_ERR short
while (got < size) {
size_t want = size - got;
if (want > sizeof(buf)) want = sizeof(buf);
int rd = Serial.readBytes(buf, want);
if (rd <= 0) {
if (millis() - last > 8000) break; // 8s 没有新数据才算断流
continue;
}
memcpy(page + pageLen, buf, rd);
pageLen += rd;
got += rd;
last = millis();
if (pageLen + sizeof(buf) > sizeof(page)) { // 攒 4KB 落一次盘
f.write(page, pageLen);
pageLen = 0;
}
}
if (pageLen) f.write(page, pageLen);
f.flush();
f.close();
hal::storageUnlock();
if (got == size) {
Serial.printf("PUT_OK %u\n", (unsigned)got);
svc::musicLib.scanAsync(); // 可能是音乐,直接重扫
} else {
// 带上实际收到多少:USB CDC 侧丢字节时会小于 size
Serial.printf("PUT_ERR short %u/%u\n", (unsigned)got, (unsigned)size);
}
}
// W <ssid>,<密码>\n —— 主机端直接下发 WiFi 凭据
// 存在的理由:macOS 14+ 没有定位授权时 CoreWLAN 关联一律 -3900,
// 从 Mac 连不上设备热点;串口是唯一不依赖用户点屏幕的配置通道。
static void setWifi() {
String line = Serial.readStringUntil('\n');
line.trim();
int comma = line.indexOf(',');
if (line.length() == 0 || comma <= 0) {
Serial.println("WIFI_ERR usage: W ssid,password");
return;
}
String ssid = line.substring(0, comma);
String pwd = line.substring(comma + 1);
ssid.trim();
pwd.trim();
if (ssid.length() == 0) { Serial.println("WIFI_ERR empty ssid"); return; }
Serial.printf("WIFI_TRY ssid=%s pwdlen=%u\n", ssid.c_str(), (unsigned)pwd.length());
svc::net.connect(ssid, pwd);
}
// U <url>\n —— 主机端下发服务端地址(设备端 UI 已只读,配网页又需要连热点)
static void setServerUrl() {
String url = Serial.readStringUntil('\n');
url.trim();
while (url.endsWith("/")) url.remove(url.length() - 1);
if (!url.startsWith("http://") && !url.startsWith("https://")) {
Serial.println("SRV_ERR usage: U http://host:port");
return;
}
settings.setS("net.server", url);
Serial.printf("SRV_OK %s\n", settings.getS("net.server").c_str());
}
static void otaStatus() {
Serial.printf("OTA slot=%s v%s other=%s(%s) state=%d pct=%d err=%s\n",
svc::ota.runningSlot(), BRAND_VERSION,
svc::ota.otherSlot(), svc::ota.otherSlotHasImage() ? "image" : "empty",
(int)svc::ota.state(), svc::ota.progress(),
svc::ota.error().length() ? svc::ota.error().c_str() : "-");
}
static void startOtaFromUrl() {
String url = Serial.readStringUntil('\n');
url.trim();
if (!url.startsWith("http://") && !url.startsWith("https://")) {
Serial.println("OTA_ERR usage: O http://host/path/app.bin");
return;
}
Serial.printf("OTA_BEGIN %s\n", url.c_str());
svc::ota.startFromUrl(url, "");
}
void RemoteDebug::loop() {
while (Serial.available() > 0) {
int c = Serial.read();
switch (c) {
case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': {
int idx = c - '1';
App* a = appMgr.byIndex((uint8_t)idx);
if (a) {
ui::shell.closeLauncher();
ui::shell.closeSheet();
ui::shell.switchTo(a);
LOG("DBG", "-> app %d (%s)", idx, a->meta().id);
}
break;
}
case 'u': ui::shell.openLauncher(); break;
case 'd': ui::shell.openSheet(); break;
case 'v': ui::splash.replay(); break; // 重播启动动画并停在中途
case 'x': ui::splash.dismiss(); break;
// + / -:凭空拧一格旋钮,主机端用它验证"旋钮 → 界面"链路
case '+': hal::encoderInject(1); break;
case '-': hal::encoderInject(-1); break;
case 'c':
ui::shell.closeLauncher();
ui::shell.closeSheet();
ui::shell.closeModals();
break;
case 'g': ui::shell.openNetWizard(); break; // 配网向导
case 'S': ui::shell.openServerEditor(); break; // 服务端地址编辑器
case ']': ui::shell.wizardKnob(1); break;
case '[': ui::shell.wizardKnob(-1); break;
case 'W': setWifi(); break; // 下发 WiFi:W ssid,password
case 'U': setServerUrl(); break; // 下发服务端:U http://host:port
// A/M:热点与 STA 互切。设备一旦连上路由器就不会再广播热点(正常行为),
// 但手机想连配网页、手上又没有屏可点的时候,需要一条不依赖触摸的通道。
case 'A':
// 走请求队列而不是直接切模式:和 UI 路径保持一致(切网口不在事件里做)
svc::net.requestAp();
Serial.printf("AP_REQ ssid=%s pass=%s\n", DEFAULT_AP_SSID, DEFAULT_AP_PASS);
break;
case 'M': { // 回 STA:用 NVS 里的账号重连
String s = settings.getS("net.ssid");
if (s.length()) {
svc::net.connect(s, settings.getS("net.pass"));
Serial.printf("STA_TRY %s\n", s.c_str());
} else {
Serial.println("STA_NONE");
}
break;
}
case 'N': // 网络状态
Serial.printf("NET ssid=%s ip=%s rssi=%d online=%d server=%s\n",
svc::net.ssid().c_str(), svc::net.ip().c_str(), svc::net.rssi(),
(int)svc::net.online(), svc::net.serverUrl().c_str());
Serial.printf("NET mode=%d ap=%s ip=%s status=%d\n",
(int)svc::net.mode(), svc::net.apUp() ? "up" : "down",
WiFi.softAPIP().toString().c_str(), (int)WiFi.status());
break;
case 'K': { // 扫描周边 WiFi(判断 2.4G 有没有)
// 只扫不发包:不进 STA 连接流程,所以不会把当前热点搞挂
int n = WiFi.scanNetworks();
Serial.printf("SCAN n=%d\n", n);
for (int i = 0; i < n; i++) {
Serial.printf(" %2d. %-28s rssi=%d ch=%d %s\n", i + 1,
WiFi.SSID(i).c_str(), (int)WiFi.RSSI(i),
(int)WiFi.channel(i),
WiFi.encryptionType(i) == WIFI_AUTH_OPEN ? "open" : "sec");
}
WiFi.scanDelete();
break;
}
// V=看槽位与升级状态;O=按 URL 直接升(服务端接口没就绪时用它联调);R=手动回滚
case 'V': otaStatus(); break;
case 'Q': // 扫码登录浮层(无触摸时验证用)
if (ui::qrScreen.visible()) {
ui::qrScreen.close();
Serial.println("QR closed");
} else {
ui::qrScreen.open();
Serial.println("QR opened");
}
break;
case 'O': startOtaFromUrl(); break;
case 'L': apps::settingsApp.dumpList(); break; // 导出设置列表的行(排布局问题用)
case 'Y': apps::musicApp.forceSync(); Serial.println("MS_FORCE"); break; // 同步媒体(等同点「同步」)
case 'C': // 走正式接口检查更新(服务端契约)
Serial.println(svc::ota.check() ? "OTA_CHECK started" : "OTA_CHECK busy/unavailable");
break;
case 'I': // 装已知的新版本(等价于点设置页那一行)
Serial.println(svc::ota.start() ? "OTA_START" : "OTA_START err: no update / busy");
break;
case 'R':
if (!svc::ota.rollback()) {
Serial.printf("ROLLBACK_ERR %s\n",
svc::ota.error().length() ? svc::ota.error().c_str() : "no image");
}
break;
case 's': shoot(); break;
case 'm': musicList(); break;
case 'p': apps::musicApp.handleTap(); break; // 播放/暂停(验证唱片旋转)
case 'D': if (!apps::musicApp.dumpDisc()) Serial.println("DISC_NONE"); break;
case 'F': putFile(); break;
case '?':
LOG("DBG", "app=%s launcher=%d sheet=%d heap=%u",
ui::shell.current() ? ui::shell.current()->meta().id : "-",
(int)ui::shell.launcherVisible(), (int)ui::shell.sheetVisible(),
(unsigned)ESP.getFreeHeap());
break;
default: break;
}
}
}
} // namespace svc

View File

@ -0,0 +1,24 @@
#pragma once
// RemoteDebug.h —— 串口调试通道
//
// 为什么需要:设备是圆屏,改完 UI 只能靠猜。这里给一条从 USB 拿画面的路,
// 顺带能远程切页面,改完立刻能看到真实渲染结果。
//
// 命令(单字符,不需要回车):
// 1..5 切到第 N 个应用
// u 打开一级菜单 d 打开应用设置
// c 收起所有覆盖层 s 截屏(回 SHOT w h bytes + 原始 RGB565)
// ? 打印当前状态
#include <stdint.h>
namespace svc {
class RemoteDebug {
public:
void begin();
void loop();
};
extern RemoteDebug remoteDbg;
} // namespace svc

View File

@ -0,0 +1,238 @@
#include "WeatherService.h"
#include "PlatformService.h"
#include "OtaService.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include <WiFi.h>
#include <ArduinoJson.h>
namespace svc {
WeatherService weather;
// 后台任务与主循环之间只通过这一块"待合并区"交接,
// 主循环写 _d、UI 只读 _d,任务只写 pending,避免两边同时改同一个字符串。
//
// 这里**不能**用"全局 FetchResult + 拷贝赋值"的写法:实测本机构建下,静态区里
// String 起来时并不总是干净的空态(s_res.err / _d.error 开机就是 buff=0x80000000、len=0),
// String::operator= 看到 buffer() 非空就去 memmove,直接 LoadProhibited @0x80000000。
// 所以结果放在**堆**上交接:new 出来的对象其 String 一定经过构造,主循环取走后再 delete。
struct FetchResult {
bool ok = false;
WeatherData d;
String err;
};
static FetchResult* s_pending = nullptr; // 任务写,主循环取走
static volatile bool s_ready = false;
static volatile bool s_busy = false;
void WeatherService::begin() {
// 同上:静态对象里的 String 显式归零(等价于 String::init() 的结果),
// 之后对 _d 的赋值才不会踩到 0x80000000。
memset(&_d, 0, sizeof(_d));
// 城市不落本地:由服务端按账号"常住地"解析后随天气一起下发。
// 本地再存一份只会出现过期值(改了常住地,天气还显示老城市)。
_d.city = "";
_nextTryMs = millis() + 5000; // 开机等网络和绑定状态就绪再拉
}
const char* WeatherService::codeToText(int code) {
if (code == 0) return "晴";
if (code <= 2) return "少云";
if (code == 3) return "多云";
if (code == 45 || code == 48) return "雾";
if (code >= 51 && code <= 57) return "毛毛雨";
if (code >= 61 && code <= 65) return "雨";
if (code == 66 || code == 67) return "冻雨";
if (code >= 71 && code <= 77) return "雪";
if (code >= 80 && code <= 82) return "阵雨";
if (code == 85 || code == 86) return "阵雪";
if (code >= 95) return "雷雨";
return "未知";
}
const char* WeatherService::codeToSymbol(int code) {
if (code == 0) return "晴";
if (code <= 3) return "云";
if (code == 45 || code == 48) return "雾";
if (code >= 51 && code <= 67) return "雨";
if (code >= 71 && code <= 86) return "雪";
if (code >= 95) return "雷";
return "?";
}
// 天气决定这个页面的整体色调:晴=暖黄,阴=灰蓝,雨=水蓝,雪=冷白,雷=紫
uint32_t WeatherService::codeToColor(int code) {
if (code < 0) return 0x8FA6B2;
if (code == 0) return 0xFFC107;
if (code <= 2) return 0xFFD54F;
if (code == 3) return 0x90A4AE;
if (code == 45 || code == 48) return 0x78909C;
if (code <= 67) return 0x4FC3F7;
if (code <= 86) return 0xB3E5FC;
return 0xB39DDB;
}
// 和风图标码(字符串 "100"/"302"…)→ 本工程既有的归一化码。
// 这样配色和文案继续复用上面两张表,不用为和风单独写一套。
int WeatherService::normCode(const char* icon) {
int n = atoi(icon ? icon : "");
if (n == 100 || n == 150) return 0; // 晴
if (n >= 101 && n <= 103) return 2; // 少云/晴间多云
if (n == 104) return 3; // 阴
if (n >= 300 && n <= 399) return (n == 302 || n == 303) ? 95 : 61; // 雷 / 雨
if (n >= 400 && n <= 499) return 71; // 雪
if (n >= 500 && n <= 599) return 45; // 雾霾
if (n >= 600 && n <= 699) return 73; // 雨夹雪/冻雨
return 3;
}
// ---- 后台任务本体:只碰 pending,不碰 LVGL ----
static void fetchTask(void* arg) {
((WeatherService*)arg)->doFetch();
s_ready = true;
s_busy = false;
vTaskDelete(nullptr);
}
void WeatherService::doFetch() {
// 结果对象建在堆上:new 出来的 String 一定走过构造函数,是干净的空态。
FetchResult* r = new FetchResult();
if (!r) return;
if (!platform.bound()) {
r->err = "设备未绑定";
s_pending = r;
return;
}
if (WiFi.status() != WL_CONNECTED) {
r->err = "未联网";
s_pending = r;
return;
}
String body;
int status = 0;
if (!platform.get("/device/v1/weather", body, status)) {
r->err = "连不上服务端";
s_pending = r;
return;
}
if (status == 401) {
platform.noteRevoked(); // token 失效:回主线程清 token
r->err = "绑定已失效";
s_pending = r;
return;
}
if (status == 503) { // 服务端没配和风 Key/Host
r->err = "服务端未配置天气";
s_pending = r;
return;
}
if (status != 200) {
r->err = String("服务端 ") + status;
s_pending = r;
return;
}
JsonDocument doc;
if (deserializeJson(doc, body)) {
r->err = "解析失败";
s_pending = r;
return;
}
r->d.city = String((const char*)(doc["city"] | ""));
r->d.tempC = doc["temp"] | 0;
r->d.feels = doc["feels"] | 0;
r->d.humidity = doc["humidity"] | 0;
r->d.text = String((const char*)(doc["text"] | ""));
r->d.windDir = String((const char*)(doc["wind_dir"] | ""));
const char* ws = doc["wind_scale"] | "";
r->d.windScale = atoi(ws);
r->d.code = normCode(doc["code"] | "");
r->d.updatedMs = millis();
r->ok = true;
LOG("WX", "%s %dC %s hum=%d%%", r->d.city.c_str(), r->d.tempC,
r->d.text.c_str(), r->d.humidity);
s_pending = r;
}
bool WeatherService::requestUpdate(bool force) {
if (_d.updating || s_busy) return false;
// 升级正在占着 WiFi 和 flash:这时候再去拉天气只会两败俱伤
if (ota.active()) return false;
if (!platform.bound()) {
_d.error = "设备未绑定";
return false;
}
if (WiFi.status() != WL_CONNECTED) {
_d.error = "未联网";
return false;
}
int32_t iv = settings.getI("wx.interval");
if (iv <= 0) iv = 30; // 见 applyResult() 里的说明
if (!force && _d.valid &&
millis() - _d.updatedMs < (uint32_t)iv * 60UL * 1000UL) {
return false;
}
_d.updating = true;
s_busy = true;
// 实测任务栈只用到 2.7KB(HTTPClient + JSON 都不大),12KB 够;给太大会挤爆堆
if (xTaskCreatePinnedToCore(fetchTask, "wx_http", 12288, this, 1, nullptr, 0) != pdPASS) {
s_busy = false;
_d.updating = false;
// 堆碎片化时 12KB 连续栈申请不到。失败了就别每 5ms 重试——
// 30 秒后再试(同 PlatformService::dispatch 的节流写法)
static uint32_t s_retryAt = 0;
if (millis() >= s_retryAt) {
LOG("WX", "task create failed (heap low), retry in 30s");
s_retryAt = millis() + 30000;
}
_nextTryMs = millis() + 30000;
return false;
}
return true;
}
void WeatherService::applyResult() {
s_ready = false;
FetchResult* p = s_pending;
s_pending = nullptr;
if (!p) return;
if (p->ok) {
WeatherData nd = p->d; // 源是堆对象,字段都是干净的
nd.valid = true;
nd.updating = false;
nd.error = "";
_d = nd;
} else {
_d.updating = false;
_d.error = p->err;
}
delete p;
// 兜底 30 分钟:settings 里读不到(旧版 NVS 没这个键)时 getI() 返回 0,
// 不兜就是每 loop 一次请求
int32_t iv = settings.getI("wx.interval");
if (iv <= 0) iv = 30;
_nextTryMs = millis() + (uint32_t)iv * 60UL * 1000UL;
}
void WeatherService::loop() {
if (s_ready) applyResult();
if (millis() < _nextTryMs) return;
if (!platform.bound()) {
_nextTryMs = millis() + 30000; // 没绑定就别再敲服务端了
return;
}
if (WiFi.status() != WL_CONNECTED) {
_nextTryMs = millis() + 30000;
return;
}
requestUpdate();
}
} // namespace svc

View File

@ -0,0 +1,58 @@
#pragma once
// WeatherService.h —— 天气数据
//
// 数据源:nex_buddy 平台 /device/v1/weather(服务端聚合和风 + Redis 缓存 30min)。
// 设备不持有任何第三方 Key,也不直连和风——换供应商不用动固件。
// 城市由服务端按账号资料(居住地 → 出生地)决定,设备不再传经纬度。
//
// 拉取放在独立任务里做:一次请求要几百毫秒,同步跑会把 UI 冻住,
// 圆屏上表现为"进天气页就不动了"。这里改成发一次请求、后台取、回来后合并。
#include <Arduino.h>
namespace svc {
struct WeatherData {
bool valid = false;
bool updating = false;
int tempC = 0; // 实况温度
int feels = 0; // 体感
int humidity = 0;
int windScale = 0; // 风力等级
int code = -1; // 归一化天气码(沿用 codeToColor 的语义)
uint32_t updatedMs = 0;
String city; // 服务端规范化后的城市名
String text; // "晴" / "小雨"(服务端给的中文描述)
String windDir;
String error;
};
class WeatherService {
public:
void begin();
void loop();
// 发起一次后台拉取(立即返回,不阻塞 LVGL)
bool requestUpdate(bool force = false);
bool busy() const { return _d.updating; }
const WeatherData& data() const { return _d; }
void invalidate() { _d.valid = false; }
static const char* codeToText(int code);
static const char* codeToSymbol(int code); // 用 LVGL 符号/文字示意
static uint32_t codeToColor(int code); // 天气主题色
static int normCode(const char* qweatherIcon); // 和风图标码 → 归一化码
// 供后台任务调用,完成一次同步拉取并把结果写进待合并区
void doFetch();
private:
void applyResult();
WeatherData _d;
uint32_t _nextTryMs = 0;
};
extern WeatherService weather;
} // namespace svc

View File

@ -0,0 +1,460 @@
#include "WebPortal.h"
#include "web_ui.h"
#include "NetService.h"
#include "WeatherService.h"
#include "OtaService.h"
#include "../core/Settings.h"
#include "../core/AppManager.h"
#include "../core/Log.h"
#include "../hal/Storage.h"
#include "../hal/Power.h"
#include "../ui/Shell.h"
#include "../config/AppConfig.h"
#include <WebServer.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <SD_MMC.h>
#include <ArduinoJson.h>
#include <esp_ota_ops.h>
#include <esp_partition.h>
namespace svc {
WebPortal webPortal;
static WebServer server(80);
static File s_upFile;
static String s_uploadDir = "/";
static uint32_t s_uploadBytes = 0;
// ---------------------------------------------------------------- 工具
static void sendJson(const JsonDocument& doc) {
String out;
serializeJson(doc, out);
server.sendHeader("Cache-Control", "no-store");
server.send(200, "application/json", out);
}
static String normalizePath(const String& in) {
String p = in.length() ? in : "/";
if (!p.startsWith("/")) p = "/" + p;
// 去掉 .. 穿越
while (p.indexOf("..") >= 0) p.replace("..", "");
while (p.indexOf("//") >= 0) p.replace("//", "/");
if (p.length() > 1 && p.endsWith("/")) p.remove(p.length() - 1);
return p;
}
static const char* contentTypeOf(const String& name) {
String n = name;
n.toLowerCase();
if (n.endsWith(".html")) return "text/html; charset=utf-8";
if (n.endsWith(".css")) return "text/css";
if (n.endsWith(".js")) return "application/javascript";
if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg";
if (n.endsWith(".png")) return "image/png";
if (n.endsWith(".mp3")) return "audio/mpeg";
if (n.endsWith(".json")) return "application/json";
if (n.endsWith(".txt")) return "text/plain; charset=utf-8";
return "application/octet-stream";
}
// ---------------------------------------------------------------- 状态
static void handleStatus() {
JsonDocument doc;
doc["version"] = KNOBOS_VERSION;
doc["mode"] = (net.mode() == NetMode::Ap) ? "ap" : "sta";
doc["online"] = net.online();
doc["ssid"] = net.ssid();
doc["ip"] = net.ip();
doc["rssi"] = net.rssi();
doc["uptime"] = millis() / 1000;
doc["server"] = net.serverUrl();
JsonObject b = doc["battery"].to<JsonObject>();
b["mv"] = hal::batteryMilliVolts();
b["pct"] = hal::batteryPercent();
b["ext"] = hal::externalPower();
JsonObject sd = doc["sd"].to<JsonObject>();
sd["ready"] = hal::storageReady();
sd["total"] = hal::storageTotalBytes();
sd["used"] = hal::storageUsedBytes();
const auto& w = weather.data();
JsonObject wj = doc["weather"].to<JsonObject>();
wj["valid"] = w.valid;
wj["temp"] = w.tempC;
const esp_partition_t* run = esp_ota_get_running_partition();
doc["partition"] = run ? run->label : "?";
doc["app"] = ui::shell.current() ? ui::shell.current()->meta().name : "—";
sendJson(doc);
}
// ---------------------------------------------------------------- 设置
static void handleGetSettings() {
size_t n = 0;
const SettingDesc* t = Settings::table(n);
JsonDocument doc;
JsonArray arr = doc.to<JsonArray>();
for (size_t i = 0; i < n; i++) {
JsonObject o = arr.add<JsonObject>();
o["k"] = t[i].key;
o["l"] = t[i].label;
o["g"] = t[i].group;
o["t"] = (int)t[i].type;
o["min"] = t[i].min;
o["max"] = t[i].max;
o["step"] = t[i].step;
o["u"] = t[i].unit;
o["opt"] = t[i].options;
if (t[i].type == SType::TEXT) o["v"] = settings.getS(t[i].key);
else o["v"] = settings.getI(t[i].key);
}
sendJson(doc);
}
static void handleSetSetting() {
JsonDocument doc;
if (deserializeJson(doc, server.arg("plain")) != DeserializationError::Ok) {
server.send(400, "application/json", "{\"error\":\"bad json\"}");
return;
}
const char* key = doc["key"];
const SettingDesc* d = Settings::find(key);
if (!d) {
server.send(404, "application/json", "{\"error\":\"unknown key\"}");
return;
}
if (d->type == SType::TEXT) {
settings.setS(key, doc["value"].as<String>());
} else {
settings.setI(key, doc["value"].as<int32_t>());
}
server.send(200, "application/json", "{\"ok\":true}");
}
// ---------------------------------------------------------------- 文件
static void handleFiles() {
String path = normalizePath(server.arg("path"));
JsonDocument doc;
doc["path"] = path;
JsonArray dirs = doc["dirs"].to<JsonArray>();
JsonArray files = doc["files"].to<JsonArray>();
if (!hal::storageReady()) {
doc["error"] = "no sd";
sendJson(doc);
return;
}
hal::StorageLock guard;
File dir = SD_MMC.open(path);
if (!dir || !dir.isDirectory()) {
doc["error"] = "not a directory";
sendJson(doc);
return;
}
File f = dir.openNextFile();
while (f) {
String nm = f.name();
int slash = nm.lastIndexOf('/');
if (slash >= 0) nm = nm.substring(slash + 1);
if (!nm.startsWith(".")) { // 过滤 macOS 的 ._ 文件
if (f.isDirectory()) {
dirs.add(nm);
} else {
JsonObject o = files.add<JsonObject>();
o["n"] = nm;
o["s"] = f.size();
}
}
f.close();
f = dir.openNextFile();
}
dir.close();
sendJson(doc);
}
static void handleDownload() {
String path = normalizePath(server.arg("path"));
if (!hal::storageReady()) {
server.send(503, "text/plain", "SD not ready");
return;
}
File f = SD_MMC.open(path, FILE_READ);
if (!f || f.isDirectory()) {
server.send(404, "text/plain", "not found");
return;
}
server.sendHeader("Content-Disposition", "attachment; filename=\"" + path.substring(path.lastIndexOf('/') + 1) + "\"");
server.streamFile(f, contentTypeOf(path));
f.close();
}
static void handleDelete() {
String path = normalizePath(server.arg("path"));
if (path == "/" || path.length() < 2) {
server.send(400, "application/json", "{\"error\":\"bad path\"}");
return;
}
bool ok = false;
{
hal::StorageLock guard;
if (SD_MMC.exists(path)) {
File f = SD_MMC.open(path);
bool isDir = f && f.isDirectory();
if (f) f.close();
ok = isDir ? SD_MMC.rmdir(path) : SD_MMC.remove(path);
}
}
server.send(200, "application/json", ok ? "{\"ok\":true}" : "{\"error\":\"failed\"}");
if (ok) LOG("WEB", "deleted %s", path.c_str());
}
static void handleSetDir() {
s_uploadDir = normalizePath(server.arg("dir"));
server.send(200, "application/json", "{\"ok\":true}");
}
static void handleUploadFinal() {
JsonDocument doc;
doc["ok"] = true;
doc["bytes"] = s_uploadBytes;
sendJson(doc);
s_uploadBytes = 0;
}
static void handleUploadChunk() {
HTTPUpload& up = server.upload();
switch (up.status) {
case UPLOAD_FILE_START: {
String path = s_uploadDir + "/" + up.filename;
LOG("WEB", "upload -> %s", path.c_str());
hal::storageLock();
s_upFile = SD_MMC.open(path, FILE_WRITE);
if (!s_upFile) {
hal::storageUnlock();
LOG("WEB", "upload open failed");
}
s_uploadBytes = 0;
break;
}
case UPLOAD_FILE_WRITE:
if (s_upFile) {
s_upFile.write(up.buf, up.currentSize);
s_uploadBytes += up.currentSize;
}
break;
case UPLOAD_FILE_END:
if (s_upFile) {
s_upFile.close();
hal::storageUnlock();
}
break;
case UPLOAD_FILE_ABORTED:
if (s_upFile) {
s_upFile.close();
hal::storageUnlock();
}
break;
default:
break;
}
}
// ---------------------------------------------------------------- WiFi
static void handleWifiScan() {
String out = net.scanJson();
server.sendHeader("Cache-Control", "no-store");
server.send(200, "application/json", out);
}
static void handleWifiConnect() {
JsonDocument doc;
if (deserializeJson(doc, server.arg("plain")) != DeserializationError::Ok) {
server.send(400, "application/json", "{\"error\":\"bad json\"}");
return;
}
String ssid = doc["ssid"].as<String>();
String pwd = doc["pwd"].as<String>();
server.send(200, "application/json", "{\"ok\":true}");
delay(120);
net.connect(ssid, pwd);
}
// ---------------------------------------------------------------- 服务端地址
// 粗校验:只认 http(s)://host[:port][/path],host 不能为空。
// 返回空串表示合法并把尾斜杠规整掉;否则返回错误说明。
static String validateServerUrl(const String& in, String& norm) {
String u = in;
u.trim();
while (u.endsWith("/")) u.remove(u.length() - 1);
norm = u;
if (!u.startsWith("http://") && !u.startsWith("https://"))
return "必须以 http:// 或 https:// 开头";
int slash = u.indexOf('/', u.indexOf("://") + 3);
String hostPart = (slash < 0) ? u.substring(u.indexOf("://") + 3)
: u.substring(u.indexOf("://") + 3, slash);
if (hostPart.length() == 0) return "缺少主机名";
if (u.length() > 120) return "太长了";
return "";
}
// 保存前用 /healthz 试连一次;热点模式(无外网)下必然失败,前端提示即可
static void handleServerTest() {
JsonDocument req;
String url = server.arg("url");
if (url.length() == 0) {
if (deserializeJson(req, server.arg("plain")) != DeserializationError::Ok) {
server.send(400, "application/json", "{\"error\":\"bad json\"}");
return;
}
url = req["url"].as<String>();
}
JsonDocument doc;
String norm, err = validateServerUrl(url, norm);
if (err.length()) {
doc["ok"] = false;
doc["error"] = err;
sendJson(doc);
return;
}
if (!net.online()) {
doc["ok"] = false;
doc["error"] = "设备未联网,无法测试";
sendJson(doc);
return;
}
WiFiClientSecure tls; // https 时用 TLS(暂不校验证书链,与 PlatformService 一致)
WiFiClient plain;
HTTPClient http;
http.setConnectTimeout(4000);
http.setTimeout(4000);
String probe = norm + "/healthz";
const bool https = norm.startsWith("https");
if (https) tls.setInsecure();
bool begun = https ? http.begin(tls, probe) : http.begin(plain, probe);
int code = begun ? http.GET() : -1;
if (begun) http.end();
doc["ok"] = (code >= 200 && code < 300);
doc["code"] = code;
doc["url"] = norm;
if (code < 0) doc["error"] = "连接失败";
else if (code >= 400) doc["error"] = "服务端返回错误";
sendJson(doc);
LOG("WEB", "server test %s -> %d", probe.c_str(), code);
}
// ---------------------------------------------------------------- 维护
static void handleReset() {
settings.resetAll();
server.send(200, "application/json", "{\"ok\":true}");
delay(300);
ESP.restart();
}
static void handleReboot() {
server.send(200, "application/json", "{\"ok\":true}");
delay(300);
ESP.restart();
}
// 回滚到另一个槽。
// 以前这个接口叫 "boot/original",语义是"切回原厂 app0";2026-11 起 app0/app1
// 都是自研槽、互为回滚目标,所以语义变成"切到另一个槽(通常是上一个能跑的版本)"。
// 老路径保留,网页端旧缓存里的按钮点了也不会 404。
static void handleBootRollback() {
if (!svc::ota.otherSlotHasImage()) {
server.send(409, "application/json", "{\"error\":\"other slot has no image\"}");
return;
}
server.send(200, "application/json", "{\"ok\":true}");
delay(300);
svc::ota.rollback(); // 内部切槽 + 重启
}
// ---------------------------------------------------------------- 强制门户
// 手机系统连上一个新 WiFi 都会先请求一个固定探针,用来判断"这个网要不要登录"。
// 只要响应"不像正常联网",系统就会自己弹出登录窗并加载我们的配网页:
// iOS / macOS http://captive.apple.com/hotspot-detect.html (正常应回 "Success")
// Android http://connectivitycheck.gstatic.com/generate_204(正常应是 204 空)
// Windows http://www.msftconnecttest.com/connecttest.txt (正常应是 "Microsoft Connect Test")
// 所以这里一律 302 到门户首页。之前没有这一段,iPhone 连上热点只会在
// 设置里显示"无互联网连接",绝不会弹窗——必须手动敲 192.168.4.1。
static void captiveRedirect() {
IPAddress ip = WiFi.softAPIP();
if ((uint32_t)ip == 0) ip = WiFi.localIP(); // 配网宽限期内 AP 还开着,正常走上面
String url = String("http://") + ip.toString() + "/";
server.sendHeader("Cache-Control", "no-store, no-cache, must-revalidate");
server.sendHeader("Location", url, true);
// 附带一个自带跳转的极简页:个别客户端不认 302,但认 meta refresh
server.send(302, "text/html; charset=utf-8",
"<!doctype html><meta charset=utf-8>"
"<meta http-equiv=refresh content=\"0;url=" + url + "\">");
}
// ---------------------------------------------------------------- 注册
void WebPortal::begin() {
server.on("/", HTTP_GET, []() {
server.sendHeader("Cache-Control", "max-age=60");
server.send_P(200, "text/html; charset=utf-8", WEB_UI_HTML);
});
// 各系统的联网探针,全部导向门户首页
server.on("/hotspot-detect.html", captiveRedirect); // iOS / macOS
server.on("/library/test/success.html", captiveRedirect); // macOS 旧版
server.on("/generate_204", captiveRedirect); // Android
server.on("/gen_204", captiveRedirect);
server.on("/connecttest.txt", captiveRedirect); // Windows 10+
server.on("/ncsi.txt", captiveRedirect); // Windows 旧版
server.on("/redirect", captiveRedirect);
server.on("/canonical.html", captiveRedirect); // Firefox
server.on("/success.txt", captiveRedirect);
server.on("/api/status", HTTP_GET, handleStatus);
server.on("/api/settings", HTTP_GET, handleGetSettings);
server.on("/api/setting", HTTP_POST, handleSetSetting);
server.on("/api/files", HTTP_GET, handleFiles);
server.on("/api/download", HTTP_GET, handleDownload);
server.on("/api/delete", HTTP_POST, handleDelete);
server.on("/api/cd", HTTP_POST, handleSetDir);
server.on("/api/upload", HTTP_POST, handleUploadFinal, handleUploadChunk);
server.on("/api/wifi/scan", HTTP_GET, handleWifiScan);
server.on("/api/wifi", HTTP_POST, handleWifiConnect);
server.on("/api/server/test", HTTP_POST, handleServerTest);
server.on("/api/reset", HTTP_POST, handleReset);
server.on("/api/reboot", HTTP_POST, handleReboot);
server.on("/api/boot/original", HTTP_POST, handleBootRollback); // 旧名,语义见上
server.on("/api/boot/rollback", HTTP_POST, handleBootRollback);
server.onNotFound([]() {
// 热点模式下没匹配到的 GET 一律当成"手机在探网",送回门户首页。
// /api/ 要除外:那是网页自己在取数据,得让它看到真实的 404 而不是一张 HTML。
if (net.apUp() && server.method() == HTTP_GET
&& !String(server.uri()).startsWith("/api/")) {
captiveRedirect();
return;
}
server.send(404, "application/json", "{\"error\":\"not found\"}");
});
server.begin();
_started = true;
LOG("WEB", "http server on :80");
}
void WebPortal::loop() {
if (_started) server.handleClient();
}
} // namespace svc

View File

@ -0,0 +1,22 @@
#pragma once
// WebPortal.h —— 内置网页服务
//
// 手机/电脑访问 http://<设备IP> 或 http://nexbuddy.local 即可:
// 查看设备信息、修改全部设置、管理 TF 卡(浏览/上传/下载/删除)。
// 上传走 multipart 流式写入,不占内存;单次请求写卡期间 UI 会短暂卡顿(已接受)。
#include <Arduino.h>
namespace svc {
class WebPortal {
public:
void begin();
void loop();
private:
bool _started = false;
};
extern WebPortal webPortal;
} // namespace svc

View File

@ -0,0 +1,430 @@
#pragma once
// web_ui.h —— 设备内置网页(单页应用,无外部依赖)
// 文件名以 web_ 开头,是为了让字体子集脚本跳过它——
// 页面里的中文由浏览器自己渲染,不需要打进固件字体。
static const char WEB_UI_HTML[] PROGMEM = R"HTMLRAW(<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>nex_buddy</title>
<style>
:root{
--bg:#0a0c10; --card:#161a21; --card2:#1e242e; --line:#272e3a;
--tx:#eef1f6; --dim:#8b94a4; --ac:#ff7a45; --ok:#4dd6a8; --err:#ff5b6e;
}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
body{margin:0;background:var(--bg);color:var(--tx);
font:15px/1.6 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;
padding:20px 16px 60px}
.wrap{max-width:760px;margin:0 auto}
header{display:flex;align-items:center;gap:12px;margin-bottom:22px}
.logo{width:44px;height:44px;border-radius:50%;
background:radial-gradient(circle at 32% 28%,var(--ac),#a83b12);
box-shadow:0 0 24px rgba(255,122,69,.35);flex:none}
h1{font-size:19px;margin:0;font-weight:600;letter-spacing:.3px}
.sub{color:var(--dim);font-size:12.5px}
.tabs{display:flex;gap:6px;background:var(--card);padding:5px;border-radius:14px;margin-bottom:18px}
.tabs button{flex:1;border:0;background:transparent;color:var(--dim);padding:10px;
border-radius:10px;font-size:14.5px;font-family:inherit;cursor:pointer;transition:.18s}
.tabs button.on{background:var(--card2);color:var(--tx);box-shadow:0 2px 10px rgba(0,0,0,.3)}
.card{background:var(--card);border-radius:18px;padding:16px 18px;margin-bottom:14px}
.card h2{font-size:13px;color:var(--dim);margin:0 0 12px;font-weight:500;letter-spacing:.6px}
.kv{display:flex;justify-content:space-between;padding:9px 0;border-bottom:1px solid var(--line)}
.kv:last-child{border-bottom:0}
.kv .k{color:var(--dim)}
.kv .v{font-variant-numeric:tabular-nums;max-width:62%;text-align:right;word-break:break-all}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.stat{background:var(--card2);border-radius:14px;padding:14px}
.stat .n{font-size:24px;font-weight:600;font-variant-numeric:tabular-nums}
.stat .l{font-size:12px;color:var(--dim);margin-top:2px}
.row{display:flex;align-items:center;justify-content:space-between;gap:14px;
padding:12px 0;border-bottom:1px solid var(--line)}
.row:last-child{border-bottom:0}
.row .lbl{flex:1;min-width:0}
.row .lbl small{display:block;color:var(--dim);font-size:12px;margin-top:2px}
input[type=range]{width:130px;accent-color:var(--ac);flex:none}
input[type=text],input[type=password],select{
background:var(--card2);border:1px solid var(--line);color:var(--tx);
padding:8px 11px;border-radius:9px;font-family:inherit;font-size:14px;outline:none;max-width:200px}
input[type=text]:focus,input[type=password]:focus,select:focus{border-color:var(--ac)}
.sw{width:48px;height:28px;border-radius:14px;background:var(--card2);position:relative;
cursor:pointer;transition:.2s;flex:none;border:1px solid var(--line)}
.sw::after{content:'';position:absolute;top:3px;left:3px;width:20px;height:20px;
border-radius:50%;background:var(--dim);transition:.2s}
.sw.on{background:var(--ac);border-color:var(--ac)}
.sw.on::after{left:23px;background:#fff}
.btn{background:var(--card2);border:1px solid var(--line);color:var(--tx);
padding:9px 15px;border-radius:10px;font-family:inherit;font-size:14px;cursor:pointer;transition:.15s}
.btn:hover{border-color:var(--ac)}
.btn.primary{background:var(--ac);border-color:var(--ac);color:#12151a;font-weight:600}
.btn.danger{color:var(--err)}
.btn.block{display:block;width:100%;padding:15px;font-size:16px;border-radius:12px}
.btn:disabled{opacity:.45;cursor:not-allowed}
.toast{position:fixed;left:50%;bottom:28px;transform:translate(-50%,20px);opacity:0;
background:var(--card2);border:1px solid var(--line);padding:11px 20px;border-radius:12px;
font-size:14px;transition:.25s;pointer-events:none;z-index:99;max-width:88vw}
.toast.on{opacity:1;transform:translate(-50%,0)}
.modal{position:fixed;inset:0;background:rgba(4,6,10,.62);display:none;align-items:center;
justify-content:center;padding:22px;z-index:200}
.modal.on{display:flex}
.modal .box{background:var(--card);border:1px solid var(--line);border-radius:20px;
padding:20px 20px 16px;width:100%;max-width:330px;box-shadow:0 18px 50px rgba(0,0,0,.55)}
.modal h3{margin:0 0 10px;font-size:17px;font-weight:600}
.modal .msg{color:var(--dim);font-size:13.5px;line-height:1.75;word-break:break-word}
.modal .msg b{color:var(--tx);font-weight:600}
.modal .acts{display:flex;gap:8px;justify-content:flex-end;margin-top:18px}
.hide{display:none!important}
.tag{display:inline-block;font-size:11.5px;padding:2px 8px;border-radius:20px;
background:rgba(77,214,168,.14);color:var(--ok)}
.tag.off{background:rgba(139,148,164,.14);color:var(--dim)}
.note{color:var(--dim);font-size:12.5px;line-height:1.7;margin-top:10px}
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="logo"></div>
<div style="flex:1">
<h1>nex_buddy <span id="ver" style="font-size:12px;color:var(--dim);font-weight:400"></span></h1>
<div class="sub"><span id="netmode">连接中…</span></div>
</div>
<span class="tag off" id="onlinetag">离线</span>
</header>
<div class="tabs">
<button class="on" data-tab="home">概览</button>
<button data-tab="set">设置</button>
</div>
<!-- 概览 -->
<div id="tab-home">
<div class="card">
<h2>状态</h2>
<div class="grid">
<div class="stat"><div class="n" id="s-bri">—</div><div class="l">电量</div></div>
<div class="stat"><div class="n" id="s-temp">—</div><div class="l">温度</div></div>
<div class="stat"><div class="n" id="s-sd">—</div><div class="l">TF 卡已用</div></div>
<div class="stat"><div class="n" id="s-up">—</div><div class="l">运行时长</div></div>
</div>
</div>
<div class="card">
<h2>网络</h2>
<div class="kv"><span class="k">WiFi</span><span class="v" id="n-ssid">—</span></div>
<div class="kv"><span class="k">IP 地址</span><span class="v" id="n-ip">—</span></div>
<div class="kv"><span class="k">信号</span><span class="v" id="n-rssi">—</span></div>
<div class="kv"><span class="k">访问地址</span><span class="v" id="n-url">—</span></div>
</div>
<div class="card">
<h2>配网</h2>
<div class="row">
<div class="lbl">更换 WiFi<small>选择后输入密码即可切换</small></div>
<select id="wifi-list"><option>扫描中…</option></select>
</div>
<div class="row">
<div class="lbl">密码</div>
<input type="password" id="wifi-pwd" placeholder="WiFi 密码">
</div>
<div style="display:flex;gap:8px;margin-top:12px">
<button class="btn primary" id="btn-join" onclick="joinWifi()">连接</button>
<button class="btn" onclick="scanWifi()">重新扫描</button>
</div>
<div class="note">连不上时设备会自动开热点 <b>nex_buddy</b>,密码 <b>12345678</b>,连上后访问 192.168.4.1。</div>
</div>
<div class="card">
<h2>服务端</h2>
<!-- 默认只读展示,点「修改」才展开输入框:地址是关键配置,
常驻输入框容易让人误以为要填什么,也容易误触清空 -->
<div id="srv-view">
<div class="kv"><span class="k">服务端地址</span><span class="v" id="srv-show">—</span></div>
<div style="display:flex;gap:8px;margin-top:12px">
<button class="btn primary" onclick="editServer()">修改</button>
<button class="btn" onclick="testServer()">测试连通</button>
</div>
</div>
<div id="srv-edit" class="hide">
<div class="row">
<div class="lbl">服务端地址<small>平台服务的根地址,保存后立即生效</small></div>
<input type="text" id="srv-url" placeholder="http://host:port" style="max-width:240px">
</div>
<div style="display:flex;gap:8px;margin-top:12px">
<button class="btn primary" onclick="saveServer()">保存</button>
<button class="btn" onclick="testServer()">测试连通</button>
<button class="btn" onclick="resetServer()">恢复默认</button>
<button class="btn" onclick="cancelServer()">取消</button>
</div>
</div>
<div class="note" id="srv-note"></div>
</div>
<div class="card">
<h2>设备</h2>
<div class="kv"><span class="k">固件版本</span><span class="v" id="d-ver">—</span></div>
<div class="kv"><span class="k">主控</span><span class="v">ESP32-S3R8 · 16MB/8MB</span></div>
<div class="kv"><span class="k">启动分区</span><span class="v" id="d-part">—</span></div>
<div class="kv"><span class="k">当前应用</span><span class="v" id="d-app">—</span></div>
<button class="btn primary block" style="margin-top:14px" onclick="rebootDevice()">完成重启</button>
</div>
</div>
<!-- 设置 -->
<div id="tab-set" class="hide"></div>
</div>
<div class="toast" id="toast"></div>
<div class="modal" id="modal">
<div class="box">
<h3 id="m-title"></h3>
<div class="msg" id="m-body"></div>
<div class="acts" id="m-acts"></div>
</div>
</div>
<script>
const $ = s => document.querySelector(s);
const el = (t,c,h)=>{const e=document.createElement(t); if(c)e.className=c; if(h!=null)e.innerHTML=h; return e;};
// ---------- 弹窗 ----------
// acts: [{l:'按钮文字', p:true 主按钮, f:点击回调}]
function popup(title, body, acts){
$('#m-title').textContent = title;
$('#m-body').innerHTML = body;
const box = $('#m-acts'); box.innerHTML = '';
(acts && acts.length ? acts : [{l:'知道了'}]).forEach(a=>{
const b = el('button', 'btn' + (a.p ? ' primary' : ''), a.l);
b.onclick = ()=>{ closePopup(); if(a.f) a.f(); };
box.appendChild(b);
});
$('#modal').classList.add('on');
}
function closePopup(){ $('#modal').classList.remove('on'); }
function toast(msg, ms=1800){
const t = $('#toast'); t.textContent = msg; t.classList.add('on');
clearTimeout(t._h); t._h = setTimeout(()=>t.classList.remove('on'), ms);
}
async function api(p, opt){
const r = await fetch(p, opt);
const ct = r.headers.get('content-type')||'';
return ct.includes('json') ? r.json() : r.text();
}
// ---------- tab ----------
document.querySelectorAll('.tabs button').forEach(b=>{
b.onclick = ()=>{
document.querySelectorAll('.tabs button').forEach(x=>x.classList.remove('on'));
b.classList.add('on');
['home','set'].forEach(t=>$('#tab-'+t).classList.toggle('hide', t!==b.dataset.tab));
if(b.dataset.tab==='set') loadSettings();
};
});
// ---------- 概览 ----------
function fmtUp(s){
const d=Math.floor(s/86400), h=Math.floor(s%86400/3600), m=Math.floor(s%3600/60);
return d? d+'天'+h+'h' : (h? h+'h'+m+'m' : m+'分');
}
async function loadStatus(){
try{
const d = await api('/api/status');
$('#ver').textContent = 'v'+d.version;
$('#netmode').textContent = d.mode==='ap' ? '热点模式 · 等待配网' : (d.online? '已连接 '+d.ssid : '未联网');
$('#onlinetag').textContent = d.online? '在线':'离线';
$('#onlinetag').className = 'tag'+(d.online?'':' off');
$('#s-bri').textContent = d.battery.ext ? 'USB' : d.battery.pct+'%';
$('#s-temp').textContent = d.weather.valid? d.weather.temp+'°' : '—';
const used = (d.sd.used/1048576).toFixed(0), tot=(d.sd.total/1048576).toFixed(0);
$('#s-sd').textContent = d.sd.ready? used+'M' : '无卡';
$('#s-up').textContent = fmtUp(d.uptime);
$('#n-ssid').textContent = d.ssid||'—';
$('#n-ip').textContent = d.ip||'—';
$('#n-rssi').textContent = d.rssi? d.rssi+' dBm':'—';
$('#n-url').textContent = 'http://'+d.ip;
fillServer(d);
$('#d-ver').textContent = d.version;
$('#d-part').textContent = d.partition;
$('#d-app').textContent = d.app;
}catch(e){ $('#onlinetag').textContent='失联'; }
}
// 扫描一次要 3~4 秒,而设备端 WebServer 是单线程的:和别的请求撞上会被顶掉,
// 所以失败重试一次,而不是直接报"扫描失败"
async function scanWifi(tryN){
tryN = tryN || 0;
const sel = $('#wifi-list'); sel.innerHTML = '<option>扫描中…</option>';
try{
const list = await api('/api/wifi/scan');
sel.innerHTML='';
if(!list.length) sel.innerHTML='<option value="">未发现网络</option>';
list.forEach(w=>{
const o = el('option'); o.value=w.ssid;
o.textContent = w.ssid + ' (' + w.rssi + 'dBm)' + (w.enc?' 🔒':'');
sel.appendChild(o);
});
}catch(e){
if(tryN < 1){ setTimeout(()=>scanWifi(tryN+1), 900); }
else { sel.innerHTML='<option value="">扫描失败,点「重新扫描」</option>'; }
}
}
// 提交后轮询 /api/status,等设备真的连上(配网成功后热点会保留 60 秒,
// 手机还挂在热点上时能读到新 IP,所以这里能拿到结果)
async function waitOnline(ssid, tries){
for(let i=0;i<tries;i++){
await new Promise(r=>setTimeout(r,1200));
try{
const d = await api('/api/status');
if(d.online && (!ssid || d.ssid===ssid)) return d;
}catch(e){ /* 设备切网瞬间可能短暂失联,继续等 */ }
}
return null;
}
async function joinWifi(){
const ssid = $('#wifi-list').value, pwd = $('#wifi-pwd').value;
if(!ssid){ popup('还没选 WiFi', '先在上面的列表里选一个网络,再点连接。'); return; }
const btn = $('#btn-join');
btn.disabled = true; btn.textContent = '连接中…';
popup('正在连接', '设备正在接入 <b>'+ssid+'</b>…<br>请让手机留在 <b>nex_buddy</b> 热点上,最多等 25 秒。');
try{
await api('/api/wifi', {method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({ssid, pwd})});
}catch(e){ /* 设备切走时这次请求可能没回应,后面靠轮询判断 */ }
const d = await waitOnline(ssid, 20);
btn.disabled = false; btn.textContent = '连接';
if(d){
popup('已连接', '设备已接入 <b>'+ssid+'</b>。<br>新地址:<b>http://'+d.ip+'</b><br><span style="color:var(--dim)">热点将在 60 秒后关闭,之后请用这个地址访问。</span>',
[{l:'打开', p:1, f:()=>window.open('http://'+d.ip)},{l:'关闭'}]);
loadStatus();
}else{
popup('连接失败', '设备没能连上 <b>'+ssid+'</b>。<br>常见原因:密码不对、路由器只开 5GHz、或这个网络需要网页认证。<br><span style="color:var(--dim)">热点会在约 20 秒后重新出现,可以再试一次。</span>',
[{l:'重新扫描', p:1, f:scanWifi},{l:'关闭'}]);
loadStatus();
}
}
// ---------- 服务端地址 ----------
// 默认只读,点「修改」进入编辑;保存/取消后回到只读
function fillServer(d){
const s = d && d.server != null ? d.server : '';
$('#srv-show').textContent = s || '—';
// 编辑态不要碰输入框:状态 5 秒轮询一次,无条件回填会把用户
// 正在输入的地址冲回旧值——就是“改完一抬头地址又变回去了”的那个 bug
if ($('#srv-edit').classList.contains('hide')) $('#srv-url').value = s;
}
function editServer(){ $('#srv-view').classList.add('hide'); $('#srv-edit').classList.remove('hide'); }
function cancelServer(){
$('#srv-url').value = $('#srv-show').textContent === '—' ? '' : $('#srv-show').textContent;
$('#srv-edit').classList.add('hide'); $('#srv-view').classList.remove('hide');
}
async function saveServer(){
const u = $('#srv-url').value.trim();
if(!/^https?:\/\/.+/.test(u)){ toast('地址要以 http:// 或 https:// 开头'); return false; }
const ok = await setVal('net.server', u.replace(/\/+$/,''), true);
if(!ok) return false;
$('#srv-show').textContent = u.replace(/\/+$/,'');
$('#srv-edit').classList.add('hide'); $('#srv-view').classList.remove('hide');
popup('服务端地址已保存', '设备会立即改用新地址并重新核对绑定状态。<br>建议重启一次,让所有服务用干净的状态重连。',
[{l:'立即重启', p:1, f:rebootDevice},{l:'稍后'}]);
return true;
}
async function testServer(){
const u = $('#srv-url').value.trim();
if(!u){ toast('请先填写地址'); return; }
$('#srv-note').textContent = '正在测试连通…';
try{
const r = await api('/api/server/test', {method:'POST',
headers:{'Content-Type':'application/json'}, body: JSON.stringify({url:u})});
$('#srv-note').textContent = r.ok ? ('连通正常(HTTP '+r.code+')') : ('测试失败:'+(r.error||'HTTP '+r.code));
}catch(e){ $('#srv-note').textContent = '测试失败:请求出错'; }
}
async function resetServer(){
$('#srv-url').value = 'http://192.168.2.147:8100';
await saveServer();
}
// ---------- 重启 ----------
// 不用原生 confirm():手机连热点弹出的系统配网窗口(captive portal webview)
// 会静默屏蔽 alert/confirm,按钮点了等于没点。确认框一律走自己的 popup。
function askConfirm(title, msg, onOk){
popup(title, msg, [{l:'确定', p:1, f:onOk}, {l:'取消'}]);
}
function rebootDevice(){
askConfirm('完成重启', '确定现在重启设备?重启后用原地址重新打开本页。', ()=>{
try{ api('/api/reboot',{method:'POST'}); }catch(e){ /* 设备重启前可能来不及回应 */ }
popup('正在重启', '设备马上重启,大约 20 秒后恢复。', [{l:'知道了'}]);
});
}
// ---------- 设置 ----------
let groups = {};
function renderSetting(it){
const row = el('div','row');
const lbl = el('div','lbl'); lbl.textContent = it.l;
if(it.u) { const s=el('small'); s.textContent='单位 '+it.u; lbl.appendChild(s); }
row.appendChild(lbl);
if(it.t===1){ // bool
const sw = el('div','sw'+(it.v?' on':''));
sw.onclick = async()=>{ const nv = it.v?0:1; it.v=nv; sw.classList.toggle('on',!!nv);
await setVal(it.k, nv); };
row.appendChild(sw);
} else if(it.t===2){ // enum
const sel = el('select');
(it.opt||'').split('|').forEach((name,i)=>{
const o=el('option',null,name); o.value=i; if(i===it.v)o.selected=true; sel.appendChild(o);
});
sel.onchange = ()=> setVal(it.k, +sel.value);
row.appendChild(sel);
} else if(it.t===0){ // int
const box = el('div'); box.style.display='flex'; box.style.alignItems='center'; box.style.gap='10px';
const val = el('span',null,it.v+(it.u||'')); val.style.color='var(--dim)'; val.style.fontSize='13px';
val.style.minWidth='46px'; val.style.textAlign='right';
const rg = el('input'); rg.type='range'; rg.min=it.min; rg.max=it.max; rg.step=it.step||1; rg.value=it.v;
rg.oninput = ()=>{ val.textContent = rg.value+(it.u||''); };
rg.onchange = ()=> setVal(it.k, +rg.value);
box.appendChild(val); box.appendChild(rg); row.appendChild(box);
} else { // text
const inp = el('input'); inp.type='text'; inp.value = it.v||''; inp.placeholder='未设置';
inp.onchange = ()=> setVal(it.k, inp.value, true);
row.appendChild(inp);
}
return row;
}
async function setVal(k, v, isText){
try{
const r = await api('/api/setting', {method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({key:k, value:v})});
if(!r || !r.ok){ toast('保存失败'); return false; }
toast('已保存');
if(k==='sys.accent'||k==='sys.bright') setTimeout(loadStatus, 300);
return true;
}catch(e){ toast('保存失败'); return false; }
}
async function loadSettings(){
const items = await api('/api/settings');
const host = $('#tab-set'); host.innerHTML=''; groups={};
items.forEach(it=>{ (groups[it.g] = groups[it.g]||[]).push(it); });
Object.keys(groups).forEach(g=>{
const c = el('div','card'); c.appendChild(el('h2',null,g));
groups[g].forEach(it=> c.appendChild(renderSetting(it)));
host.appendChild(c);
});
const c = el('div','card');
c.appendChild(el('h2',null,'维护'));
const b1 = el('button','btn','恢复默认设置');
b1.onclick = ()=> askConfirm('恢复默认设置', '确定恢复全部设置为默认值?', async()=>{
await api('/api/reset', {method:'POST'}); toast('已恢复'); loadSettings(); loadStatus(); });
const b2 = el('button','btn','重启设备');
b2.style.marginLeft='8px';
b2.onclick = ()=> askConfirm('重启设备', '确定重启?', ()=>{
try{ api('/api/reboot',{method:'POST'}); }catch(e){}
popup('正在重启', '设备马上重启,大约 20 秒后恢复。', [{l:'知道了'}]); });
c.appendChild(b1); c.appendChild(b2);
host.appendChild(c);
}
// ---------- 启动 ----------
// 顺序执行:先状态后扫描,两个请求并发会互相顶掉(设备端单线程)
loadStatus().then(()=>scanWifi());
setInterval(loadStatus, 5000);
</script>
</body>
</html>)HTMLRAW";

View File

@ -0,0 +1,136 @@
#include "BindScreen.h"
#include "Theme.h"
#include "Widgets.h"
#include "../services/PlatformService.h"
#include "../config/AppConfig.h"
#include <Arduino.h>
namespace ui {
BindScreen bindScreen;
void BindScreen::build(lv_obj_t* parent) {
_box = lv_obj_create(parent);
lv_obj_set_size(_box, SCREEN_W, SCREEN_H);
lv_obj_center(_box);
lv_obj_set_style_bg_color(_box, theme::bg(), 0);
lv_obj_set_style_bg_opa(_box, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_box, 0, 0);
lv_obj_set_style_radius(_box, 0, 0);
lv_obj_set_style_pad_all(_box, 0, 0);
lv_obj_clear_flag(_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_box, LV_OBJ_FLAG_CLICKABLE);
// 环同时是倒计时:配对码剩余时间越少,环越短
_arc = arc(_box, 168, 3, theme::accent());
lv_obj_set_style_arc_opa(_arc, LV_OPA_20, LV_PART_MAIN);
_title = label(_box, "绑定设备", FONT_TEXT, theme::textDim());
lv_obj_align(_title, LV_ALIGN_CENTER, 0, -118);
// 六位码是这一屏唯一的主角,字号尽量大:隔一米也能读出来。
// 码下面**只留一行**——平时是倒计时,出错时换成原因。
// 以前这里还压着「192.168.x · 设备 BD44」「点击换码」「在网页端输入此码」
// 三行小字,整屏像张说明书;绑定页只有一件事要传达,就是这六位数。
_code = label(_box, "······", FONT_NUM_L, theme::accent());
lv_obj_set_style_text_letter_space(_code, 6, 0);
lv_obj_align(_code, LV_ALIGN_CENTER, 0, -6);
_ttl = label(_box, "", FONT_TEXT, theme::textDim());
lv_obj_set_width(_ttl, 288);
lv_label_set_long_mode(_ttl, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(_ttl, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(_ttl, LV_ALIGN_CENTER, 0, 66);
lv_obj_add_event_cb(_box, [](lv_event_t* e) {
// 点一下换一张码:码过期或用户嫌看不清时的手动兜底
if (svc::platform.pairState() == svc::PairState::Bound) return;
svc::platform.startPairing(true);
}, LV_EVENT_CLICKED, this);
}
void BindScreen::show() {
if (!_box) return;
_on = true;
_okAt = 0;
_shownCode = "";
_ttlTotal = 600;
lv_obj_clear_flag(_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_box);
lv_obj_set_style_opa(_box, LV_OPA_TRANSP, 0);
lv_obj_fade_in(_box, 160, 0);
// 已绑定就不该走到这里;否则立刻取码
if (!svc::platform.bound()) svc::platform.startPairing();
refresh();
}
void BindScreen::hide() {
if (!_box) return;
_on = false;
lv_obj_add_flag(_box, LV_OBJ_FLAG_HIDDEN);
}
void BindScreen::loop() {
if (!_on) return;
// 绑定成功:先让"绑定成功"停一下,再收起,避免用户没看到就跳走
if (svc::platform.bound()) {
if (!_okAt) _okAt = millis();
if (millis() - _okAt > 1100) {
hide();
toast(lv_layer_top(), "已绑定,资料已同步", 1600);
return;
}
}
if (millis() - _lastUi < 200) return;
_lastUi = millis();
refresh();
}
void BindScreen::refresh() {
const auto st = svc::platform.pairState();
String code = svc::platform.pairCode();
if (code.length() == 6) {
if (code != _shownCode) {
_shownCode = code;
_ttlTotal = svc::platform.pairLeftSec();
if (_ttlTotal < 30) _ttlTotal = 600;
}
char buf[12];
snprintf(buf, sizeof(buf), "%c%c%c %c%c%c", code[0], code[1], code[2],
code[3], code[4], code[5]);
lv_label_set_text(_code, buf);
lv_obj_set_style_text_color(_code, theme::accent(), 0);
} else {
_shownCode = "";
lv_label_set_text(_code, "······");
lv_obj_set_style_text_color(_code, theme::textDim(), 0);
}
uint32_t left = svc::platform.pairLeftSec();
if (st == svc::PairState::Bound) {
lv_label_set_text(_ttl, "资料同步中");
arcSetPct(_arc, 100);
arcSetColor(_arc, theme::accent());
} else if (st == svc::PairState::Failed) {
// 只有真出事才出字:原因直接写在这一行(码位此时是空的)
lv_label_set_text(_ttl, svc::platform.pairHint());
arcSetPct(_arc, 0);
arcSetColor(_arc, theme::accent());
} else if (left > 0) {
lv_label_set_text_fmt(_ttl, "剩 %u:%02u", left / 60, left % 60);
int pct = _ttlTotal ? (int)(left * 100UL / _ttlTotal) : 0;
arcSetPct(_arc, pct);
arcSetColor(_arc, theme::accent());
} else {
lv_label_set_text(_ttl, "正在取码…");
arcSetPct(_arc, 0);
arcSetColor(_arc, theme::accent());
}
}
} // namespace ui

View File

@ -0,0 +1,45 @@
#pragma once
// BindScreen.h —— 设备绑定页(全屏,盖在整个界面之上)
//
// 流程(与 01-总体设计.md 2.1 一致):
// 进入需要账号的功能 → 未绑定 → 本页升起
// → 服务端取 6 位码上屏 → 用户手机/电脑打开网页输入
// → 本页每 5 秒问一次状态 → 已确认则换 token 存 NVS → 自动收起
//
// 交互:点击 = 换一张码(当前码过期/看不清时用);下滑 = 先不绑。
//
// 版式(0.1.8 起):标题 + 大号六位码 + 一行状态(倒计时 / 出错原因)。
// 码下面曾经压着「服务端地址 · 设备号」「剩 x:xx · 点击换码」「在网页端输入此码」
// 三行小字——同一屏五个信息,扫码时反而找不到那六位数。现在没有常驻提示:
// 只有一种情况会出字,就是取码/绑定出错(见 refresh)。
#include <Arduino.h>
#include <lvgl.h>
namespace ui {
class BindScreen {
public:
void build(lv_obj_t* parent);
void show();
void hide();
bool visible() const { return _on; }
void loop(); // 每帧驱动:轮询状态、倒计时、成功自动收起
private:
void refresh();
lv_obj_t* _box = nullptr;
lv_obj_t* _arc = nullptr;
lv_obj_t* _title = nullptr;
lv_obj_t* _code = nullptr;
lv_obj_t* _ttl = nullptr; // 唯一的一行字:倒计时,出错时换成原因
bool _on = false;
uint32_t _ttlTotal = 600;
uint32_t _lastUi = 0;
uint32_t _okAt = 0;
String _shownCode;
};
extern BindScreen bindScreen;
} // namespace ui

230
src/ui/Launcher.cpp 100644
View File

@ -0,0 +1,230 @@
#include "Launcher.h"
#include "Theme.h"
#include "Widgets.h"
#include "../assets/icons.h"
#include "../core/AppManager.h"
#include "../core/Log.h"
#include "../hal/Haptic.h"
#include "../config/AppConfig.h"
#include <math.h>
namespace ui {
// ---------------- 几何参数(全部以屏幕中心为原点) ----------------
static const int ARC_SIZE = 358; // 扇区所在圆的直径
static const int SECTOR_W = 115; // 扇区径向厚度
static const int SECTOR_GAP = 1; // 段间缝隙(度)
static const int ICON_R = 124; // 图标中心半径
static const int ICON_SIZE = 44; // 图标资源原始尺寸
static const int HUB_R = 56; // 中心圆盘半径
// 注意:不要用 lv_obj_set_style_transform_zoom 缩放图标。本工程的图标是
// LV_IMG_CF_TRUE_COLOR_ALPHA,缩放这条路径在 LVGL 8.4 上会静默不渲染(图标直接消失)。
// 需要多大就按多大生成位图,1:1 显示,动画只做透明度。
static inline int polarX(float deg, int r) { return SCREEN_R + (int)lroundf(r * cosf(deg * 0.01745329f)); }
static inline int polarY(float deg, int r) { return SCREEN_R + (int)lroundf(r * sinf(deg * 0.01745329f)); }
// ============================ 构建 ============================
void Launcher::build(lv_obj_t* parent, PickCb onPick) {
_pick = onPick;
_root = lv_obj_create(parent);
lv_obj_set_size(_root, SCREEN_W, SCREEN_H);
lv_obj_center(_root);
lv_obj_set_style_bg_color(_root, theme::bg(), 0);
lv_obj_set_style_bg_opa(_root, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_root, 0, 0);
lv_obj_set_style_pad_all(_root, 0, 0);
lv_obj_set_style_radius(_root, 0, 0);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_root, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_flag(_root, LV_OBJ_FLAG_HIDDEN);
_n = appMgr.count();
if (_n > 8) _n = 8;
const float step = 360.0f / (float)_n;
// arc 的 0° 默认在 3 点方向;旋转 270° 后 0° 到 12 点。
// 再减去半个步长,让第 0 段以正上方为中心,且所有段都落在 [0,360) 内不跨零。
const int rot = 270 - (int)(step * 0.5f);
for (int i = 0; i < _n; i++) {
float a0 = step * (float)i + SECTOR_GAP * 0.5f;
float a1 = step * (float)(i + 1) - SECTOR_GAP * 0.5f;
lv_obj_t* seg = lv_arc_create(_root);
lv_obj_set_size(seg, ARC_SIZE, ARC_SIZE);
lv_obj_center(seg);
lv_obj_clear_flag(seg, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
lv_obj_remove_style(seg, nullptr, LV_PART_KNOB);
lv_arc_set_rotation(seg, (uint16_t)rot);
lv_arc_set_bg_angles(seg, (uint16_t)lroundf(a0), (uint16_t)lroundf(a1));
lv_arc_set_angles(seg, 0, 0); // 指示弧不用
lv_obj_set_style_bg_opa(seg, LV_OPA_TRANSP, LV_PART_MAIN);
lv_obj_set_style_border_width(seg, 0, LV_PART_MAIN);
lv_obj_set_style_arc_width(seg, SECTOR_W, LV_PART_MAIN);
lv_obj_set_style_arc_rounded(seg, false, LV_PART_MAIN);
lv_obj_set_style_arc_color(seg, theme::sector(), LV_PART_MAIN);
lv_obj_set_style_arc_opa(seg, LV_OPA_COVER, LV_PART_MAIN);
lv_obj_set_style_arc_opa(seg, LV_OPA_TRANSP, LV_PART_INDICATOR);
_seg[i] = seg;
// 只放图标不放文字:图标本身语义足够清楚,扇区里少一行字反而干净,
// 当前选中的名字由中心圆盘承载(见 _hubName)。
const AppMeta& m = appMgr.at(i)->meta();
float deg = -90.0f + step * (float)i;
lv_obj_t* ico = lv_img_create(_root);
lv_img_set_src(ico, m.icon ? m.icon : &icon_clock);
lv_obj_set_style_img_recolor(ico, theme::textDim(), 0);
lv_obj_set_style_img_recolor_opa(ico, LV_OPA_COVER, 0);
lv_obj_align(ico, LV_ALIGN_CENTER, polarX(deg, ICON_R) - SCREEN_R,
polarY(deg, ICON_R) - SCREEN_R);
lv_obj_clear_flag(ico, LV_OBJ_FLAG_CLICKABLE);
_ico[i] = ico;
}
// ---------------- 中心圆盘 ----------------
_hub = lv_obj_create(_root);
lv_obj_set_size(_hub, HUB_R * 2, HUB_R * 2);
lv_obj_center(_hub);
lv_obj_set_style_radius(_hub, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(_hub, theme::surfaceHi(), 0);
lv_obj_set_style_bg_opa(_hub, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_hub, 0, 0);
lv_obj_set_style_border_color(_hub, theme::accent(), 0);
lv_obj_set_style_border_opa(_hub, LV_OPA_20, 0);
lv_obj_set_style_pad_all(_hub, 0, 0);
lv_obj_clear_flag(_hub, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
_hubDot = lv_obj_create(_hub);
lv_obj_set_size(_hubDot, 6, 6);
lv_obj_align(_hubDot, LV_ALIGN_TOP_MID, 0, 18);
lv_obj_set_style_radius(_hubDot, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(_hubDot, theme::accent(), 0);
lv_obj_set_style_border_width(_hubDot, 0, 0);
lv_obj_clear_flag(_hubDot, LV_OBJ_FLAG_SCROLLABLE);
_hubName = label(_hub, "", FONT_TITLE, theme::text());
lv_obj_align(_hubName, LV_ALIGN_CENTER, 0, -4);
_hubSub = label(_hub, "", FONT_TEXT, theme::textDim());
lv_obj_align(_hubSub, LV_ALIGN_CENTER, 0, 26);
// 整层接管点击:arc 的命中区是外接矩形,会吞掉触摸,所以扇区一律不响应事件。
lv_obj_add_event_cb(_root, [](lv_event_t* e) {
Launcher* self = (Launcher*)lv_event_get_user_data(e);
lv_indev_t* indev = lv_indev_get_act();
if (!indev) return;
lv_point_t p;
lv_indev_get_point(indev, &p);
int dx = p.x - SCREEN_R, dy = p.y - SCREEN_R;
float r = sqrtf((float)dx * dx + (float)dy * dy);
if (r > SCREEN_R + 4) return; // 屏幕圆角外的无效区
if (r <= HUB_R - 4) { // 中心:确认当前选中
self->enter(self->_sel);
return;
}
// 按角度定位扇区:0° 指正上方,顺时针增大
float rel = atan2f((float)dy, (float)dx) * 57.29578f + 90.0f;
if (rel < 0) rel += 360.0f;
float step = 360.0f / (float)self->_n;
int idx = ((int)((rel + step * 0.5f) / step)) % self->_n;
if (idx != self->_sel) {
self->select(idx);
}
self->enter(idx);
}, LV_EVENT_CLICKED, this);
}
// ============================ 选中态 ============================
void Launcher::refresh(bool animate) {
(void)animate;
for (int i = 0; i < _n; i++) {
bool on = (i == _sel);
lv_obj_t* seg = _seg[i];
lv_obj_t* ico = _ico[i];
if (!seg) continue;
// 选中段:强调色扫一层底色。混合比例要够高(112/255≈44%),
// 低于这个数橙色会被深灰拉成"土褐色",看着像是脏了而不是被选中。
lv_color_t segc = on ? lv_color_mix(theme::accent(), theme::sector(), 112)
: theme::sector();
lv_obj_set_style_arc_color(seg, segc, LV_PART_MAIN);
lv_obj_set_style_img_recolor(ico, on ? theme::accent() : theme::textDim(), 0);
}
if (_n > 0 && _hubName) {
const AppMeta& m = appMgr.at(_sel)->meta();
lv_label_set_text(_hubName, m.name);
char buf[16];
snprintf(buf, sizeof(buf), "%d / %d", _sel + 1, _n);
lv_label_set_text(_hubSub, buf);
// 全站只用主色:每个应用一个色会让一级菜单看起来像七套设计
lv_obj_set_style_bg_color(_hubDot, theme::accent(), 0);
lv_obj_set_style_border_color(_hub, theme::accent(), 0);
}
}
void Launcher::select(int idx, bool haptic) {
if (_n <= 0) return;
idx = (idx % _n + _n) % _n;
if (idx == _sel) return;
_sel = idx;
refresh(true);
if (haptic) hal::hapticTick();
}
void Launcher::move(int32_t diff) {
if (diff == 0) return;
select(_sel + (int)diff);
}
void Launcher::enter(int idx) {
if (idx < 0 || idx >= _n) return;
App* a = appMgr.at(idx);
if (!a) return;
hal::hapticClick();
if (_pick) _pick(a);
}
// ============================ 显隐 ============================
void Launcher::open(int startIdx) {
if (_on) return;
_on = true;
_sel = (startIdx >= 0 && startIdx < _n) ? startIdx : 0;
refresh(false);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_root);
// 整层淡入,图标依次错开浮现,像"转起来"
lv_obj_set_style_opa(_root, LV_OPA_TRANSP, 0);
lv_obj_fade_in(_root, 150, 0);
for (int i = 0; i < _n; i++) {
lv_obj_set_style_opa(_ico[i], LV_OPA_TRANSP, 0);
lv_obj_fade_in(_ico[i], 260, 60 + i * 30);
}
LOG("UI", "launcher open, sel=%d", _sel);
}
void Launcher::close() {
if (!_on) return;
_on = false;
lv_obj_fade_out(_root, 120, 0);
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _root);
lv_anim_set_time(&a, 120);
lv_anim_set_exec_cb(&a, [](void* o, int32_t) {});
lv_anim_set_ready_cb(&a, [](lv_anim_t* an) {
lv_obj_add_flag((lv_obj_t*)an->var, LV_OBJ_FLAG_HIDDEN);
});
lv_anim_start(&a);
}
} // namespace ui

56
src/ui/Launcher.h 100644
View File

@ -0,0 +1,56 @@
#pragma once
// Launcher.h —— 扇形均分的一级菜单
//
// 视觉模型(参考旋钮设备的常见形态):
//
// ╱‾‾‾ 扇区 i ‾‾‾╲ 每个应用占一段等分扇形,段与段之间留
// │ ▲图标 │ 一道细缝(露底色),形成"切开"的质感;
// │ ▲名称 │
// │ ╭───────╮ │ 中心留一个圆盘,显示当前选中的应用名,
// │ │ 应用名 │ │ 它是视觉焦点,也是点击热区。
// │ ╰───────╯ │
// ╲_____________╱
//
// 扇区本身不可点击(arc 的命中区是整个矩形,会吞掉所有触摸),
// 点击由整层统一接管:按角度算出落在哪个扇区,再按半径区分"中心确认"与"选段并进入"。
#include <lvgl.h>
#include <functional>
class App;
namespace ui {
class Launcher {
public:
using PickCb = std::function<void(App*)>;
void build(lv_obj_t* parent, PickCb onPick);
void open(int startIdx);
void close();
bool visible() const { return _on; }
void move(int32_t diff); // 旋钮:>0 顺时针
void select(int idx, bool haptic = true);
lv_obj_t* root() const { return _root; }
private:
void refresh(bool animate);
void enter(int idx);
lv_obj_t* _root = nullptr;
lv_obj_t* _seg[8] = {nullptr};
lv_obj_t* _ico[8] = {nullptr};
lv_obj_t* _hub = nullptr; // 中心圆盘
lv_obj_t* _hubName = nullptr;
lv_obj_t* _hubSub = nullptr;
lv_obj_t* _hubDot = nullptr;
int _sel = 0;
int _n = 0;
bool _on = false;
PickCb _pick;
};
} // namespace ui

View File

@ -0,0 +1,204 @@
#include "NetWizard.h"
#include "Theme.h"
#include "Widgets.h"
#include "../services/NetService.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../config/AppConfig.h"
namespace ui {
// ============================ 构建 ============================
void NetWizard::build(lv_obj_t* parent) {
_box = lv_obj_create(parent);
lv_obj_set_size(_box, SCREEN_W, SCREEN_H);
lv_obj_center(_box);
lv_obj_set_style_bg_color(_box, theme::bg(), 0);
lv_obj_set_style_bg_opa(_box, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_box, 0, 0);
lv_obj_set_style_radius(_box, 0, 0);
lv_obj_set_style_pad_all(_box, 0, 0);
lv_obj_clear_flag(_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_box, LV_OBJ_FLAG_HIDDEN);
_title = label(_box, "配网", FONT_TITLE, theme::text());
lv_obj_align(_title, LV_ALIGN_TOP_MID, 0, 52);
_main = label(_box, "", FONT_TITLE, theme::accent());
lv_obj_align(_main, LV_ALIGN_TOP_MID, 0, 108);
_sub = label(_box, "", FONT_TEXT, theme::text());
lv_obj_align(_sub, LV_ALIGN_TOP_MID, 0, 146);
// 说明文字是**页面内容**,不是浮层提示:配网页只有这一屏,
// 热点名/密码/网址就是它的全部信息,必须一直看得见。
_note = label(_box, "", FONT_TEXT, theme::textDim());
lv_obj_set_width(_note, 296);
lv_label_set_long_mode(_note, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(_note, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(_note, LV_ALIGN_TOP_MID, 0, 174);
_btn = label(_box, "", FONT_TEXT, lv_color_hex(0xFFFFFF));
lv_obj_set_style_bg_color(_btn, theme::accent(), 0);
lv_obj_set_style_bg_opa(_btn, LV_OPA_COVER, 0);
lv_obj_set_style_radius(_btn, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_pad_hor(_btn, 20, 0);
lv_obj_set_style_pad_ver(_btn, 8, 0);
lv_obj_align(_btn, LV_ALIGN_CENTER, 0, 56);
lv_obj_add_flag(_btn, LV_OBJ_FLAG_CLICKABLE);
// 注意:不能引用另一个全局实例——Shell 里只有一个 NetWizard(它自己持有),
// 之前图省事写 ui::netWizard,结果打开的是个从没 build 过的对象。
lv_obj_add_event_cb(_btn, [](lv_event_t* e) {
NetWizard* self = (NetWizard*)lv_event_get_user_data(e);
switch (self->_btnAct) {
case BTN_AP:
case BTN_REAP:
// 只发请求:真正的 WiFi.mode()/softAP() 由 NetService::loop() 执行。
// 在点击回调里直接切网口会卡住 UI,还可能撞上后台正在跑的 TLS 请求。
svc::net.requestAp();
lv_label_set_text(self->_note, "正在开启热点…");
self->setButton(nullptr, false);
break;
case BTN_DONE:
// 配完了:热点不用再等宽限期,立刻收掉(手机已经连上新 WiFi),
// 向导自己退出。不需要重启——凭据早就落 NVS 了,重启只是把同样的
// 连接过程再走一遍,反而会断掉刚建好的会话。
svc::net.requestStopAp();
self->_configured = false;
self->close();
toast(lv_layer_top(), "已联网", 1600);
break;
default:
break;
}
}, LV_EVENT_CLICKED, this);
lv_obj_add_flag(_btn, LV_OBJ_FLAG_HIDDEN);
}
void NetWizard::setButton(const char* text, bool show) {
if (!_btn) return;
if (text) lv_label_set_text(_btn, text);
if (show) lv_obj_clear_flag(_btn, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(_btn, LV_OBJ_FLAG_HIDDEN);
}
// ============================ 状态页 ============================
// 已联网或正在连接时,不硬切热点:先告诉用户现状,由他决定要不要重配。
// 焦点只有一个:刚配完网(_configured)就给「完成」,让这趟流程有个收尾;
// 平时进来看状态就给「重新配网」。
void NetWizard::renderIdle() {
_guide = false;
_shownOnline = svc::net.online();
lv_label_set_text(_title, "网络");
if (svc::net.online()) {
lv_label_set_text(_main, svc::net.ssid().c_str());
lv_obj_set_style_text_color(_main, theme::text(), 0);
lv_label_set_text_fmt(_sub, "%s · 已连接", svc::net.ip().c_str());
if (_configured) {
// 配网刚成功:一句话交代结果 + 一个「完成」把这一屏收掉。
// 不需要重启设备:凭据已落 NVS,热点会在下一帧关掉,
// 这时重启只是把刚建立的连接再断一次(还会让后台同步从头开始)。
lv_label_set_text(_note, "配置已保存,热点即将关闭");
setButton("完成", true);
_btnAct = BTN_DONE;
} else {
lv_label_set_text(_note, ""); // 说清楚现状就够了,操作提示不写
setButton("重新配网", true);
_btnAct = BTN_REAP;
}
} else {
lv_label_set_text(_main, "未联网");
lv_obj_set_style_text_color(_main, theme::textDim(), 0);
String ssid = settings.getS("net.ssid");
if (ssid.length()) lv_label_set_text_fmt(_sub, "正在连接 %s …", ssid.c_str());
else lv_label_set_text(_sub, "还没有配置 WiFi");
lv_label_set_text(_note, "");
setButton("开启配网热点", true);
_btnAct = BTN_AP;
}
}
// ============================ 单页引导 ============================
// 只有一步:手机连本机热点。
// 手机连上后能自己弹出配置页,靠的是两件事(以前只写了注释、没实现,
// 所以 iPhone 上从来没弹过):
// 1. NetService 在热点期间跑通配 DNS,把任何域名都解析到 192.168.4.1;
// 2. WebPortal 把 /hotspot-detect.html、/generate_204 这些系统探针 302 到首页。
// 不给二维码:WiFi 连接二维码扫完并不会自动跳到配置页,屏上多一个码反而让人以为要先扫。
void NetWizard::renderGuide() {
_guide = true;
lv_label_set_text(_title, "配网");
lv_obj_set_style_text_color(_main, theme::accent(), 0);
// ssid() 返回的是临时 String,先把 c_str 用到的字符串留在本地
String apSsid = svc::net.ssid();
lv_label_set_text(_main, apSsid.c_str());
lv_label_set_text_fmt(_sub, "密码 %s", DEFAULT_AP_PASS);
// 只留一句"手机连上会怎样",地址是兜底:iOS 会记住上次对这个 SSID 的判断,
// 极端情况下要等它重新探测,这时直接敲地址最快。
lv_label_set_text(_note, "手机连上会自动打开配置页");
setButton(nullptr, false);
// 热点名与密码已经是"怎么连"的全部答案;192.168.4.1 放在副行,不占正文
LOG("WIZ", "guide: ap=%s", apSsid.c_str());
}
// ============================ 显隐 ============================
void NetWizard::open(bool manual) {
if (!_box) return;
_on = true;
_manual = manual;
_configured = false; // 每次打开都是新的一趟流程
_shownOnline = svc::net.online();
lv_obj_clear_flag(_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_box);
if (svc::net.mode() == svc::NetMode::Ap) renderGuide();
else renderIdle();
}
void NetWizard::close() {
if (!_box) return;
_on = false;
_manual = false;
_configured = false;
lv_obj_add_flag(_box, LV_OBJ_FLAG_HIDDEN);
}
void NetWizard::loop() {
if (!_on) return;
// 开机时 network 还没起来,open() 只能先显示状态页;
// 等它真的切到热点模式了,再自动翻到引导页。
if (!_guide && svc::net.mode() == svc::NetMode::Ap) {
renderGuide();
return;
}
// 已经切回 STA(用户在配网页提交了新 WiFi):从引导页回到状态页。
// 这一跳就等于"配网提交了"——记下来,等连上之后给他一个「完成」。
if (_guide && svc::net.mode() != svc::NetMode::Ap) {
_configured = true;
renderIdle();
return;
}
// 状态页要跟着联网状态走:连上的那一刻把「开启配网热点」换成「完成」,
// 否则用户会一直停在"正在连接 …",以为没成功。
if (!_guide && svc::net.online() != _shownOnline) {
renderIdle();
return;
}
// 开机自动弹出的向导:一连上就自己收(用户不需要再点一下)。
// 主动从设置里点进来的(_manual)才留「完成」——那一趟是他自己在操作,
// 让页面自己消失会让人以为配错了。
if (!_manual && _configured && svc::net.online()) {
close();
toast(lv_layer_top(), "已联网", 1600);
LOG("WIZ", "connected, wizard closed");
}
}
bool NetWizard::onKnob(int32_t diff) {
(void)diff;
return _on; // 只有一页,旋钮无事可做,但也不能漏给下层
}
} // namespace ui

52
src/ui/NetWizard.h 100644
View File

@ -0,0 +1,52 @@
#pragma once
// NetWizard.h —— 配网向导(全屏模态)
//
// 为什么需要它:设备只有旋钮和圆屏,让用户在 360×360 上敲 WiFi 名和密码是灾难。
// 所以设备负责"把人送进门",键盘留给手机:
//
// ① 手机连本机热点(屏上只给热点名 + 密码)
// ② 手机连上后会自动弹出认证页(固件实现了 captive portal 探测),
// 页面里选 WiFi、填密码、填服务端地址 → 设备自动存 NVS 并回 STA
//
// 不再有"打开 192.168.4.1"和二维码:网址要手打,码扫了也不会自动跳转,
// 两步都是多余的摩擦。联网成功向导自动收起。
//
// 触发:① 开机时 NVS 里没有 SSID;② 设置 → 网络 → 配网向导(会切到热点模式)。
#include <Arduino.h>
#include <lvgl.h>
namespace ui {
class NetWizard {
public:
void build(lv_obj_t* parent);
void open(bool manual = false); // 主动配网(已联网时会先确认切热点)
void close();
bool visible() const { return _on; }
void loop(); // 每帧:联网成功自动收起
bool onKnob(int32_t diff); // 返回 true 表示已消费
private:
void renderGuide(); // 热点引导页(只有一页)
void renderIdle(); // 已联网 / 正在连接时的提示页
void setButton(const char* text, bool show);
// 按钮只有一个,但按下要做什么取决于当前状态
enum : uint8_t { BTN_NONE = 0, BTN_AP, BTN_DONE, BTN_REAP };
lv_obj_t* _box = nullptr;
lv_obj_t* _title = nullptr;
lv_obj_t* _main = nullptr;
lv_obj_t* _sub = nullptr;
lv_obj_t* _note = nullptr; // 页面内的说明文字(不是浮层提示,跟着页面走)
lv_obj_t* _btn = nullptr;
uint8_t _btnAct = BTN_NONE;
bool _on = false;
bool _guide = false; // true=正在显示引导页,false=显示状态页
bool _manual = false; // 用户从设置里点进来的(不是开机自动弹的)
bool _configured = false; // 这一轮真的配过网(热点 → STA),用于给「完成」
bool _shownOnline = false; // 状态页上一次画的时候是否已联网(用来触发重画)
};
} // namespace ui

View File

@ -0,0 +1,77 @@
#include "OtaPanel.h"
#include "Theme.h"
#include "Widgets.h"
#include "../services/OtaService.h"
#include "../config/AppConfig.h"
namespace ui {
OtaPanel otaPanel;
void OtaPanel::build() {
_root = lv_obj_create(lv_layer_top());
lv_obj_set_size(_root, SCREEN_W, SCREEN_H);
lv_obj_center(_root);
lv_obj_set_style_bg_color(_root, theme::bg(), 0);
lv_obj_set_style_bg_opa(_root, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_root, 0, 0);
lv_obj_set_style_radius(_root, 0, 0);
lv_obj_set_style_pad_all(_root, 0, 0);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_root, LV_OBJ_FLAG_CLICKABLE); // 升级期间吃掉触摸,别让人乱点
_arc = arc(_root, 150, 4, theme::accent());
lv_obj_set_style_arc_opa(_arc, LV_OPA_20, LV_PART_MAIN);
_pct = label(_root, "0%", FONT_NUM_L, theme::text());
lv_obj_align(_pct, LV_ALIGN_CENTER, 0, -18);
_ver = label(_root, "", FONT_MEDIA, theme::accent());
lv_obj_align(_ver, LV_ALIGN_CENTER, 0, 30);
_tip = label(_root, "正在写入新固件 · 请勿断电", FONT_TEXT, theme::textDim());
lv_obj_align(_tip, LV_ALIGN_CENTER, 0, 66);
lv_obj_set_style_opa(_root, LV_OPA_TRANSP, 0);
lv_obj_fade_in(_root, 180, 0);
}
void OtaPanel::destroy() {
if (!_root) return;
lv_obj_del(_root);
_root = _arc = _pct = _ver = _tip = nullptr;
}
void OtaPanel::loop() {
const svc::OtaState st = svc::ota.state();
const bool need = (st == svc::OtaState::Downloading ||
st == svc::OtaState::Verifying ||
st == svc::OtaState::Ready);
if (need && !_root) build();
if (!need) { destroy(); return; }
if (!_root) return;
int p = svc::ota.progress();
if (p < 0) p = 0;
if (p > 100) p = 100;
if (st == svc::OtaState::Ready) p = 100;
static int lastPct = -1;
if (p != lastPct) {
lastPct = p;
arcSetPct(_arc, p);
lv_label_set_text_fmt(_pct, "%d%%", p);
}
const String& v = svc::ota.release().version;
if (v.length() && strcmp(lv_label_get_text(_ver), v.c_str()) != 0) {
lv_label_set_text_fmt(_ver, "→ %s", v.c_str());
}
const char* tip = (st == svc::OtaState::Ready) ? "校验通过 · 即将重启"
: "正在写入新固件 · 请勿断电";
if (strcmp(lv_label_get_text(_tip), tip) != 0) lv_label_set_text(_tip, tip);
}
} // namespace ui

30
src/ui/OtaPanel.h 100644
View File

@ -0,0 +1,30 @@
#pragma once
// OtaPanel.h —— 固件更新进度浮层
//
// 为什么单独一个全屏层、而不是把进度塞进设置页某一行:
// 升级期间最要紧的一句话是"别断电",它必须盖在所有内容最上面,
// 而且圆屏上列表会滚,进度跟着滚走就没人看得见了。
// 所以和启动动画一样建在 lv_layer_top(),只在下载/校验/待重启时出现。
#include <lvgl.h>
namespace ui {
class OtaPanel {
public:
void loop(); // 每帧跟着 svc::ota 的状态显示/刷新
bool visible() const { return _root != nullptr; }
private:
void build();
void destroy();
lv_obj_t* _root = nullptr;
lv_obj_t* _arc = nullptr;
lv_obj_t* _pct = nullptr;
lv_obj_t* _ver = nullptr;
lv_obj_t* _tip = nullptr;
};
extern OtaPanel otaPanel;
} // namespace ui

391
src/ui/QrCode.cpp 100644
View File

@ -0,0 +1,391 @@
#include "QrCode.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
namespace ui {
namespace {
constexpr int MAX_VER = 7;
constexpr int QUIET = 4;
constexpr int MAX_SIZE = 17 + 4 * MAX_VER; // 45
constexpr int MAX_BLK = 4;
// 版本 1..7 / 纠错 M 的码字表(ISO/IEC 18004 表 9)
// total = 总码字数;ecc = 每块纠错码字数;blk = 块数。
// 这四个数决定了每块数据码字数 = (total - ecc*blk) / blk,恰好都整除。
const uint16_t TOTAL_CW[MAX_VER + 1] = {0, 26, 44, 70, 100, 134, 172, 196};
const uint8_t ECC_CW[MAX_VER + 1] = {0, 10, 16, 26, 18, 24, 16, 18};
const uint8_t NBLK[MAX_VER + 1] = {0, 1, 1, 1, 2, 2, 4, 4};
// 对齐图案中心坐标(v1 没有;v7 起为三个)
const uint8_t ALIGN_POS[MAX_VER + 1][3] = {
{0, 0, 0}, {0, 0, 0}, {6, 18, 0}, {6, 22, 0}, {6, 26, 0},
{6, 30, 0}, {6, 34, 0}, {6, 22, 38},
};
const uint8_t ALIGN_CNT[MAX_VER + 1] = {0, 0, 2, 2, 2, 2, 2, 3};
uint8_t s_mod[MAX_SIZE * MAX_SIZE]; // 最终模块
uint8_t s_fn[MAX_SIZE * MAX_SIZE]; // 功能图案标记(不参与掩码)
uint8_t s_data[MAX_SIZE * MAX_SIZE]; // 数据 + 纠错码字(交织后)
// ---------------------------------------------------------------- GF(256)
uint8_t GF_EXP[512];
uint8_t GF_LOG[256];
bool s_gfReady = false;
void gfInit() {
if (s_gfReady) return;
int x = 1;
for (int i = 0; i < 255; i++) {
GF_EXP[i] = (uint8_t)x;
GF_LOG[x] = (uint8_t)i;
x <<= 1;
if (x & 0x100) x ^= 0x11D;
}
for (int i = 255; i < 512; i++) GF_EXP[i] = GF_EXP[i - 255];
s_gfReady = true;
}
inline uint8_t gfMul(uint8_t a, uint8_t b) {
if (a == 0 || b == 0) return 0;
return GF_EXP[(int)GF_LOG[a] + (int)GF_LOG[b]];
}
// 生成多项式,系数按「最低次在前」存放(与余数计算的方向一致)
void rsDivisor(int degree, uint8_t* out) {
memset(out, 0, (size_t)degree);
out[degree - 1] = 1;
uint8_t root = 1;
for (int i = 0; i < degree; i++) {
for (int j = 0; j < degree; j++) {
out[j] = gfMul(out[j], root);
if (j + 1 < degree) out[j] ^= out[j + 1];
}
root = gfMul(root, 0x02);
}
}
// Reed-Solomon 余数:数据多项式 ÷ 生成多项式,得到 degree 个纠错码字
void rsRemainder(const uint8_t* data, int len, const uint8_t* divisor, int degree, uint8_t* rem) {
memset(rem, 0, (size_t)degree);
for (int i = 0; i < len; i++) {
uint8_t factor = (uint8_t)(data[i] ^ rem[0]);
memmove(rem, rem + 1, (size_t)(degree - 1));
rem[degree - 1] = 0;
for (int j = 0; j < degree; j++) rem[j] ^= gfMul(divisor[j], factor);
}
}
// ---------------------------------------------------------------- 位流
void putBits(uint8_t* buf, int& bitPos, uint32_t val, int n) {
for (int i = n - 1; i >= 0; i--) {
if ((val >> i) & 1) buf[bitPos >> 3] |= (uint8_t)(0x80 >> (bitPos & 7));
bitPos++;
}
}
inline bool getBit(uint32_t v, int i) { return ((v >> i) & 1) != 0; }
// ---------------------------------------------------------------- 矩阵绘制
inline int ix(int x, int y, int size) { return y * size + x; }
void setFn(int size, int x, int y, bool dark) {
s_mod[ix(x, y, size)] = dark ? 1 : 0;
s_fn[ix(x, y, size)] = 1;
}
void drawFinder(int size, int cx, int cy) {
for (int dy = -4; dy <= 4; dy++) {
for (int dx = -4; dx <= 4; dx++) {
int x = cx + dx, y = cy + dy;
if (x < 0 || y < 0 || x >= size || y >= size) continue;
int dist = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
// dist 4 是分隔符(白),2 是内圈(白),其余黑
setFn(size, x, y, dist != 2 && dist != 4);
}
}
}
void drawAlign(int size, int cx, int cy) {
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++) {
int dist = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
setFn(size, cx + dx, cy + dy, dist != 1);
}
}
}
void drawFormatBits(int size, int mask) {
// 纠错等级 M 的两位编码是 00
uint32_t data = (uint32_t)mask; // ecBits << 3 | mask,M 时高 3 位为 0
uint32_t rem = data;
for (int i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >> 9) * 0x537u);
uint32_t bits = ((data << 10) | rem) ^ 0x5412u;
// 第一份:左上角周围
for (int i = 0; i <= 5; i++) setFn(size, 8, i, getBit(bits, i));
setFn(size, 8, 7, getBit(bits, 6));
setFn(size, 8, 8, getBit(bits, 7));
setFn(size, 7, 8, getBit(bits, 8));
for (int i = 9; i < 15; i++) setFn(size, 14 - i, 8, getBit(bits, i));
// 第二份:右上 + 左下
for (int i = 0; i < 8; i++) setFn(size, size - 1 - i, 8, getBit(bits, i));
for (int i = 8; i < 15; i++) setFn(size, 8, size - 15 + i, getBit(bits, i));
setFn(size, 8, size - 8, true); // 固定暗模块
}
void drawVersionBits(int size, int ver) {
if (ver < 7) return;
uint32_t rem = (uint32_t)ver;
for (int i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >> 11) * 0x1F25u);
uint32_t bits = ((uint32_t)ver << 12) | rem;
for (int i = 0; i < 18; i++) {
bool bit = getBit(bits, i);
int a = size - 11 + i % 3;
int b = i / 3;
setFn(size, a, b, bit);
setFn(size, b, a, bit);
}
}
void drawFunctionPatterns(int size, int ver) {
memset(s_mod, 0, sizeof(s_mod));
memset(s_fn, 0, sizeof(s_fn));
// 时序图案
for (int i = 0; i < size; i++) {
setFn(size, 6, i, i % 2 == 0);
setFn(size, i, 6, i % 2 == 0);
}
// 三个定位图案(各自带分隔符)
drawFinder(size, 3, 3);
drawFinder(size, size - 4, 3);
drawFinder(size, 3, size - 4);
// 对齐图案:落在定位图案上的那几个不画
int n = ALIGN_CNT[ver];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int cx = ALIGN_POS[ver][i], cy = ALIGN_POS[ver][j];
bool corner = (i == 0 && j == 0) || (i == 0 && j == n - 1) || (i == n - 1 && j == 0);
if (corner) continue;
drawAlign(size, cx, cy);
}
}
drawFormatBits(size, 0); // 先占位,选完掩码再重画
drawVersionBits(size, ver);
}
void drawCodewords(int size, const uint8_t* cw, int cwLen) {
int i = 0; // 位序号
for (int right = size - 1; right >= 1; right -= 2) {
if (right == 6) right = 5; // 跳过竖向时序列
for (int vert = 0; vert < size; vert++) {
for (int j = 0; j < 2; j++) {
int x = right - j;
bool upward = ((right + 1) & 2) == 0;
int y = upward ? size - 1 - vert : vert;
if (!s_fn[ix(x, y, size)] && i < cwLen * 8) {
s_mod[ix(x, y, size)] = getBit(cw[i >> 3], 7 - (i & 7)) ? 1 : 0;
i++;
}
}
}
}
}
void applyMask(int size, int mask) {
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
if (s_fn[ix(x, y, size)]) continue;
bool invert = false;
switch (mask) {
case 0: invert = (x + y) % 2 == 0; break;
case 1: invert = y % 2 == 0; break;
case 2: invert = x % 3 == 0; break;
case 3: invert = (x + y) % 3 == 0; break;
case 4: invert = (x / 3 + y / 2) % 2 == 0; break;
case 5: invert = (x * y) % 2 + (x * y) % 3 == 0; break;
case 6: invert = ((x * y) % 2 + (x * y) % 3) % 2 == 0; break;
case 7: invert = ((x + y) % 2 + (x * y) % 3) % 2 == 0; break;
}
if (invert) s_mod[ix(x, y, size)] ^= 1;
}
}
}
// ---------------------------------------------------------------- 掩码评分
// 规范里的四条惩罚规则;这里按 11 位窗口直接比对 1:1:3:1:1 的两个模式,
// 比逐段累计 run-length 更好核对(结果一致,且不依赖历史状态)。
const uint8_t PAT_A[11] = {1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0};
const uint8_t PAT_B[11] = {0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1};
int penalty(int size) {
int score = 0;
// 规则 1:同色连续 5 个起,长度 n 罚 3 + (n-5)
for (int y = 0; y < size; y++) {
int run = 1;
for (int x = 1; x < size; x++) {
if (s_mod[ix(x, y, size)] == s_mod[ix(x - 1, y, size)]) {
run++;
if (run == 5) score += 3;
else if (run > 5) score++;
} else {
run = 1;
}
}
}
for (int x = 0; x < size; x++) {
int run = 1;
for (int y = 1; y < size; y++) {
if (s_mod[ix(x, y, size)] == s_mod[ix(x, y - 1, size)]) {
run++;
if (run == 5) score += 3;
else if (run > 5) score++;
} else {
run = 1;
}
}
}
// 规则 2:2x2 同色
for (int y = 0; y < size - 1; y++) {
for (int x = 0; x < size - 1; x++) {
uint8_t c = s_mod[ix(x, y, size)];
if (c == s_mod[ix(x + 1, y, size)] && c == s_mod[ix(x, y + 1, size)] &&
c == s_mod[ix(x + 1, y + 1, size)]) {
score += 3;
}
}
}
// 规则 3:像定位图案的 1:1:3:1:1(前后各留 4 白)
for (int y = 0; y < size; y++) {
for (int x = 0; x + 11 <= size; x++) {
bool a = true, b = true;
for (int i = 0; i < 11; i++) {
uint8_t m = s_mod[ix(x + i, y, size)];
if (m != PAT_A[i]) a = false;
if (m != PAT_B[i]) b = false;
}
if (a) score += 40;
if (b) score += 40;
}
}
for (int x = 0; x < size; x++) {
for (int y = 0; y + 11 <= size; y++) {
bool a = true, b = true;
for (int i = 0; i < 11; i++) {
uint8_t m = s_mod[ix(x, y + i, size)];
if (m != PAT_A[i]) a = false;
if (m != PAT_B[i]) b = false;
}
if (a) score += 40;
if (b) score += 40;
}
}
// 规则 4:暗模块比例偏离 50%
int dark = 0;
for (int i = 0; i < size * size; i++) dark += s_mod[i] ? 1 : 0;
int total = size * size;
int k = (int)((labs((long)dark * 20 - (long)total * 10) + total - 1) / total) - 1;
if (k > 0) score += k * 10;
return score;
}
int pickVersion(int nbytes) {
for (int v = 1; v <= MAX_VER; v++) {
int dataCw = TOTAL_CW[v] - ECC_CW[v] * NBLK[v];
// 4 bit 模式 + 8 bit 计数(v1..v9 都是 8 位)
if (4 + 8 + nbytes * 8 <= dataCw * 8) return v;
}
return -1;
}
} // namespace
bool qrEncode(const char* text, uint8_t* out, int outSide, int& side, int& maskUsed) {
if (!text || !out || !*text) return false;
gfInit();
int n = (int)strlen(text);
int ver = pickVersion(n);
if (ver < 0) return false;
int size = 17 + 4 * ver;
int blocks = NBLK[ver];
int eccPer = ECC_CW[ver];
int dataCw = TOTAL_CW[ver] - eccPer * blocks;
int perBlk = dataCw / blocks;
side = size + QUIET * 2;
if (side > outSide) return false;
// ---------------- 数据位流
memset(s_data, 0, sizeof(s_data));
int bitPos = 0;
putBits(s_data, bitPos, 0x4, 4); // 字节模式
putBits(s_data, bitPos, (uint32_t)n, 8);
for (int i = 0; i < n; i++) putBits(s_data, bitPos, (uint8_t)text[i], 8);
int capBits = dataCw * 8;
int term = capBits - bitPos;
if (term > 4) term = 4;
if (term > 0) putBits(s_data, bitPos, 0, term);
if (bitPos & 7) putBits(s_data, bitPos, 0, 8 - (bitPos & 7));
for (int k = 0, dp = bitPos >> 3; dp < dataCw; k++, dp++) {
s_data[dp] = (k & 1) ? 0x11 : 0xEC;
}
// ---------------- 分块纠错 + 交织
uint8_t div[32];
uint8_t ecc[MAX_BLK][28];
rsDivisor(eccPer, div);
for (int b = 0; b < blocks; b++) {
rsRemainder(s_data + b * perBlk, perBlk, div, eccPer, ecc[b]);
}
uint8_t outCw[256];
int o = 0;
for (int i = 0; i < perBlk; i++)
for (int b = 0; b < blocks; b++) outCw[o++] = s_data[b * perBlk + i];
for (int i = 0; i < eccPer; i++)
for (int b = 0; b < blocks; b++) outCw[o++] = ecc[b][i];
// ---------------- 铺矩阵 → 试 8 种掩码
drawFunctionPatterns(size, ver);
drawCodewords(size, outCw, o);
int best = 0, bestScore = -1;
for (int m = 0; m < 8; m++) {
drawFormatBits(size, m);
applyMask(size, m);
int s = penalty(size);
applyMask(size, m); // 异或两次即还原
if (bestScore < 0 || s < bestScore) {
bestScore = s;
best = m;
}
}
drawFormatBits(size, best);
applyMask(size, best);
maskUsed = best;
// ---------------- 加静区输出
memset(out, 0, (size_t)side * side);
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
out[(y + QUIET) * side + (x + QUIET)] = s_mod[ix(x, y, size)];
}
}
return true;
}
} // namespace ui

23
src/ui/QrCode.h 100644
View File

@ -0,0 +1,23 @@
// 轻量 QR 编码器:只做「字节模式 + 纠错 M + 版本 1..7」。
//
// 为什么要自己写:设备屏上的二维码内容是运行时才有的(服务端签发的一次性票据),
// 没法预先画成图片;而 Arduino 环境里没有现成的二维码库可用。
// 需求范围很窄——URL 只有几十字节、只要 M 级纠错、只要黑白模块矩阵——
// 所以只实现这一条路径,代码量小到可以逐行核对。
//
// 版本 1..7 的纠错块都是等长的(1/1/1/2/2/4/4 块),省掉了混合块的交织分支,
// 这是能把实现压到几百行的关键;124 字节的容量对 URL 绰绰有余。
#pragma once
#include <stdint.h>
namespace ui {
// 把 text 编成二维码模块矩阵(含 4 模块静区)。
// out : 输出缓冲,outSide*outSide 字节,1 = 黑模块、0 = 白
// side : 返回实际边长(含静区)
// maskUsed: 返回选中的掩码编号(调试用)
// 返回 false 表示内容太长或缓冲不够。
bool qrEncode(const char* text, uint8_t* out, int outSide, int& side, int& maskUsed);
} // namespace ui

280
src/ui/QrScreen.cpp 100644
View File

@ -0,0 +1,280 @@
#include "QrScreen.h"
#include "Theme.h"
#include "Widgets.h"
#include "QrCode.h"
#include "../services/PlatformService.h"
#include "../core/Log.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <string.h>
namespace ui {
QrScreen qrScreen;
namespace {
// 二维码画布:224 取的是「360 圆屏能放下的舒适方块」。
// 浮层不再带提示区(扫码时底部那圈遮罩只会干扰摄像头对焦),
// 卡片直接居中:正方形边长 s 放在半径 180 的圆里,s ≤ 254 才不会切角,224 留了呼吸。
constexpr int CANVAS = 224;
constexpr int MAT_MAX = 64; // v7 是 53(含静区),留够余量
struct Ticket {
char url[192];
uint32_t expireMs;
bool ok;
char err[48];
};
Ticket s_tk; // 后台任务写、主线程读
volatile bool s_tkReady = false;
volatile bool s_busy = false;
uint8_t* s_px = nullptr;
uint8_t s_mat[MAT_MAX * MAT_MAX];
void fetchTask(void*) {
Ticket t;
memset(&t, 0, sizeof(t));
if (!svc::platform.bound()) {
strcpy(t.err, "设备未绑定 · 先在配网页配对");
} else if (WiFi.status() != WL_CONNECTED) {
strcpy(t.err, "设备未联网");
} else {
String body, out;
int status = 0;
// 重试是必须的:设备平时在 WiFi modem sleep 里,唤醒后的第一条 TCP
// 连接经常直接失败(connect 超时/被丢包)。旧代码一次不成就把
// 「连不上服务端」顶到屏上,用户再点一次就好了——第一次生成二维码
// 几乎必然撞上。这里自己重试 3 次(每次 350ms 间隔),5xx 也算可重试。
for (int attempt = 1; attempt <= 3; attempt++) {
body = "";
out = "";
status = 0;
// 取票是幂等的:每次都会作废这张设备上之前的码
svc::platform.post("/device/v1/web-login/ticket", "{}", body, status);
if (status > 0 && status < 500) break;
LOG("QR", "ticket attempt %d/3 failed (status=%d)", attempt, status);
if (attempt < 3) vTaskDelay(pdMS_TO_TICKS(350));
}
if (status == 200) {
JsonDocument doc;
if (deserializeJson(doc, body) == DeserializationError::Ok) {
const char* url = doc["url"] | "";
if (url && *url) {
strncpy(t.url, url, sizeof(t.url) - 1);
t.expireMs = millis() + (uint32_t)(doc["expires_in"] | 300) * 1000UL;
t.ok = true;
} else {
strcpy(t.err, "服务端没有返回链接");
}
} else {
strcpy(t.err, "响应解析失败");
}
} else if (status == 409) {
strcpy(t.err, "设备未绑定账号");
} else if (status <= 0) {
strcpy(t.err, "连不上服务端");
} else {
snprintf(t.err, sizeof(t.err), "取码失败(HTTP %d)", status);
}
}
s_tk = t;
s_tkReady = true;
s_busy = false;
vTaskDelete(nullptr);
}
} // namespace
void QrScreen::build(lv_obj_t* parent) {
// 半透明遮罩:下面是「我的」页,能透出来一点,一眼就知道这是浮层不是新页面。
// 整层可点:点哪儿都关(有码时)或者重试(没码时)——不再需要额外的按钮。
_root = lv_obj_create(parent);
lv_obj_set_size(_root, SCREEN_W, SCREEN_H);
lv_obj_center(_root);
lv_obj_add_style(_root, theme::styleScreen(), 0);
lv_obj_set_style_bg_color(_root, lv_color_hex(0x000000), 0);
lv_obj_set_style_bg_opa(_root, LV_OPA_80, 0);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_root, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_root, LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(_root, [](lv_event_t*) { qrScreen.tap(); }, LV_EVENT_CLICKED, nullptr);
// 白卡片取消:白底改由 render() 画进画布(只围住静区一圈),
// 不再有一大圈白边;容器只负责放画布与提示文字。
_panel = lv_obj_create(_root);
lv_obj_set_size(_panel, CANVAS + 20, CANVAS + 20);
lv_obj_center(_panel);
lv_obj_set_style_bg_opa(_panel, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(_panel, 0, 0);
lv_obj_set_style_pad_all(_panel, 0, 0);
lv_obj_clear_flag(_panel, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE); // 点击交给遮罩层
// 画布要透明叠在遮罩上:TRUE_COLOR_ALPHA 每像素多 1 字节 alpha
if (!s_px) s_px = (uint8_t*)ps_malloc((size_t)CANVAS * CANVAS * 3);
if (!s_px) s_px = (uint8_t*)malloc((size_t)CANVAS * CANVAS * 3); // 没有 PSRAM 时的兜底
if (s_px) {
_canvas = lv_canvas_create(_panel);
lv_canvas_set_buffer(_canvas, s_px, CANVAS, CANVAS, LV_IMG_CF_TRUE_COLOR_ALPHA);
lv_obj_center(_canvas);
lv_obj_clear_flag(_canvas, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_canvas, LV_OBJ_FLAG_HIDDEN);
}
// 白底没了:提示文案直接落在深色遮罩上,用亮色
_msg = label(_panel, "", FONT_TEXT, lv_color_hex(0xE6EAF0));
lv_obj_set_width(_msg, CANVAS - 32);
lv_label_set_long_mode(_msg, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(_msg, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_center(_msg);
}
void QrScreen::open() {
if (!_root) return;
if (visible()) return; // 已经开着就别重新取票(会作废屏上这张)
_expireMs = 0;
_showing = false;
// 上一次没收的票要丢掉:那张码在服务端已被新的覆盖,画出来也是废的
s_tkReady = false;
if (_canvas) lv_obj_add_flag(_canvas, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_root);
lv_obj_set_style_opa(_root, LV_OPA_TRANSP, 0);
lv_obj_fade_in(_root, 150, 0);
requestTicket();
}
void QrScreen::toggle() {
if (visible()) close();
else open();
}
void QrScreen::tap() {
// 有码:点一下收起来(这是用户要的"再点一次消除")
// 没码(正在生成 / 过期 / 出错):点一下重试
if (_showing) close();
else refresh();
}
void QrScreen::close() {
if (!_root) return;
lv_obj_add_flag(_root, LV_OBJ_FLAG_HIDDEN);
_expireMs = 0;
}
bool QrScreen::visible() const {
return _root && !lv_obj_has_flag(_root, LV_OBJ_FLAG_HIDDEN);
}
void QrScreen::refresh() {
if (!visible()) return;
if (s_busy) return;
requestTicket();
}
void QrScreen::requestTicket() {
showMessage("正在生成二维码…");
_expireMs = 0;
if (!svc::platform.bound()) {
showMessage("设备未绑定 · 先在配网页配对");
return;
}
if (s_busy) return;
s_busy = true;
if (xTaskCreate(fetchTask, "qr_ticket", 8192, nullptr, 1, nullptr) != pdPASS) {
s_busy = false;
showMessage("任务创建失败 · 点击重试");
}
}
void QrScreen::render(const char* url) {
if (!_canvas) {
showMessage("显示缓冲不足,无法生成二维码");
return;
}
int side = 0, mask = 0;
if (!qrEncode(url, s_mat, MAT_MAX, side, mask)) {
showMessage("链接过长,无法生成二维码");
return;
}
int scale = CANVAS / side;
if (scale < 1) {
showMessage("二维码尺寸超出屏幕");
return;
}
int px = side * scale;
int off = (CANVAS - px) / 2;
int q = scale * 2; // 静区 2 个模块:识别率下限,不再多留
if (off - q < 0) q = off; // 码贴边时静区收缩,别把白底画出画布
// 画布全透明;白底在这里按需画,只包住"静区 + 码",没有大白边
lv_canvas_fill_bg(_canvas, lv_color_black(), LV_OPA_TRANSP);
lv_draw_rect_dsc_t d;
lv_draw_rect_dsc_init(&d);
d.border_width = 0;
d.bg_color = lv_color_hex(0xFFFFFF);
d.bg_opa = LV_OPA_COVER;
d.radius = 18;
lv_canvas_draw_rect(_canvas, off - q, off - q, px + 2 * q, px + 2 * q, &d);
// 点阵模块 + 主题色:纯 accent 橙对白底对比度不够,扫描器拉不响;
// 把它向黑混到 40%,色相保留、对比度达标。每个模块缩 1px 成圆点,点阵感。
d.bg_color = lv_color_mix(theme::accent(), lv_color_black(), LV_OPA_40);
d.radius = LV_RADIUS_CIRCLE;
int cell = scale - 1;
for (int y = 0; y < side; y++) {
for (int x = 0; x < side; x++) {
if (s_mat[y * side + x]) {
lv_canvas_draw_rect(_canvas, off + x * scale, off + y * scale, cell, cell, &d);
}
}
}
lv_obj_clear_flag(_canvas, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(_msg, LV_OBJ_FLAG_HIDDEN);
_showing = true;
LOG("QR", "ticket side=%d scale=%d mask=%d url=%s", side, scale, mask, url);
}
void QrScreen::showMessage(const char* text) {
if (!_msg) return;
if (_canvas) lv_obj_add_flag(_canvas, LV_OBJ_FLAG_HIDDEN);
_showing = false;
lv_label_set_text(_msg, text);
lv_obj_clear_flag(_msg, LV_OBJ_FLAG_HIDDEN);
}
void QrScreen::loop() {
if (!visible()) return;
if (s_tkReady) {
s_tkReady = false;
if (s_tk.ok) {
_expireMs = s_tk.expireMs;
render(s_tk.url);
} else {
showMessage(s_tk.err[0] ? s_tk.err : "取码失败 · 点击重试");
}
}
// 过期后把码撤掉:屏幕上留着一张已经不能用的二维码,比空着更误导
if (_expireMs && millis() > _expireMs) {
_expireMs = 0;
showMessage("二维码已过期 · 点击刷新");
}
}
} // namespace ui

47
src/ui/QrScreen.h 100644
View File

@ -0,0 +1,47 @@
#pragma once
// QrScreen.h —— 「我的」页点击升起的扫码登录浮层
//
// 为什么是一个浮层而不是一个页面:它属于「我的」这个上下文(登录的是同一台
// 设备绑定的同一个账号),关掉就该回到资料上,不需要独立的入口。
//
// 交互:点一下打开,再点一下关(任一点击都算)。码过期/取票失败时,
// 点击变成"重试"——这时候屏幕上没有码,关掉它没有任何意义。
//
// 流程:向服务端要一张一次性票据(5 分钟、一码一用)→ 编成二维码铺满屏 →
// 手机扫码打开 Web 端,服务端验票即登录,落到个人页。
#include <lvgl.h>
namespace ui {
class QrScreen {
public:
void build(lv_obj_t* parent);
void open();
void toggle(); // 开着就关,关着就开(「我的」页点击用)
void close();
bool visible() const;
void tap(); // 浮层上的一次点击:有码=关,没码=重试
// 拉票结果合并 + 过期检查(主循环里调)
void loop();
// 重新取票(由内部点击回调调用,也可以从串口触发)
void refresh();
private:
void requestTicket();
void render(const char* url);
void showMessage(const char* text);
lv_obj_t* _root = nullptr;
lv_obj_t* _panel = nullptr; // 白底圆角卡片:二维码要白底才扫得出来
lv_obj_t* _canvas = nullptr;
lv_obj_t* _msg = nullptr;
uint32_t _expireMs = 0;
bool _showing = false; // 当前屏上是二维码,还是"正在生成/已过期"文字
};
extern QrScreen qrScreen;
} // namespace ui

View File

@ -0,0 +1,219 @@
#include "ServerEditor.h"
#include "Theme.h"
#include "Widgets.h"
#include "../services/NetService.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../apps/SettingsApp.h"
#include "../config/AppConfig.h"
#include <stdio.h>
#include <string.h>
namespace ui {
// 段布局:协议(62) + 四段 IP(各 52) + 端口(140),横向居中
static const int CHIP_H = 52;
static const int GAP = 6;
static const int W_SCHEME = 62;
static const int W_OCTET = 52;
static const int W_PORT = 140;
// 段点击回调(必须是类的静态成员才能摸私有成员;
// 带捕获的 lambda 无法转 lv_event_cb_t)
// 段序号存在对象的 user_data 里,self 由事件 user_data 传入
void ServerEditor::chipCb(lv_event_t* e) {
ServerEditor* self = (ServerEditor*)lv_event_get_user_data(e);
int i = (int)(intptr_t)lv_obj_get_user_data(lv_event_get_target(e));
self->_sel = i;
self->paint();
}
static lv_obj_t* makeChip(lv_obj_t* parent, int w) {
lv_obj_t* c = lv_obj_create(parent);
lv_obj_set_size(c, w, CHIP_H);
lv_obj_set_style_radius(c, 14, 0);
lv_obj_set_style_border_width(c, 0, 0);
lv_obj_set_style_pad_all(c, 0, 0);
lv_obj_clear_flag(c, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(c, LV_OBJ_FLAG_CLICKABLE);
return c;
}
void ServerEditor::build(lv_obj_t* parent) {
_box = lv_obj_create(parent);
lv_obj_set_size(_box, SCREEN_W, SCREEN_H);
lv_obj_center(_box);
lv_obj_set_style_bg_color(_box, theme::bg(), 0);
lv_obj_set_style_bg_opa(_box, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_box, 0, 0);
lv_obj_set_style_radius(_box, 0, 0);
lv_obj_set_style_pad_all(_box, 0, 0);
lv_obj_clear_flag(_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_t* title = label(_box, "服务端地址", FONT_TITLE, theme::text());
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 46);
_tip = label(_box, "", FONT_TEXT, theme::textDim());
lv_obj_align(_tip, LV_ALIGN_TOP_MID, 0, 84);
// 第一行:协议 + 四段 IP
const int total = W_SCHEME + 4 * W_OCTET + 4 * GAP;
int x = (SCREEN_W - total) / 2;
for (int i = 0; i < 5; i++) {
int w = (i == 0) ? W_SCHEME : W_OCTET;
_chip[i] = makeChip(_box, w);
lv_obj_align(_chip[i], LV_ALIGN_TOP_LEFT, x, 116);
_text[i] = label(_chip[i], "", FONT_TEXT, theme::text());
lv_obj_center(_text[i]);
lv_obj_set_user_data(_chip[i], (void*)(intptr_t)i);
lv_obj_add_event_cb(_chip[i], chipCb, LV_EVENT_CLICKED, this);
x += w + GAP;
}
// 第二行:端口
_chip[5] = makeChip(_box, W_PORT);
lv_obj_align(_chip[5], LV_ALIGN_TOP_MID, 0, 116 + CHIP_H + 12);
_text[5] = label(_chip[5], "", FONT_TEXT, theme::text());
lv_obj_center(_text[5]);
lv_obj_set_user_data(_chip[5], (void*)(intptr_t)5);
lv_obj_add_event_cb(_chip[5], chipCb, LV_EVENT_CLICKED, this);
// 顶部 _tip 已经写了"点一段选中 · 转动改值",这里不再重复一行,
// 否则 244 起的那行会被底部按钮(254 起)压住
// 底部三个按钮:默认 / 取消 / 保存
struct BtnDef { const char* text; int dx; ActKind kind; int action; };
const BtnDef defs[3] = {
{"默认", -104, ActKind::Ghost, 0},
{"取消", 0, ActKind::Ghost, 1},
{"保存", 104, ActKind::Primary, 2},
};
for (const auto& d : defs) {
lv_obj_t* b = pillAction(_box, d.text, 92, 44, d.kind, [](lv_event_t* e) {
ServerEditor* self = (ServerEditor*)lv_event_get_user_data(e);
int act = (int)(intptr_t)lv_obj_get_user_data(lv_event_get_target(e));
if (act == 0) {
// 回出厂默认,最快的一条退路
settings.setS("net.server", DEFAULT_SERVER_URL);
self->parse();
self->paint();
toast(lv_layer_top(), "已恢复默认地址", 1400);
} else if (act == 1) {
self->close();
} else {
self->save();
}
}, this);
lv_obj_align(b, LV_ALIGN_CENTER, d.dx, 96);
// 按钮动作既需要 action 序号又需要对象指针:把序号塞进对象的 user_data
lv_obj_set_user_data(b, (void*)(intptr_t)d.action);
}
}
// ============================ 解析 / 绘制 ============================
void ServerEditor::parse() {
String s = settings.getS("net.server");
_parsedOk = true;
_https = s.startsWith("https://");
String rest = s;
int p = rest.indexOf("://");
if (p >= 0) rest = rest.substring(p + 3);
int slash = rest.indexOf('/');
if (slash >= 0) rest = rest.substring(0, slash);
int colon = rest.lastIndexOf(':');
int port = 8100;
if (colon > 0 && rest.indexOf(':') == colon) {
port = rest.substring(colon + 1).toInt();
rest = rest.substring(0, colon);
}
if (port < 1 || port > 65535) port = 8100;
_port = port;
int a = 0, b = 0, c = 0, d = 0;
if (sscanf(rest.c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) == 4) {
_ip[0] = a; _ip[1] = b; _ip[2] = c; _ip[3] = d;
} else {
// 域名形式(api.example.com):设备端没法逐段编辑,保持上次的值并提示
_parsedOk = false;
}
_sel = 1;
}
void ServerEditor::paint() {
if (!_box) return;
for (int i = 0; i < 6; i++) {
if (!_chip[i]) continue;
bool on = (i == _sel);
lv_obj_set_style_bg_color(_chip[i], on ? theme::accent() : theme::surfaceHi(), 0);
lv_obj_set_style_bg_opa(_chip[i], LV_OPA_COVER, 0);
lv_obj_set_style_text_color(_text[i], on ? theme::bg() : theme::text(), 0);
}
lv_label_set_text(_text[0], _https ? "https" : "http");
for (int i = 0; i < 4; i++) {
char b[8];
snprintf(b, sizeof(b), "%d", _ip[i]);
lv_label_set_text(_text[1 + i], b);
}
char pb[24];
snprintf(pb, sizeof(pb), "端口 %d", _port);
lv_label_set_text(_text[5], pb);
// 选中态自己会说话(被选中的段染主色),不再写"点一段选中 · 转动改值"
lv_label_set_text(_tip, _parsedOk ? "" : "当前是域名,这里只能改成 IP 形式");
}
String ServerEditor::url() const {
char b[64];
snprintf(b, sizeof(b), "%s://%d.%d.%d.%d:%d", _https ? "https" : "http",
_ip[0], _ip[1], _ip[2], _ip[3], _port);
return String(b);
}
// ============================ 显隐 / 输入 ============================
void ServerEditor::open() {
if (!_box) return;
parse();
paint();
_on = true;
lv_obj_clear_flag(_box, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_box);
}
void ServerEditor::close() {
if (!_box) return;
_on = false;
lv_obj_add_flag(_box, LV_OBJ_FLAG_HIDDEN);
}
void ServerEditor::save() {
String u = url();
settings.setS("net.server", u);
LOG("UI", "server url -> %s", u.c_str());
toast(lv_layer_top(), "已保存,立即生效", 1500);
apps::settingsApp.rebuild(); // 设置页那行要跟着变
close();
}
bool ServerEditor::onKnob(int32_t diff) {
if (!_on || diff == 0) return false;
if (_sel == 0) {
_https = !_https;
} else if (_sel <= 4) {
int v = _ip[_sel - 1] + (int)diff;
v %= 256;
if (v < 0) v += 256;
_ip[_sel - 1] = v;
} else {
// 端口按 10 一档:从默认 8100 调到 8080 只要两格,逐 1 太磨人
_port += (int)diff * 10;
if (_port < 1) _port = 1;
if (_port > 65535) _port = 65535;
}
paint();
return true;
}
} // namespace ui

View File

@ -0,0 +1,44 @@
#pragma once
// ServerEditor.h —— 服务端地址编辑器(全屏模态)
//
// 圆屏 + 旋钮没法弹系统键盘,所以地址按"段"编辑:
// [http] [192] [168] [2] [147] [端口 8100]
// 点击某段 = 选中,旋钮 = 改这一段的数,点保存写 NVS(立即生效,不用重启)。
//
// 只支持 http(s)://<IPv4>:<port> 这种形式;如果 NVS 里存的是域名,
// 打开时给出提示并允许回默认值——域名情况留给网页端改。
#include <Arduino.h>
#include <lvgl.h>
namespace ui {
class ServerEditor {
public:
void build(lv_obj_t* parent);
void open();
void close();
bool visible() const { return _on; }
bool onKnob(int32_t diff); // 返回 true 表示已消费
private:
static void chipCb(lv_event_t* e); // 段点击(LVGL 回调必须是函数指针)
void parse(); // 从 NVS 读 net.server 拆成段
void paint(); // 刷新高亮与文本
void save();
String url() const;
lv_obj_t* _box = nullptr;
lv_obj_t* _tip = nullptr;
lv_obj_t* _chip[6] = {nullptr};
lv_obj_t* _text[6] = {nullptr};
int _sel = 1; // 0=协议 1..4=IP 5=端口
bool _https = false;
int _ip[4] = {192, 168, 2, 147};
int _port = 8100;
bool _on = false;
bool _parsedOk = true;
};
} // namespace ui

313
src/ui/Shell.cpp 100644
View File

@ -0,0 +1,313 @@
#include "Shell.h"
#include "Theme.h"
#include "Widgets.h"
#include "OtaPanel.h"
#include "../core/AppManager.h"
#include "../core/Settings.h"
#include "../core/Log.h"
#include "../services/PlatformService.h"
#include "../services/NetService.h"
#include "../hal/Display.h"
#include "../hal/Encoder.h"
#include "../hal/Haptic.h"
#include "../config/AppConfig.h"
#include <math.h>
#include <string.h>
namespace ui {
Shell shell;
// ============================ 初始化 ============================
void Shell::begin() {
_root = lv_obj_create(nullptr);
lv_obj_add_style(_root, theme::styleScreen(), 0);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_SCROLLABLE);
lv_scr_load(_root);
_content = lv_obj_create(_root);
lv_obj_set_size(_content, SCREEN_W, SCREEN_H);
lv_obj_center(_content);
lv_obj_add_style(_content, theme::styleTransparent(), 0);
lv_obj_clear_flag(_content, LV_OBJ_FLAG_SCROLLABLE);
_launcher.build(_root, [](App* a) {
shell.switchTo(a);
shell.closeLauncher();
});
buildSheet();
_bind.build(_root); // 绑定页挂在最外层,需要时升起
_wizard.build(_root); // 配网向导
_srvEdit.build(_root); // 服务端地址编辑器
qrScreen.build(_root); // 扫码登录浮层(「我的」页下拉时升起)
hal::setTouchHook([this](bool down, int x, int y) { onTouch(down, x, y); });
// 开机进入设置里指定的桌面应用
int boot = settings.getI("sys.boot");
_home = appMgr.byIndex((uint8_t)(boot < appMgr.count() ? boot : 0));
if (_home) switchTo(_home);
// 一次都没配过 WiFi:什么都不用点,直接把向导推到眼前
if (settings.getS("net.ssid").length() == 0) _wizard.open();
LOG("UI", "shell ready, home=%s", _home ? _home->meta().id : "none");
}
// ============================ 应用切换 ============================
void Shell::switchTo(App* app) {
if (!app) return;
if (app != _cur) {
if (_cur) {
_cur->onExit();
if (_cur->root()) lv_obj_add_flag(_cur->root(), LV_OBJ_FLAG_HIDDEN);
}
if (!app->root()) {
lv_obj_t* r = lv_obj_create(_content);
lv_obj_set_size(r, SCREEN_W, SCREEN_H);
lv_obj_center(r);
lv_obj_add_style(r, theme::styleTransparent(), 0);
lv_obj_clear_flag(r, LV_OBJ_FLAG_SCROLLABLE);
app->setRoot(r);
app->build(r);
}
lv_obj_clear_flag(app->root(), LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(app->root());
// 切应用给一层淡入,硬切太生硬
lv_obj_set_style_opa(app->root(), LV_OPA_TRANSP, 0);
lv_obj_fade_in(app->root(), 200, 0);
_cur = app;
app->onEnter();
LOG("UI", "app -> %s", app->meta().id);
} else if (!_launcher.visible()) {
app->onEnter();
}
// 需要账号的功能:只有服务端**确认过**「这台设备没绑定」时才弹绑定页。
// 以前只看本地 token——服务端地址填错、服务端连不上时,一进模块就报
// "未绑定",而真相是压根没问到服务端。这种情况下让应用正常进去,
// 用页面内的"正在连接服务端"说明现状。
const bool confirmedUnbound = svc::net.online() && svc::platform.serverOk();
if (app->meta().needBind && !svc::platform.bound() && confirmedUnbound) _bind.show();
}
void Shell::backHome() {
closeSheet();
closeLauncher();
if (_home) switchTo(_home);
}
// ============================ 一级菜单 ============================
void Shell::openLauncher() {
if (_sheetOn) return;
_launcher.open(appMgr.indexOf(_cur));
}
void Shell::closeLauncher() { _launcher.close(); }
// ============================ 应用设置层 ============================
// 全屏层从下方升起:圆屏上"卡片"很容易有一角掉到视窗外面,
// 铺满整屏反而永远安全,看起来也像设备本身在翻面。
//
// 盖在应用之上的临时层:与「设置」应用完全同构 —— 全屏 + 中心聚焦轮盘
// + 上滑退出。不再用 300×168 小卡片:设置就是设置,两处不应该两副面孔。
void Shell::buildSheet() {
_sheet = lv_obj_create(_root);
lv_obj_set_size(_sheet, SCREEN_W, SCREEN_H);
lv_obj_center(_sheet);
lv_obj_set_style_bg_color(_sheet, theme::bg(), 0);
lv_obj_set_style_bg_opa(_sheet, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_sheet, 0, 0);
lv_obj_set_style_radius(_sheet, 0, 0);
lv_obj_set_style_pad_all(_sheet, 0, 0);
lv_obj_clear_flag(_sheet, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_sheet, LV_OBJ_FLAG_HIDDEN);
// 全屏列表,交给轮盘布局(不能用 listColumn,互斥)
_sheetList = lv_obj_create(_sheet);
lv_obj_set_size(_sheetList, SCREEN_W, SCREEN_H);
lv_obj_center(_sheetList);
lv_obj_set_style_bg_opa(_sheetList, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(_sheetList, 0, 0);
lv_obj_set_style_pad_all(_sheetList, 0, 0);
lv_obj_set_style_pad_hor(_sheetList, 20, 0);
lv_obj_clear_flag(_sheetList, LV_OBJ_FLAG_SCROLLABLE);
}
void Shell::openSheet() {
if (_sheetOn || !_cur || _launcher.visible()) return;
// 设置应用的整页就是设置列表,再抽一个抽屉等于把同一份内容叠两层
if (strcmp(_cur->meta().id, "settings") == 0) return;
// 应用自己声明"没有设置"时什么也不发生。以前这里会弹一句
// "此应用无需设置"——但那也是一句操作提示,而提示层现在只回答
// "刚才那件事的结果是什么",不该用来解释"这里为什么没反应"。
if (!_cur->meta().hasSettings) return;
_sheetOn = true;
lv_obj_clean(_sheetList);
_cur->buildAppSettings(_sheetList);
if (lv_obj_get_child_cnt(_sheetList) == 0) {
lv_obj_t* l = label(_sheetList, "此应用暂无设置", FONT_TEXT, theme::textDim());
lv_obj_center(l);
}
settingNavAttach(_sheetList);
lv_obj_clear_flag(_sheet, LV_OBJ_FLAG_HIDDEN);
lv_obj_move_foreground(_sheet);
lv_obj_set_y(_sheet, SCREEN_H);
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _sheet);
lv_anim_set_values(&a, SCREEN_H, 0);
lv_anim_set_time(&a, 260);
lv_anim_set_path_cb(&a, lv_anim_path_ease_out);
lv_anim_set_exec_cb(&a, [](void* o, int32_t v) { lv_obj_set_y((lv_obj_t*)o, (lv_coord_t)v); });
lv_anim_start(&a);
}
void Shell::closeSheet() {
if (!_sheetOn) return;
_sheetOn = false;
settingNavDetach();
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _sheet);
lv_anim_set_values(&a, 0, SCREEN_H);
lv_anim_set_time(&a, 200);
lv_anim_set_path_cb(&a, lv_anim_path_ease_in);
lv_anim_set_exec_cb(&a, [](void* o, int32_t v) { lv_obj_set_y((lv_obj_t*)o, (lv_coord_t)v); });
lv_anim_set_ready_cb(&a, [](lv_anim_t* an) {
lv_obj_add_flag((lv_obj_t*)an->var, LV_OBJ_FLAG_HIDDEN);
});
lv_anim_start(&a);
}
// ============================ 手势 ============================
void Shell::onTouch(bool down, int x, int y) {
// 参数的三种含义:
// TAP_SLOP 按住期间允许的抖动,之内一律当"点击"交给 LVGL
// SWIPE_MIN 真正算滑动的位移
// SWIPE_MS 超过这个时长就认为是在拖列表/慢慢挪,不切页
// 之前只有 46px 一个阈值、又不看时长,于是"在设置里拖动列表"
// 松手就被当成上滑,一级菜单弹出来,看着像设置页自己退出了。
static const int TAP_SLOP = 56;
static const int SWIPE_MIN = 80;
static const uint32_t SWIPE_MS = 600;
if (down) {
_sx = x;
_sy = y;
_st = millis();
if (_cur && !_launcher.visible() && !_sheetOn && !_bind.visible()
&& !_wizard.visible() && !_srvEdit.visible()) {
_cur->onPress(x, y); // 应用记下"按下那一刻的滚动位置"
}
return;
}
int dx = x - _sx;
int dy = y - _sy;
uint32_t dt = millis() - _st;
if (abs(dx) < TAP_SLOP && abs(dy) < TAP_SLOP) return; // 点击交给 LVGL
if (dt > SWIPE_MS) return; // 慢拖:列表滚动
if (abs(dx) < SWIPE_MIN && abs(dy) < SWIPE_MIN) return; // 抖了一下,不算手势
handleSwipe(dx, dy);
}
void Shell::handleSwipe(int dx, int dy) {
// 扫码登录是一层浮层:上滑收起,其它手势吞掉(别让它顺手把抽屉拉开)
if (qrScreen.visible()) {
if (dy < 0 && abs(dy) > abs(dx)) qrScreen.close();
return;
}
// 配网向导:下滑收起(先去干别的),其它手势吞掉
if (_wizard.visible()) {
if (dy > 0 && abs(dy) > abs(dx)) _wizard.close();
return;
}
// 地址编辑器:编辑期间一律不响应手势,避免手一抖把输入丢了
if (_srvEdit.visible()) return;
// 绑定页是模态的:下滑收起(先不绑),其它手势全吞掉
if (_bind.visible()) {
if (dy > 0 && abs(dy) > abs(dx)) {
svc::platform.cancelPairing();
_bind.hide();
}
return;
}
// 设置层不吃触摸滚动(轮盘自己算位置),纵向滑动手势都交给下面的
// 通用处理:上滑/下滑都是关闭。滑轨拖动距离小于手势阈值,不受影响。
// 应用可以否决这次滑动(保留扩展位)。
if (_cur && !_launcher.visible() && !_cur->allowShellSwipe(dx, dy)) return;
if (abs(dy) <= abs(dx)) {
if (_cur && !_launcher.visible() && !_sheetOn) {
_cur->onGesture(dx < 0 ? Gesture::SwipeLeft : Gesture::SwipeRight);
}
return;
}
if (dy < 0) { // 上滑
if (_sheetOn) closeSheet();
else if (!_launcher.visible()) openLauncher();
} else { // 下滑
if (_sheetOn) {
closeSheet();
} else if (_launcher.visible()) {
closeLauncher();
} else if (!(_cur && _cur->onGesture(Gesture::SwipeDown))) {
// 应用可以先把下滑用在别处(「我的」→ 扫码登录),
// 没接住才轮到"拉出设置抽屉"
openSheet();
}
}
}
void Shell::onLongPress() { backHome(); }
void Shell::closeModals() {
if (_wizard.visible()) _wizard.close();
if (_srvEdit.visible()) _srvEdit.close();
if (_bind.visible()) { // 调试用:先把绑定页收起来看底层页面
svc::platform.cancelPairing();
_bind.hide();
}
}
// ============================ 主循环 ============================
void Shell::loop(uint32_t nowMs) {
if (_cur && !_launcher.visible()) _cur->onTick(nowMs);
_bind.loop();
_wizard.loop();
qrScreen.loop();
otaPanel.loop(); // 升级进度浮层:始终盖在最上面
int32_t d = hal::encoderTake();
if (d != 0) {
hal::notifyActivity();
if (_srvEdit.visible()) {
_srvEdit.onKnob(d); // 改当前选中的那一段
hal::hapticTick();
} else if (_wizard.visible()) {
_wizard.onKnob(d); // 在两步引导之间切换
hal::hapticTick();
} else if (_bind.visible()) {
// 绑定页是模态的,旋钮不做任何事
} else if (_launcher.visible()) {
_launcher.move(d);
} else if (_sheetOn) {
// 轮盘:旋到中心即选中(轮盘永远消费旋钮)
settingNavKnob(d);
hal::hapticTick();
} else if (_cur) {
// 旋钮反馈统一在框架层给,应用不用各自记得震一下
if (_cur->onKnob(d)) hal::hapticTick();
}
}
}
} // namespace ui

79
src/ui/Shell.h 100644
View File

@ -0,0 +1,79 @@
#pragma once
// Shell.h —— 导航外壳
//
// 交互模型(全圆环):
//
// 应用全屏 --上划--> 一级菜单(扇形均分,见 Launcher)
// 一级菜单 --点击--> 进入应用
// 一级菜单 --下滑--> 取消
// 应用内 --下滑--> 应用设置层(全屏升起,与设置应用同构)
// (设置应用例外:它的整页就是设置,不再叠一层)
// 设置层 --下滑/上滑--> 关闭
// 设置层 --旋钮--> 中心聚焦轮盘:旋到中心即选中(滑轨行只手指拖动调值)
// 未配网 --开机--> 配网向导(热点名/密码/网址/二维码)
// 网络设置 --配网向导--> 切热点并显示向导(模态,联网后自动收起)
// 网络设置 --服务端地址--> 分段编辑器(旋钮改值、点击换段)
// 未绑定 --进入需账号的功能--> 绑定页(码上屏,等网页确认)
// 绑定页 --下滑--> 收起(先不绑);--点击--> 换一张码
// 任意位置 --长按--> 回到桌面应用(设置里的"开机启动")
//
// 旋钮:一级菜单里切换选中;应用内交给应用自己处理。
#include "../core/App.h"
#include "Launcher.h"
#include "BindScreen.h"
#include "NetWizard.h"
#include "ServerEditor.h"
#include "QrScreen.h"
namespace ui {
class Shell {
public:
void begin();
void loop(uint32_t nowMs);
void switchTo(App* app);
App* current() const { return _cur; }
void openLauncher();
void closeLauncher();
bool launcherVisible() const { return _launcher.visible(); }
void openSheet();
void closeSheet();
bool sheetVisible() const { return _sheetOn; }
void backHome();
void onLongPress();
void closeModals();
void openNetWizard() { _wizard.open(true); } // 设置里点「配网向导」
void openServerEditor(){ _srvEdit.open(); } // 收起配网向导 / 地址编辑器(串口 c 键用)
void wizardKnob(int32_t d) { _wizard.onKnob(d); } // 串口 [ ] 键:向导翻页
private:
void buildSheet();
void onTouch(bool down, int x, int y);
void handleSwipe(int dx, int dy);
lv_obj_t* _root = nullptr;
lv_obj_t* _content = nullptr;
lv_obj_t* _sheet = nullptr;
lv_obj_t* _sheetList = nullptr;
Launcher _launcher;
BindScreen _bind;
NetWizard _wizard;
ServerEditor _srvEdit;
App* _cur = nullptr;
App* _home = nullptr;
bool _sheetOn = false;
int _sx = 0, _sy = 0;
uint32_t _st = 0;
};
extern Shell shell;
} // namespace ui

174
src/ui/Splash.cpp 100644
View File

@ -0,0 +1,174 @@
#include "Splash.h"
#include "Theme.h"
#include "Widgets.h"
#include "../config/AppConfig.h"
#include <Arduino.h>
#include <math.h>
namespace ui {
Splash splash;
// 进度环半径:78 太小时副标题("星盘 · 天气 · 音乐"约 170px 宽)会压到环线上,
// 视觉上像字被圆框切开。96 让环把三行文字整个包进去,也更有"开机环"的存在感。
static const int RING_R = 96; // 进度环半径
static const int RING_W = 3;
void Splash::pump(uint32_t ms) {
uint32_t t0 = millis();
while (millis() - t0 < ms) {
lv_timer_handler();
delay(2);
}
}
void Splash::build() {
// 建在顶层而不是独立 screen:后续 Shell 会切换 screen,顶层始终盖在最上面
_root = lv_obj_create(lv_layer_top());
lv_obj_set_size(_root, SCREEN_W, SCREEN_H);
lv_obj_center(_root);
lv_obj_set_style_bg_color(_root, theme::bg(), 0);
lv_obj_set_style_bg_opa(_root, LV_OPA_COVER, 0);
lv_obj_set_style_border_width(_root, 0, 0);
lv_obj_set_style_radius(_root, 0, 0);
lv_obj_set_style_pad_all(_root, 0, 0);
lv_obj_clear_flag(_root, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(_root, LV_OBJ_FLAG_CLICKABLE); // 吃掉启动期间的触摸
_arc = lv_arc_create(_root);
lv_obj_set_size(_arc, RING_R * 2, RING_R * 2);
lv_obj_center(_arc);
lv_obj_clear_flag(_arc, LV_OBJ_FLAG_CLICKABLE);
lv_obj_remove_style(_arc, nullptr, LV_PART_KNOB);
lv_arc_set_rotation(_arc, 270);
lv_arc_set_bg_angles(_arc, 0, 360);
lv_arc_set_angles(_arc, 0, 0);
lv_obj_set_style_bg_opa(_arc, LV_OPA_TRANSP, LV_PART_MAIN);
lv_obj_set_style_border_width(_arc, 0, LV_PART_MAIN);
lv_obj_set_style_arc_width(_arc, RING_W, LV_PART_MAIN);
lv_obj_set_style_arc_width(_arc, RING_W, LV_PART_INDICATOR);
lv_obj_set_style_arc_color(_arc, theme::surfaceHi(), LV_PART_MAIN);
lv_obj_set_style_arc_color(_arc, theme::accent(), LV_PART_INDICATOR);
lv_obj_set_style_arc_rounded(_arc, true, LV_PART_INDICATOR);
// 环末端的小球:让"正在走"这件事有个动点
_dot = lv_obj_create(_root);
lv_obj_set_size(_dot, 7, 7);
lv_obj_set_style_radius(_dot, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(_dot, theme::accent(), 0);
lv_obj_set_style_border_width(_dot, 0, 0);
lv_obj_clear_flag(_dot, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE);
lv_obj_align(_dot, LV_ALIGN_CENTER, 0, -RING_R);
lv_obj_add_flag(_dot, LV_OBJ_FLAG_HIDDEN);
_name = label(_root, BRAND_NAME, FONT_TITLE, theme::text());
lv_obj_align(_name, LV_ALIGN_CENTER, 0, -8);
lv_obj_set_style_text_letter_space(_name, 2, 0);
// 品牌副标题:一屏之内说清这台设备是什么
lv_obj_t* tag = label(_root, BRAND_TAGLINE, FONT_TEXT, theme::textDim());
lv_obj_align(tag, LV_ALIGN_CENTER, 0, 20);
lv_obj_set_style_opa(tag, LV_OPA_TRANSP, 0);
lv_obj_fade_in(tag, 420, 220);
_step = label(_root, "正在启动", FONT_TEXT, theme::textDim());
lv_obj_align(_step, LV_ALIGN_CENTER, 0, 46);
// 名字从下方浮上来 + 淡入
lv_obj_set_style_opa(_name, LV_OPA_TRANSP, 0);
lv_obj_fade_in(_name, 380, 60);
lv_obj_align(_name, LV_ALIGN_CENTER, 0, 4);
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _name);
lv_anim_set_values(&a, 4, -8);
lv_anim_set_time(&a, 420);
lv_anim_set_path_cb(&a, lv_anim_path_ease_out);
lv_anim_set_exec_cb(&a, [](void* o, int32_t v) { lv_obj_align((lv_obj_t*)o, LV_ALIGN_CENTER, 0, v); });
lv_anim_start(&a);
pump(320);
}
void Splash::applyPct(int pct, bool animate) {
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
int from = (int)lv_arc_get_value(_arc) * 360 / 100;
if (animate) {
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _arc);
lv_anim_set_values(&a, from, pct * 360 / 100);
lv_anim_set_time(&a, 260);
lv_anim_set_path_cb(&a, lv_anim_path_ease_out);
lv_anim_set_exec_cb(&a, [](void* o, int32_t v) {
lv_arc_set_angles((lv_obj_t*)o, 0, (uint16_t)v);
// 小球跟着弧末端走
lv_obj_t* dot = (lv_obj_t*)lv_obj_get_user_data((lv_obj_t*)o);
if (dot) {
float rad = ((float)v - 90.0f) * 0.01745329f;
lv_obj_align(dot, LV_ALIGN_CENTER,
(int)lroundf(RING_R * cosf(rad)),
(int)lroundf(RING_R * sinf(rad)));
}
});
lv_obj_set_user_data(_arc, _dot); // 必须先挂上再启动,否则前几帧小球不动
lv_anim_start(&a);
lv_obj_clear_flag(_dot, LV_OBJ_FLAG_HIDDEN);
} else {
lv_arc_set_angles(_arc, 0, (uint16_t)(pct * 360 / 100));
}
lv_arc_set_value(_arc, pct);
_pct = pct;
}
void Splash::step(int pct, const char* text, uint32_t settleMs) {
if (!_root) return;
applyPct(pct, true);
if (text) lv_label_set_text(_step, text);
pump(settleMs > 0 ? settleMs : 60);
}
void Splash::replay() {
if (_root) return;
build();
step(26, "挂载存储", 260);
step(58, "连接网络", 260);
step(74, "加载应用", 0); // 停在这里,留着给人截图
}
void Splash::dismiss() {
if (!_root) return;
lv_obj_t* root = _root;
_root = nullptr;
_arc = _dot = _name = _step = nullptr;
lv_obj_del(root);
}
void Splash::finish() {
if (!_root) return;
lv_obj_t* root = _root;
_root = nullptr;
// 环向外扩散 + 整体淡出,像镜头推进后切场
lv_anim_t a;
lv_anim_init(&a);
lv_anim_set_var(&a, _arc);
lv_anim_set_values(&a, RING_R, RING_R + 60);
lv_anim_set_time(&a, 420);
lv_anim_set_path_cb(&a, lv_anim_path_ease_out);
lv_anim_set_exec_cb(&a, [](void* o, int32_t v) {
lv_obj_set_size((lv_obj_t*)o, v * 2, v * 2);
lv_obj_center((lv_obj_t*)o);
});
lv_anim_start(&a);
lv_obj_fade_out(root, 420, 60);
pump(520);
lv_obj_del(root);
}
} // namespace ui

44
src/ui/Splash.h 100644
View File

@ -0,0 +1,44 @@
#pragma once
// Splash.h —— 启动动画
//
// 为什么单独做一层:开机时各模块初始化是阻塞的,如果直接往下跑,
// 屏幕会停在第一帧直到全部完成,看起来像"死机"。
// 这里把初始化拆成若干步,每步之间主动泵几帧 LVGL,进度环走的是真实进度,
// 既好看又能在启动卡住时一眼看出卡在哪一步。
#include <lvgl.h>
namespace ui {
class Splash {
public:
void build();
// pct: 0~100 真实进度;text: 当前步骤;settleMs: 本步停留时长(泵帧用)
void step(int pct, const char* text, uint32_t settleMs = 0);
// 收尾:环扩散 + 整体淡出,然后自毁
void finish();
// 手动泵帧(初始化阶段调用,替代 delay)
static void pump(uint32_t ms);
// ---- 仅调试用 ----
// 开机动画只在启动那几秒存在,串口命令赶不上。这两个接口让它能重播并停在
// 中途,方便截图检查(见 services/RemoteDebug.cpp 的 v / x 命令)。
void replay();
void dismiss();
private:
void applyPct(int pct, bool animate);
lv_obj_t* _root = nullptr;
lv_obj_t* _arc = nullptr;
lv_obj_t* _dot = nullptr;
lv_obj_t* _name = nullptr;
lv_obj_t* _step = nullptr;
int _pct = 0;
};
extern Splash splash;
} // namespace ui

Some files were not shown because too many files have changed in this diff Show More