commit d5cfc30b3b97c011a865e0f9166f243614b0cd87 Author: DESKTOP-PUHFO60\dsx2016 Date: Sun Oct 18 21:53:26 2026 +0800 Initial CYD LD2420 radar dashboard with flashable firmware archive. Presence uses ESPHome factory gates/timeout; OT1->GPIO22 RX->GPIO27; prebuilt bins under firmware/cyd_28r. Co-authored-by: Cursor diff --git a/.cursor/rules/git-and-docs.mdc b/.cursor/rules/git-and-docs.mdc new file mode 100644 index 0000000..3868e64 --- /dev/null +++ b/.cursor/rules/git-and-docs.mdc @@ -0,0 +1,15 @@ +--- +description: 每次改动必须提交 Git、更新文档,并刷新预编译固件 +alwaysApply: true +--- + +# Git、文档与固件 + +对本项目做任何功能、行为或配置改动后,在结束本次任务前必须: + +1. **更新文档**:至少更新 `README.md` 的「功能 / 硬件 / 变更记录」中受影响部分。 +2. **刷新预编译固件**:运行 `.\firmware\export_from_build.ps1`(或 `-SkipBuild`),保证 `firmware/cyd_28r/` 随时可刷。 +3. **提交 Git**:`git add` 相关文件后 `git commit`(含 `firmware/` 归档)。 +4. **不要**在未提交的情况下声称任务已完成。 + +例外:用户明确说「先别提交」或「不要改文档」时,以用户当次指令为准。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39ce04d --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch +*.pyc +__pycache__/ +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..a53634a --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +# CYD LD2420 雷达仪表盘 + +ESP32 Cheap Yellow Display(ESP32-2432S028R)+ HLK-LD2420 24GHz 毫米波雷达 + LVGL 仪表盘。 + +## 硬件 + +| 项目 | 说明 | +|------|------| +| 板子 | CYD ESP32-2432S028R(2.8" ILI9341) | +| 传感器 | HLK-LD2420 | +| OT1 | **GPIO22**(模块串口 TX → ESP RX,固件 ≥ v1.5.3) | +| RX | **GPIO27**(模块串口 RX → ESP TX) | +| 供电 | 3.3V / GND(与 CYD 共地) | + +接线(固件 ≥ v1.5.3): + +``` +LD2420 3V3 → CYD 3.3V +LD2420 GND → CYD GND +LD2420 OT1 → GPIO22 +LD2420 RX → GPIO27 +``` + +> 旧固件(< v1.5.3)串口 TX 在 OT2,且默认波特率多为 **256000**。本工程会依次探测 115200 / 256000。 + +## 功能 + +- 横屏网格:距离圆弧 + 存在圆弧;底部左信息 / 右趋势图 +- **显示 LD2420 固件版本**(启动时进入配置模式读取 `CMD 0x0000`) +- **存在逻辑**:移动或静止检到 → 保持 ON;离开约 **10s** 后才 OFF(ESPHome 同款超时/门限) +- 检测门默认 1–12(约 0.7–8.4 m),出厂静止门限(能坐着不动也保持有人) +- 短按切换背光;长按 ≥0.7s 重置 min/max + +## 构建与烧录 + +依赖 [PlatformIO](https://platformio.org/)。 + +```bash +pio run -e cyd_28r -t upload +pio device monitor -b 115200 +``` + +### 预编译固件(随时刷,不必编译) + +已归档到 [`firmware/cyd_28r/`](firmware/cyd_28r/)(含 bootloader / partitions / app): + +```powershell +cd firmware\cyd_28r +.\flash.ps1 +# 或 .\flash.ps1 -Port COM3 +``` + +说明见 [`firmware/README.md`](firmware/README.md)。源码更新后重新打包:`.\firmware\export_from_build.ps1`。 + +### 环境选择 + +| 环境 | 适用 | +|------|------| +| `cyd_28r` | 标准 ILI9341 CYD(默认) | +| `cyd_28r_inv` | 颜色反相 / 发白 | +| `cyd_28_st7789` | USB-C 双口 / ST7789 变体 | + +## 项目结构 + +``` +platformio.ini # 板级与库依赖 +include/lv_conf.h # LVGL 配置 +src/main.cpp # 仪表盘 + LD2420 驱动 +scripts/exclude_lvgl_asm.py # 排除 ESP32 不兼容的 LVGL ASM +firmware/ # 预编译固件(可离线刷写) +.cursor/rules/ # Cursor 协作规则 +README.md # 本文档 +``` + +## 变更约定 + +每次功能或行为改动须: + +1. 更新本 README(及必要时的注释) +2. 刷新 `firmware/cyd_28r/`(`.\firmware\export_from_build.ps1`) +3. `git add` + `git commit` 提交 + +详见 `.cursor/rules/git-and-docs.mdc`。 + +## 变更记录 + +| 日期 | 说明 | +|------|------| +| 2026-10-18 | 初版:CYD + LD2420 LVGL 仪表盘;OT1→GPIO22、RX→GPIO27;显示固件版本 | +| 2026-10-18 | 存在逻辑改为 ESPHome 出厂门限 + 10s 离开保持(动/静均保持 ON) | +| 2026-10-18 | 归档预编译固件到 `firmware/cyd_28r/`,附一键刷写;初始化本地 Git | + +## 串口日志示例 + +``` +CYD LVGL LD2420 Radar Dashboard +LD2420 probe @ 115200 baud RX=22 TX=27 + FW=v1.6.1 mode=simple + set gates 1..12 to=10s (OK) +``` + +界面左下角会显示 `FW v1.6.1` 与波特率(后缀 `S`=Simple)。 diff --git a/firmware/README.md b/firmware/README.md new file mode 100644 index 0000000..0a5fd17 --- /dev/null +++ b/firmware/README.md @@ -0,0 +1,46 @@ +# 预编译固件(可随时刷写) + +当前归档目录:[`cyd_28r/`](cyd_28r/) + +对应板子:**CYD ESP32-2432S028R**(ILI9341),LD2420 OT1→GPIO22、RX→GPIO27。 +版本信息见 [`cyd_28r/VERSION.txt`](cyd_28r/VERSION.txt)。 + +## 直接刷写(无需重新编译) + +1. USB 连接板子 +2. 在本目录执行: + +```powershell +cd firmware\cyd_28r +.\flash.ps1 +# 或指定端口 +.\flash.ps1 -Port COM3 +``` + +也可双击 / 运行 `flash.bat`。 + +依赖其一即可: + +- 已安装 PlatformIO(`pio`,自带 esptool) +- 或 `pip install esptool` + +## 手动 esptool + +```bash +esptool.py --chip esp32 --port COM3 --baud 921600 write_flash -z ^ + --flash_mode dio --flash_freq 40m --flash_size 4MB ^ + 0x1000 bootloader.bin ^ + 0x8000 partitions.bin ^ + 0xe000 boot_app0.bin ^ + 0x10000 firmware.bin +``` + +## 从源码重新打包进本目录 + +在仓库根目录: + +```powershell +.\firmware\export_from_build.ps1 +# 仅复制、不编译: +.\firmware\export_from_build.ps1 -SkipBuild +``` diff --git a/firmware/cyd_28r/VERSION.txt b/firmware/cyd_28r/VERSION.txt new file mode 100644 index 0000000..f59632b --- /dev/null +++ b/firmware/cyd_28r/VERSION.txt @@ -0,0 +1,16 @@ +name: CYD LD2420 radar dashboard (cyd_28r) +git: unknown +date: 2026-10-18 +board: ESP32-2432S028R (ILI9341) +ld2420: OT1->GPIO22 RX->GPIO27 +flash_size: 4MB +offsets: + 0x1000 bootloader.bin + 0x8000 partitions.bin + 0xe000 boot_app0.bin + 0x10000 firmware.bin +sha256: + bootloader.bin 3D234A7471F67B013686DABD4DEE7C1FA915C9928463616A94BC9297ACF1ABF8 + boot_app0.bin F94C5D786A7A8FAB06AC5D10E33BF37711A6697636DC037559EA19CC410A17F0 + firmware.bin 33D7FADFD8050A0B83BE2EC233A0A310644E6545DEA0E7BCD63B315153B89A63 + partitions.bin 0A8B5720E7B77FF11F1462458C3A509DEE79224E5279898F26D6A2E3AE0517B7 diff --git a/firmware/cyd_28r/boot_app0.bin b/firmware/cyd_28r/boot_app0.bin new file mode 100644 index 0000000..13562ca Binary files /dev/null and b/firmware/cyd_28r/boot_app0.bin differ diff --git a/firmware/cyd_28r/bootloader.bin b/firmware/cyd_28r/bootloader.bin new file mode 100644 index 0000000..d592359 Binary files /dev/null and b/firmware/cyd_28r/bootloader.bin differ diff --git a/firmware/cyd_28r/firmware.bin b/firmware/cyd_28r/firmware.bin new file mode 100644 index 0000000..7f94a05 Binary files /dev/null and b/firmware/cyd_28r/firmware.bin differ diff --git a/firmware/cyd_28r/flash.bat b/firmware/cyd_28r/flash.bat new file mode 100644 index 0000000..bf983b3 --- /dev/null +++ b/firmware/cyd_28r/flash.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +cd /d "%~dp0" +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0flash.ps1" %* +exit /b %ERRORLEVEL% diff --git a/firmware/cyd_28r/flash.ps1 b/firmware/cyd_28r/flash.ps1 new file mode 100644 index 0000000..40cefb7 --- /dev/null +++ b/firmware/cyd_28r/flash.ps1 @@ -0,0 +1,84 @@ +# Flash archived CYD LD2420 radar firmware (no rebuild needed) +# Usage: +# .\flash.ps1 +# .\flash.ps1 -Port COM5 +# .\flash.ps1 -Port COM5 -Baud 460800 + +param( + [string]$Port = "", + [int]$Baud = 921600 +) + +$ErrorActionPreference = "Stop" +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $here + +function Find-Esptool { + $pio = Get-Command pio -ErrorAction SilentlyContinue + if ($pio) { + $pkg = Join-Path $env:USERPROFILE ".platformio\packages\tool-esptoolpy\esptool.py" + if (Test-Path $pkg) { return @{ Kind = "py"; Path = $pkg } } + } + $py = Get-Command python -ErrorAction SilentlyContinue + if ($py) { + try { + & python -c "import esptool" 2>$null + if ($LASTEXITCODE -eq 0) { return @{ Kind = "mod"; Path = "esptool" } } + } catch {} + } + $esp = Get-Command esptool.py -ErrorAction SilentlyContinue + if ($esp) { return @{ Kind = "py"; Path = $esp.Source } } + return $null +} + +if (-not $Port) { + $ports = @() + try { + Add-Type -AssemblyName System.IO.Ports -ErrorAction SilentlyContinue | Out-Null + $ports = [System.IO.Ports.SerialPort]::GetPortNames() | Sort-Object + } catch {} + if (-not $ports -or $ports.Count -eq 0) { + $ports = Get-CimInstance Win32_SerialPort -ErrorAction SilentlyContinue | + Select-Object -ExpandProperty DeviceID | Sort-Object + } + if (-not $ports -or $ports.Count -eq 0) { + Write-Error "No serial ports found. Plug in the CYD USB cable, then retry with -Port COMx" + } + if ($ports.Count -eq 1) { + $Port = $ports[0] + } else { + Write-Host "Available ports: $($ports -join ', ')" + $Port = $ports[-1] + Write-Host "Using last port: $Port (override with -Port)" + } +} + +$tool = Find-Esptool +if (-not $tool) { + Write-Error "esptool not found. Install PlatformIO (`pio`) or: pip install esptool" +} + +$argsCommon = @( + "--chip", "esp32", + "--port", $Port, + "--baud", "$Baud", + "--before", "default_reset", + "--after", "hard_reset", + "write_flash", "-z", + "--flash_mode", "dio", + "--flash_freq", "40m", + "--flash_size", "4MB", + "0x1000", "bootloader.bin", + "0x8000", "partitions.bin", + "0xe000", "boot_app0.bin", + "0x10000", "firmware.bin" +) + +Write-Host "Flashing $here -> $Port @ $Baud" +if ($tool.Kind -eq "mod") { + & python -m esptool @argsCommon +} else { + & python $tool.Path @argsCommon +} +if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +Write-Host "Done. Open serial monitor at 115200 if needed." diff --git a/firmware/cyd_28r/partitions.bin b/firmware/cyd_28r/partitions.bin new file mode 100644 index 0000000..21800fa Binary files /dev/null and b/firmware/cyd_28r/partitions.bin differ diff --git a/firmware/export_from_build.ps1 b/firmware/export_from_build.ps1 new file mode 100644 index 0000000..beb301a --- /dev/null +++ b/firmware/export_from_build.ps1 @@ -0,0 +1,57 @@ +# Rebuild (optional) and refresh firmware/cyd_28r from PlatformIO build output. +# Usage: +# .\firmware\export_from_build.ps1 +# .\firmware\export_from_build.ps1 -SkipBuild + +param([switch]$SkipBuild) + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +Set-Location $root + +if (-not $SkipBuild) { + pio run -e cyd_28r + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } +} + +$src = Join-Path $root ".pio\build\cyd_28r" +$dst = Join-Path $root "firmware\cyd_28r" +New-Item -ItemType Directory -Force -Path $dst | Out-Null + +Copy-Item (Join-Path $src "bootloader.bin") $dst -Force +Copy-Item (Join-Path $src "partitions.bin") $dst -Force +Copy-Item (Join-Path $src "firmware.bin") $dst -Force + +$bootApp = Join-Path $env:USERPROFILE ".platformio\packages\framework-arduinoespressif32\tools\partitions\boot_app0.bin" +if (-not (Test-Path $bootApp)) { + Write-Error "boot_app0.bin not found under PlatformIO packages" +} +Copy-Item $bootApp (Join-Path $dst "boot_app0.bin") -Force + +$git = "unknown" +try { + $git = (git -C $root rev-parse --short HEAD 2>$null).Trim() + if (-not $git) { $git = "unknown" } +} catch { $git = "unknown" } + +$date = Get-Date -Format "yyyy-MM-dd" +$hashes = Get-FileHash (Join-Path $dst "*.bin") -Algorithm SHA256 +$lines = @( + "name: CYD LD2420 radar dashboard (cyd_28r)", + "git: $git", + "date: $date", + "board: ESP32-2432S028R (ILI9341)", + "ld2420: OT1->GPIO22 RX->GPIO27", + "flash_size: 4MB", + "offsets:", + " 0x1000 bootloader.bin", + " 0x8000 partitions.bin", + " 0xe000 boot_app0.bin", + " 0x10000 firmware.bin", + "sha256:" +) +foreach ($h in $hashes) { + $lines += (" {0,-15} {1}" -f (Split-Path $h.Path -Leaf), $h.Hash) +} +$lines | Set-Content -Encoding utf8 (Join-Path $dst "VERSION.txt") +Write-Host "Exported -> $dst (git $git)" diff --git a/include/lv_conf.h b/include/lv_conf.h new file mode 100644 index 0000000..6c23cfa --- /dev/null +++ b/include/lv_conf.h @@ -0,0 +1,86 @@ +#ifndef LV_CONF_H +#define LV_CONF_H + +#include + +#define LV_COLOR_DEPTH 16 + +#define LV_MEM_SIZE (48 * 1024U) +#define LV_DEF_REFR_PERIOD 16 +#define LV_DPI_DEF 130 + +/* ESP32 无 Helium,关掉以免 .S 汇编被错误预处理 */ +#define LV_USE_DRAW_SW_ASM LV_DRAW_SW_ASM_NONE + +#define LV_USE_OS LV_OS_NONE +#define LV_USE_STDLIB_MALLOC LV_STDLIB_BUILTIN +#define LV_USE_STDLIB_STRING LV_STDLIB_BUILTIN +#define LV_USE_STDLIB_SPRINTF LV_STDLIB_BUILTIN + +#define LV_USE_LOG 0 +#define LV_USE_ASSERT_NULL 1 +#define LV_USE_ASSERT_MALLOC 1 + +#define LV_FONT_MONTSERRAT_12 1 +#define LV_FONT_MONTSERRAT_14 1 +#define LV_FONT_MONTSERRAT_16 1 +#define LV_FONT_MONTSERRAT_20 1 +#define LV_FONT_MONTSERRAT_24 1 +#define LV_FONT_MONTSERRAT_28 1 +#define LV_FONT_MONTSERRAT_32 1 +#define LV_FONT_MONTSERRAT_40 1 +#define LV_FONT_DEFAULT &lv_font_montserrat_14 + +#define LV_USE_FLOAT 1 +#define LV_USE_MATRIX 0 + +#define LV_USE_LABEL 1 +#define LV_LABEL_TEXT_SELECTION 0 +#define LV_LABEL_LONG_TXT_HINT 1 + +#define LV_USE_ARC 1 +#define LV_USE_BAR 1 +#define LV_USE_BTN 1 +#define LV_USE_BUTTON 1 +#define LV_USE_IMG 1 +#define LV_USE_IMAGE 1 +#define LV_USE_LINE 1 +#define LV_USE_SLIDER 1 +#define LV_USE_SWITCH 1 +#define LV_USE_TEXTAREA 0 +#define LV_USE_CHECKBOX 0 +#define LV_USE_DROPDOWN 0 +#define LV_USE_ROLLER 0 +#define LV_USE_TABLE 0 +#define LV_USE_CALENDAR 0 +#define LV_USE_CHART 1 +#define LV_USE_KEYBOARD 0 +#define LV_USE_LIST 0 +#define LV_USE_MENU 0 +#define LV_USE_MSGBOX 0 +#define LV_USE_SPAN 0 +#define LV_USE_SPINBOX 0 +#define LV_USE_SPINNER 1 +#define LV_USE_TABVIEW 0 +#define LV_USE_TILEVIEW 0 +#define LV_USE_WIN 0 +#define LV_USE_LED 1 +#define LV_USE_SCALE 1 + +#define LV_USE_THEME_DEFAULT 1 +#define LV_THEME_DEFAULT_DARK 1 +#define LV_THEME_DEFAULT_GROW 0 +#define LV_THEME_DEFAULT_TRANSITION_TIME 80 + +#define LV_USE_FLEX 1 +#define LV_USE_GRID 1 + +#define LV_USE_TFT_ESPI 1 + +#define LV_USE_OBSERVER 0 +#define LV_USE_SYSMON 0 +#define LV_USE_PROFILER 0 +#define LV_USE_DEMO_WIDGETS 0 +#define LV_USE_DEMO_BENCHMARK 0 + +#endif /* LV_CONF_H */ diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..39ec4c4 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,66 @@ +; CYD ESP32-2432S028R — LVGL LD2420 毫米波雷达仪表盘 +; LD2420 OT1 -> GPIO22 (ESP RX), LD2420 RX -> GPIO27 (ESP TX) + +[platformio] +default_envs = cyd_28r + +[env] +platform = espressif32@6.9.0 +board = esp32dev +framework = arduino +monitor_speed = 115200 +upload_speed = 921600 +board_build.partitions = min_spiffs.csv +lib_deps = + lvgl/lvgl@9.2.2 + bodmer/TFT_eSPI@2.5.43 + https://github.com/PaulStoffregen/XPT2046_Touchscreen.git +extra_scripts = pre:scripts/exclude_lvgl_asm.py +build_flags = + -D CORE_DEBUG_LEVEL=0 + -D USER_SETUP_LOADED=1 + -D USE_HSPI_PORT=1 + -D ILI9341_2_DRIVER=1 + -D TFT_WIDTH=240 + -D TFT_HEIGHT=320 + -D TFT_MISO=12 + -D TFT_MOSI=13 + -D TFT_SCLK=14 + -D TFT_CS=15 + -D TFT_DC=2 + -D TFT_RST=-1 + -D TFT_BL=21 + -D TFT_BACKLIGHT_ON=HIGH + -D SPI_FREQUENCY=40000000 + -D SPI_READ_FREQUENCY=20000000 + -D LOAD_GLCD=1 + -D LOAD_FONT2=0 + -D LOAD_FONT4=0 + -D LOAD_FONT6=0 + -D LOAD_FONT7=0 + -D LOAD_FONT8=0 + -D LOAD_GFXFF=0 + -D SMOOTH_FONT=0 + -D TOUCH_CS=-1 + -D LV_CONF_INCLUDE_SIMPLE=1 + -I include + +; 标准 CYD 2.8" 电阻屏 (ILI9341) +[env:cyd_28r] +build_flags = + ${env.build_flags} + +; 颜色反相版本(若画面色偏/发白可改用此环境) +[env:cyd_28r_inv] +build_flags = + ${env.build_flags} + -D TFT_INVERSION_ON=1 + +; USB-C 双口 / 7789 变体 +[env:cyd_28_st7789] +build_flags = + ${env.build_flags} + -U ILI9341_2_DRIVER + -D ST7789_DRIVER=1 + -D TFT_RGB_ORDER=TFT_BGR + -D TFT_INVERSION_ON=1 diff --git a/scripts/exclude_lvgl_asm.py b/scripts/exclude_lvgl_asm.py new file mode 100644 index 0000000..5200ba1 --- /dev/null +++ b/scripts/exclude_lvgl_asm.py @@ -0,0 +1,13 @@ +"""Exclude LVGL Helium/Neon .S files that break ESP32 (xtensa) builds.""" +import shutil +from pathlib import Path + +Import("env") # type: ignore # noqa: F821 + +LIBDEPS = Path(env["PROJECT_LIBDEPS_DIR"]) / env["PIOENV"] / "lvgl" # type: ignore # noqa: F821 + +for sub in ("draw/sw/blend/helium", "draw/sw/blend/neon"): + target = LIBDEPS / "src" / sub + if target.exists(): + shutil.rmtree(target, ignore_errors=True) + print(f"Removed LVGL ASM path: {target}") diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..e5fea8e --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,924 @@ +/** + * CYD ESP32-2432S028R — LVGL LD2420 毫米波雷达仪表盘 + * + * 接线 (固件 ≥ v1.5.3): + * LD2420 OT1 -> GPIO22 (模块串口 TX → ESP RX) + * LD2420 RX -> GPIO27 (模块串口 RX → ESP TX) + * VCC 3.3V / GND + */ + +#include +#include +#include +#include +#include +#include + +/* ---- pins ---- */ +#define LD2420_RX_PIN 22 /* ESP RX <- OT1 */ +#define LD2420_TX_PIN 27 /* ESP TX -> RX */ +#define TFT_BL_PIN 21 + +#define XPT2046_IRQ 36 +#define XPT2046_MOSI 32 +#define XPT2046_MISO 39 +#define XPT2046_CLK 25 +#define XPT2046_CS 33 + +#define SCREEN_WIDTH 320 +#define SCREEN_HEIGHT 240 +#define UI_REFRESH_MS 250 +#define CHART_PUSH_MS 1000 +#define SENSOR_STALE_MS 5000 +#define HISTORY_LEN 48 +#define DIST_ARC_MAX 800 /* cm (~11 gates * 70cm) */ +#define DRAW_BUF_SIZE (SCREEN_WIDTH * SCREEN_HEIGHT / 10 * (LV_COLOR_DEPTH / 8)) + +/* Layout grid — exclusive regions, no overlaps */ +#define UI_M 6 +#define UI_G 6 +#define UI_HDR_H 22 +#define UI_GAUGE_H 124 +#define UI_GAUGE_W 151 +#define UI_ARC 90 +#define UI_BOT_Y (UI_HDR_H + UI_G + UI_GAUGE_H + UI_G) /* 158 */ +#define UI_BOT_H (SCREEN_HEIGHT - UI_BOT_Y - UI_M) /* 76 */ +#define UI_BOT_W (SCREEN_WIDTH - 2 * UI_M) /* 308 */ +#define UI_INFO_W 124 +#define UI_CHART_W (UI_BOT_W - 12 - UI_INFO_W - UI_G) /* ~160 */ + +/* LD2420 protocol (wire byte order) */ +static const uint8_t CMD_HDR_B[4] = {0xFD, 0xFC, 0xFB, 0xFA}; +static const uint8_t CMD_FTR_B[4] = {0x04, 0x03, 0x02, 0x01}; +static const uint8_t ENERGY_HDR_B[4] = {0xF1, 0xF2, 0xF3, 0xF4}; +static const uint8_t ENERGY_FTR_B[4] = {0xF5, 0xF6, 0xF7, 0xF8}; +static const uint16_t CMD_ENABLE_CONF = 0x00FF; +static const uint16_t CMD_DISABLE_CONF = 0x00FE; +static const uint16_t CMD_READ_VERSION = 0x0000; +static const uint16_t CMD_WRITE_SYS = 0x0012; +static const uint16_t CMD_WRITE_ABD = 0x0007; +static const uint16_t CMD_PROTOCOL_VER = 0x0002; +static const uint16_t SYS_MODE_PARAM = 0x0000; +static const uint16_t MODE_SIMPLE = 0x0064; +/* + * Presence semantics (ESPHome / HLK): + * - move OR still energy → occupied + * - presence_timeout keeps ON after last hit; only then OFF + * Factory still thresholds are low so sitting still stays detected. + */ +static const uint32_t CFG_MIN_GATE = 1; /* ~0.7 m */ +static const uint32_t CFG_MAX_GATE = 12; /* ~8.4 m */ +static const uint32_t CFG_TIMEOUT_S = 10; /* seconds after leave before OFF */ + +/* ESPHome factory thresholds — still must stay sensitive */ +static const uint32_t CFG_MOVE_THRESH[16] = { + 60000, 30000, 400, 300, 250, 250, 250, 250, + 300, 250, 250, 250, 250, 200, 200, 200}; +static const uint32_t CFG_STILL_THRESH[16] = { + 40000, 20000, 200, 250, 150, 150, 150, 150, + 150, 150, 150, 150, 100, 100, 100, 100}; + +static const lv_color_t COL_BG = lv_color_hex(0x0A1018); +static const lv_color_t COL_PANEL = lv_color_hex(0x121C2A); +static const lv_color_t COL_EDGE = lv_color_hex(0x1E2C40); +static const lv_color_t COL_TEXT = lv_color_hex(0xF2F5FA); +static const lv_color_t COL_MUTED = lv_color_hex(0x7E90A8); +static const lv_color_t COL_DIST = lv_color_hex(0x4DA3FF); +static const lv_color_t COL_PRES = lv_color_hex(0x3DBF8C); +static const lv_color_t COL_OK = lv_color_hex(0x4CAF7A); +static const lv_color_t COL_WARN = lv_color_hex(0xE6B84D); +static const lv_color_t COL_BAD = lv_color_hex(0xE05A5A); +static const lv_color_t COL_ARC_BG = lv_color_hex(0x243247); +static const lv_color_t COL_CHART_BG = lv_color_hex(0x0E1622); + +SPIClass touchscreenSPI = SPIClass(VSPI); +XPT2046_Touchscreen touchscreen(XPT2046_CS, XPT2046_IRQ); +HardwareSerial RadarSerial(2); + +static uint32_t draw_buf[DRAW_BUF_SIZE / 4]; + +static lv_obj_t *arc_dist; +static lv_obj_t *arc_pres; +static lv_obj_t *lbl_dist_val; +static lv_obj_t *lbl_pres_val; +static lv_obj_t *lbl_dist_range; +static lv_obj_t *lbl_pres_hint; +static lv_obj_t *lbl_state; +static lv_obj_t *lbl_fw; +static lv_obj_t *lbl_baud; +static lv_obj_t *lbl_status; +static lv_obj_t *lbl_uptime; +static lv_obj_t *lbl_hint; +static lv_obj_t *led_status; +static lv_obj_t *bar_presence; +static lv_obj_t *chart; +static lv_chart_series_t *ser_dist; +static lv_chart_series_t *ser_pres; + +static float disp_dist = NAN; +static float min_dist = NAN; +static float max_dist = NAN; +static bool presence = false; +static bool sensor_ok = false; +static bool fw_ok = false; +static char fw_version[24] = "----"; +static uint32_t radar_baud = 115200; +static bool energy_mode = false; +static uint32_t last_ok_ms = 0; +static uint32_t last_ui_ms = 0; +static uint32_t last_chart_ms = 0; +static uint32_t last_dbg_ms = 0; +static uint32_t presence_since_ms = 0; +static uint8_t bright_level = 2; +static const uint8_t BRIGHT_PWM[4] = {40, 90, 160, 255}; +static uint32_t hint_until_ms = 0; +static uint32_t last_seen_ms = 0; /* last time module reported presence energy */ + +static uint8_t rx_buf[512]; +static uint16_t rx_pos = 0; + +static void set_backlight(uint8_t level) { + bright_level = level & 0x03; + ledcWrite(0, BRIGHT_PWM[bright_level]); +} + +static void show_hint(const char *text, uint32_t ms) { + lv_label_set_text(lbl_hint, text); + lv_obj_remove_flag(lbl_hint, LV_OBJ_FLAG_HIDDEN); + lv_obj_move_foreground(lbl_hint); + hint_until_ms = millis() + ms; +} + +static void reset_minmax(void) { + if (!isnan(disp_dist)) { + min_dist = max_dist = disp_dist; + } else { + min_dist = max_dist = NAN; + } + show_hint("min/max reset", 1200); +} + +static void touchscreen_read(lv_indev_t *indev, lv_indev_data_t *data) { + LV_UNUSED(indev); + static bool was_pressed = false; + static uint32_t press_ms = 0; + + if (touchscreen.tirqTouched() && touchscreen.touched()) { + TS_Point p = touchscreen.getPoint(); + data->point.x = map(p.y, 240, 3800, 1, SCREEN_WIDTH); + data->point.y = map(p.x, 200, 3700, SCREEN_HEIGHT, 1); + data->state = LV_INDEV_STATE_PRESSED; + if (!was_pressed) { + was_pressed = true; + press_ms = millis(); + } + } else { + data->state = LV_INDEV_STATE_RELEASED; + if (was_pressed) { + was_pressed = false; + uint32_t held = millis() - press_ms; + if (held >= 700) { + reset_minmax(); + } else if (held < 400) { + set_backlight((bright_level + 1) & 0x03); + char buf[20]; + lv_snprintf(buf, sizeof(buf), "brightness %u/3", (unsigned)bright_level); + show_hint(buf, 900); + } + } + } +} + +static void arc_anim_exec(void *obj, int32_t v) { + lv_arc_set_value((lv_obj_t *)obj, v); +} + +static void anim_arc(lv_obj_t *arc, int32_t value) { + int32_t cur = lv_arc_get_value(arc); + if (cur == value) return; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, arc); + lv_anim_set_values(&a, cur, value); + lv_anim_set_duration(&a, 420); + lv_anim_set_exec_cb(&a, arc_anim_exec); + lv_anim_set_path_cb(&a, lv_anim_path_ease_out); + lv_anim_start(&a); +} + +static void bar_anim_exec(void *obj, int32_t v) { + lv_bar_set_value((lv_obj_t *)obj, v, LV_ANIM_OFF); +} + +static void anim_bar(lv_obj_t *bar, int32_t value) { + int32_t cur = lv_bar_get_value(bar); + if (cur == value) return; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, bar); + lv_anim_set_values(&a, cur, value); + lv_anim_set_duration(&a, 320); + lv_anim_set_exec_cb(&a, bar_anim_exec); + lv_anim_set_path_cb(&a, lv_anim_path_ease_out); + lv_anim_start(&a); +} + +static lv_obj_t *make_panel(lv_obj_t *parent, int x, int y, int w, int h) { + lv_obj_t *p = lv_obj_create(parent); + lv_obj_set_pos(p, x, y); + lv_obj_set_size(p, w, h); + lv_obj_set_style_bg_color(p, COL_PANEL, 0); + lv_obj_set_style_bg_opa(p, LV_OPA_COVER, 0); + lv_obj_set_style_border_color(p, COL_EDGE, 0); + lv_obj_set_style_border_width(p, 1, 0); + lv_obj_set_style_radius(p, 12, 0); + lv_obj_set_style_pad_all(p, 6, 0); + lv_obj_clear_flag(p, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(p, LV_OBJ_FLAG_SCROLLABLE); + return p; +} + +static lv_obj_t *make_gauge(lv_obj_t *parent, lv_color_t accent, int max_val) { + lv_obj_t *arc = lv_arc_create(parent); + lv_obj_set_size(arc, UI_ARC, UI_ARC); + lv_obj_align(arc, LV_ALIGN_TOP_MID, 0, 2); + lv_arc_set_rotation(arc, 135); + lv_arc_set_bg_angles(arc, 0, 270); + lv_arc_set_range(arc, 0, max_val); + lv_arc_set_value(arc, 0); + lv_obj_remove_style(arc, NULL, LV_PART_KNOB); + lv_obj_clear_flag(arc, LV_OBJ_FLAG_CLICKABLE); + lv_obj_set_style_arc_color(arc, COL_ARC_BG, LV_PART_MAIN); + lv_obj_set_style_arc_width(arc, 10, LV_PART_MAIN); + lv_obj_set_style_arc_color(arc, accent, LV_PART_INDICATOR); + lv_obj_set_style_arc_width(arc, 10, LV_PART_INDICATOR); + lv_obj_set_style_arc_rounded(arc, true, LV_PART_MAIN); + lv_obj_set_style_arc_rounded(arc, true, LV_PART_INDICATOR); + return arc; +} + +static lv_color_t dist_color(float cm) { + if (isnan(cm)) return COL_MUTED; + if (cm < 150.0f) return COL_PRES; + if (cm < 400.0f) return COL_DIST; + if (cm < 600.0f) return COL_WARN; + return COL_BAD; +} + +static int fw_to_int(const char *ver) { + const char *p = (*ver == 'v' || *ver == 'V') ? ver + 1 : ver; + int result = 0; + for (; *p; p++) { + if (*p == '.') continue; + if (*p < '0' || *p > '9') break; + result = result * 10 + (*p - '0'); + } + return result; +} + +/* ---- LD2420 command helpers ---- */ + +static void radar_flush(void) { + while (RadarSerial.available()) RadarSerial.read(); + rx_pos = 0; +} + +static void radar_write_frame(uint16_t cmd, const uint8_t *data, uint16_t data_len) { + uint8_t buf[64]; + uint16_t len = 0; + uint16_t frame_data = (uint16_t)(data_len + 2); + memcpy(&buf[len], CMD_HDR_B, 4); len += 4; + memcpy(&buf[len], &frame_data, 2); len += 2; + memcpy(&buf[len], &cmd, 2); len += 2; + if (data && data_len) { + memcpy(&buf[len], data, data_len); + len += data_len; + } + memcpy(&buf[len], CMD_FTR_B, 4); len += 4; + RadarSerial.write(buf, len); + RadarSerial.flush(); +} + +static bool radar_wait_ack(uint16_t expect_cmd, uint8_t *out, uint16_t out_cap, uint16_t *out_len, + uint32_t timeout_ms) { + uint8_t buf[128]; + uint16_t pos = 0; + uint32_t start = millis(); + uint16_t reply_cmd = (uint16_t)(expect_cmd | 0x0100); + + while ((millis() - start) < timeout_ms) { + while (RadarSerial.available() && pos < sizeof(buf)) { + buf[pos++] = (uint8_t)RadarSerial.read(); + if (pos >= 8) { + for (uint16_t i = 0; i + 4 <= pos; i++) { + if (memcmp(&buf[i], CMD_HDR_B, 4) != 0) continue; + if (i + 10 > pos) continue; + uint16_t flen = 0; + memcpy(&flen, &buf[i + 4], 2); + uint16_t total = (uint16_t)(4 + 2 + flen + 4); + if (i + total > pos) continue; + if (memcmp(&buf[i + total - 4], CMD_FTR_B, 4) != 0) continue; + uint16_t cmd = 0; + memcpy(&cmd, &buf[i + 6], 2); + if (cmd != reply_cmd && cmd != expect_cmd) continue; + uint16_t copy = total; + if (copy > out_cap) copy = out_cap; + memcpy(out, &buf[i], copy); + *out_len = copy; + return true; + } + } + } + delay(2); + } + return false; +} + +static bool radar_write_abd_u32(uint16_t param, uint32_t value) { + uint8_t data[6]; + memcpy(&data[0], ¶m, 2); + memcpy(&data[2], &value, 4); + radar_write_frame(CMD_WRITE_ABD, data, 6); + uint8_t ack[64]; + uint16_t ack_len = 0; + return radar_wait_ack(CMD_WRITE_ABD, ack, sizeof(ack), &ack_len, 1200); +} + +static bool radar_read_abd_u32(uint16_t param, uint32_t *value) { + uint8_t data[2]; + memcpy(data, ¶m, 2); + radar_write_frame(0x0008, data, 2); /* CMD_READ_ABD */ + uint8_t ack[64]; + uint16_t ack_len = 0; + if (!radar_wait_ack(0x0008, ack, sizeof(ack), &ack_len, 1200)) return false; + if (ack_len < 14) return false; + memcpy(value, &ack[10], 4); + return true; +} + +static bool radar_apply_detection_window(void) { + bool ok = true; + if (!radar_write_abd_u32(0x0000, CFG_MIN_GATE)) ok = false; + delay(20); + if (!radar_write_abd_u32(0x0001, CFG_MAX_GATE)) ok = false; + delay(20); + if (!radar_write_abd_u32(0x0004, CFG_TIMEOUT_S)) ok = false; + delay(20); + for (uint8_t g = 0; g < 16; g++) { + if (!radar_write_abd_u32((uint16_t)(0x0010 + g), CFG_MOVE_THRESH[g])) ok = false; + delay(12); + if (!radar_write_abd_u32((uint16_t)(0x0020 + g), CFG_STILL_THRESH[g])) ok = false; + delay(12); + } + uint32_t rmin = 0, rmax = 0, rto = 0; + radar_read_abd_u32(0x0000, &rmin); + radar_read_abd_u32(0x0001, &rmax); + radar_read_abd_u32(0x0004, &rto); + Serial.printf(" set gates %lu..%lu to=%lus (%s)\n", + (unsigned long)CFG_MIN_GATE, (unsigned long)CFG_MAX_GATE, + (unsigned long)CFG_TIMEOUT_S, ok ? "OK" : "FAIL"); + Serial.printf(" readback min=%lu max=%lu timeout=%lu\n", + (unsigned long)rmin, (unsigned long)rmax, (unsigned long)rto); + return ok; +} + +static bool radar_enable_config(bool enable) { + uint8_t ack[64]; + uint16_t ack_len = 0; + if (enable) { + uint8_t data[2]; + memcpy(data, &CMD_PROTOCOL_VER, 2); + radar_write_frame(CMD_ENABLE_CONF, data, 2); + return radar_wait_ack(CMD_ENABLE_CONF, ack, sizeof(ack), &ack_len, 1200); + } + radar_write_frame(CMD_DISABLE_CONF, NULL, 0); + return radar_wait_ack(CMD_DISABLE_CONF, ack, sizeof(ack), &ack_len, 1200); +} + +static bool radar_read_version(char *out, size_t out_sz) { + uint8_t ack[96]; + uint16_t ack_len = 0; + radar_write_frame(CMD_READ_VERSION, NULL, 0); + if (!radar_wait_ack(CMD_READ_VERSION, ack, sizeof(ack), &ack_len, 1500)) return false; + if (ack_len < 13) return false; + uint8_t ver_len = ack[10]; + if (ver_len == 0 || (uint16_t)(12 + ver_len) > ack_len - 4) { + /* some firmwares put ASCII after error word without length prefix */ + size_t n = 0; + for (uint16_t i = 10; i + 4 < ack_len && n + 1 < out_sz; i++) { + char c = (char)ack[i]; + if (c < 32 || c > 126) break; + out[n++] = c; + } + out[n] = '\0'; + return n > 0; + } + if (ver_len >= out_sz) ver_len = (uint8_t)(out_sz - 1); + memcpy(out, &ack[12], ver_len); + out[ver_len] = '\0'; + return true; +} + +static bool radar_set_mode(uint16_t mode) { + uint8_t data[8]; + memcpy(&data[0], &SYS_MODE_PARAM, 2); + uint32_t m = mode; + memcpy(&data[2], &m, 4); + radar_write_frame(CMD_WRITE_SYS, data, 6); + uint8_t ack[64]; + uint16_t ack_len = 0; + return radar_wait_ack(CMD_WRITE_SYS, ack, sizeof(ack), &ack_len, 1200); +} + +static bool radar_probe_at_baud(uint32_t baud) { + Serial.printf("LD2420 probe @ %lu baud RX=%d TX=%d\n", + (unsigned long)baud, LD2420_RX_PIN, LD2420_TX_PIN); + RadarSerial.end(); + delay(20); + RadarSerial.begin(baud, SERIAL_8N1, LD2420_RX_PIN, LD2420_TX_PIN); + delay(80); + radar_flush(); + + if (!radar_enable_config(true)) { + Serial.println(" enable config FAIL"); + return false; + } + + char ver[24] = {0}; + bool got = radar_read_version(ver, sizeof(ver)); + if (!got) { + Serial.println(" read version FAIL"); + radar_enable_config(false); + return false; + } + + strncpy(fw_version, ver, sizeof(fw_version) - 1); + fw_version[sizeof(fw_version) - 1] = '\0'; + fw_ok = true; + radar_baud = baud; + + /* Simple text ON/OFF is more reliable for presence; energy optional later */ + energy_mode = false; + Serial.printf(" FW=%s mode=simple\n", fw_version); + (void)fw_to_int(fw_version); + + radar_apply_detection_window(); + + if (!radar_set_mode(MODE_SIMPLE)) { + Serial.println(" set mode FAIL (continue with default)"); + } + + radar_enable_config(false); + radar_flush(); + return true; +} + +static bool radar_init(void) { + static const uint32_t bauds[] = {115200, 256000}; + for (uint8_t i = 0; i < 2; i++) { + if (radar_probe_at_baud(bauds[i])) return true; + } + /* last resort: open 115200 and hope for simple-mode text */ + RadarSerial.begin(115200, SERIAL_8N1, LD2420_RX_PIN, LD2420_TX_PIN); + radar_baud = 115200; + energy_mode = false; + strncpy(fw_version, "N/A", sizeof(fw_version) - 1); + fw_ok = false; + Serial.println("LD2420: no ACK — listening for simple-mode text"); + return false; +} + +/* + * Trust module ON/OFF. Module already applies presence_timeout for still/leave. + * Extra software hold only bridges brief UART glitches (not for filtering people out). + */ +static void set_occupied(bool on, float cm) { + bool was = presence; + uint32_t now = millis(); + + if (on) { + last_seen_ms = now; + presence = true; + if (!was) { + presence_since_ms = now; + Serial.println("UI: OCCUPIED"); + } + if (!isnan(cm) && cm > 0.0f) { + disp_dist = cm; + if (isnan(min_dist) || cm < min_dist) min_dist = cm; + if (isnan(max_dist) || cm > max_dist) max_dist = cm; + } + } else { + /* Module said OFF — clear immediately (timeout already elapsed on radar) */ + presence = false; + presence_since_ms = 0; + disp_dist = 0.0f; + if (was) Serial.println("UI: CLEAR"); + } + + sensor_ok = true; + last_ok_ms = now; +} + +static void handle_simple_line(const uint8_t *inbuf, int len) { + /* Lines: "ON", "OFF", "Range 123" */ + while (len > 0 && (inbuf[len - 1] == '\r' || inbuf[len - 1] == '\n' || inbuf[len - 1] == 0)) { + len--; + } + if (len <= 0) return; + + char line[48]; + uint8_t n = (len < (int)sizeof(line) - 1) ? (uint8_t)len : (uint8_t)(sizeof(line) - 1); + memcpy(line, inbuf, n); + line[n] = '\0'; + + if (n == 3 && line[0] == 'O' && line[1] == 'F' && line[2] == 'F') { + set_occupied(false, NAN); + return; + } + if (n == 2 && line[0] == 'O' && line[1] == 'N') { + set_occupied(true, disp_dist); /* keep last range until Range line updates */ + return; + } + + if (n >= 6 && strncmp(line, "Range", 5) == 0) { + const char *p = line + 5; + while (*p == ' ' || *p == '\t') p++; + if (*p >= '0' && *p <= '9') { + float cm = (float)strtol(p, NULL, 10); + /* Range with value implies target; latch occupied + distance */ + set_occupied(true, cm); + } + return; + } +} + +static void handle_energy_frame(const uint8_t *buf, int len) { + if (len < 6 + 1 + 2 + 4) return; + uint8_t index = 6; + bool present = (buf[index++] == 1); + uint16_t range = 0; + memcpy(&range, &buf[index], 2); + if (range > 2000) return; + set_occupied(present, present ? (float)range : NAN); +} + +static void radar_poll(void) { + while (RadarSerial.available()) { + int b = RadarSerial.read(); + if (b < 0) break; + if (rx_pos >= sizeof(rx_buf) - 1) rx_pos = 0; + rx_buf[rx_pos++] = (uint8_t)b; + rx_buf[rx_pos] = 0; + + if (rx_pos < 4) continue; + + /* discard command ACK frames */ + if (memcmp(&rx_buf[rx_pos - 4], CMD_FTR_B, 4) == 0) { + rx_pos = 0; + continue; + } + + if (energy_mode && memcmp(&rx_buf[rx_pos - 4], ENERGY_FTR_B, 4) == 0) { + for (int i = (int)rx_pos - 4; i >= 0; i--) { + if (memcmp(&rx_buf[i], ENERGY_HDR_B, 4) == 0) { + handle_energy_frame(&rx_buf[i], rx_pos - (uint16_t)i); + break; + } + } + rx_pos = 0; + continue; + } + + if (rx_pos >= 2 && rx_buf[rx_pos - 2] == 0x0D && rx_buf[rx_pos - 1] == 0x0A) { + handle_simple_line(rx_buf, rx_pos); + rx_pos = 0; + } + } +} + +/* ---- UI ---- */ + +static void create_ui(void) { + lv_obj_t *scr = lv_screen_active(); + lv_obj_set_style_bg_color(scr, COL_BG, 0); + lv_obj_set_style_bg_opa(scr, LV_OPA_COVER, 0); + lv_obj_clear_flag(scr, LV_OBJ_FLAG_SCROLLABLE); + + lv_obj_t *title = lv_label_create(scr); + lv_label_set_text(title, "RADAR"); + lv_obj_set_style_text_font(title, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_color(title, COL_TEXT, 0); + lv_obj_set_pos(title, UI_M, 4); + + lbl_uptime = lv_label_create(scr); + lv_label_set_text(lbl_uptime, "up 00:00"); + lv_obj_set_style_text_font(lbl_uptime, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_uptime, COL_MUTED, 0); + lv_obj_align_to(lbl_uptime, title, LV_ALIGN_OUT_RIGHT_MID, 8, 1); + + led_status = lv_led_create(scr); + lv_obj_set_size(led_status, 9, 9); + lv_obj_align(led_status, LV_ALIGN_TOP_RIGHT, -UI_M, 6); + lv_led_set_color(led_status, COL_WARN); + lv_led_on(led_status); + + lbl_status = lv_label_create(scr); + lv_label_set_text(lbl_status, "INIT"); + lv_obj_set_style_text_font(lbl_status, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_status, COL_MUTED, 0); + lv_obj_align(lbl_status, LV_ALIGN_TOP_RIGHT, -(UI_M + 16), 4); + + lbl_hint = lv_label_create(scr); + lv_label_set_text(lbl_hint, ""); + lv_obj_set_style_text_font(lbl_hint, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_hint, COL_WARN, 0); + lv_obj_set_style_bg_color(lbl_hint, COL_BG, 0); + lv_obj_set_style_bg_opa(lbl_hint, LV_OPA_COVER, 0); + lv_obj_set_style_pad_hor(lbl_hint, 6, 0); + lv_obj_align(lbl_hint, LV_ALIGN_TOP_MID, 0, 4); + lv_obj_add_flag(lbl_hint, LV_OBJ_FLAG_HIDDEN); + + const int gy = UI_HDR_H + UI_G; + + lv_obj_t *p_dist = make_panel(scr, UI_M, gy, UI_GAUGE_W, UI_GAUGE_H); + lv_obj_t *d_cap = lv_label_create(p_dist); + lv_label_set_text(d_cap, "DIST"); + lv_obj_set_style_text_font(d_cap, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(d_cap, COL_MUTED, 0); + lv_obj_align(d_cap, LV_ALIGN_TOP_LEFT, 0, -2); + + arc_dist = make_gauge(p_dist, COL_DIST, DIST_ARC_MAX); + lbl_dist_val = lv_label_create(p_dist); + lv_label_set_text(lbl_dist_val, "---"); + lv_obj_set_style_text_font(lbl_dist_val, &lv_font_montserrat_24, 0); + lv_obj_set_style_text_color(lbl_dist_val, COL_DIST, 0); + lv_obj_align(lbl_dist_val, LV_ALIGN_TOP_MID, -6, 32); + + lv_obj_t *d_unit = lv_label_create(p_dist); + lv_label_set_text(d_unit, "cm"); + lv_obj_set_style_text_font(d_unit, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(d_unit, COL_MUTED, 0); + lv_obj_align_to(d_unit, lbl_dist_val, LV_ALIGN_OUT_RIGHT_MID, 2, 2); + + lbl_dist_range = lv_label_create(p_dist); + lv_label_set_text(lbl_dist_range, "-- / --"); + lv_obj_set_style_text_font(lbl_dist_range, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_dist_range, COL_MUTED, 0); + lv_obj_align(lbl_dist_range, LV_ALIGN_BOTTOM_MID, 0, 2); + + lv_obj_t *p_pres = make_panel(scr, UI_M + UI_GAUGE_W + UI_G, gy, UI_GAUGE_W, UI_GAUGE_H); + lv_obj_t *p_cap = lv_label_create(p_pres); + lv_label_set_text(p_cap, "PRESENCE"); + lv_obj_set_style_text_font(p_cap, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(p_cap, COL_MUTED, 0); + lv_obj_align(p_cap, LV_ALIGN_TOP_LEFT, 0, -2); + + arc_pres = make_gauge(p_pres, COL_PRES, 100); + lbl_pres_val = lv_label_create(p_pres); + lv_label_set_text(lbl_pres_val, "----"); + lv_obj_set_style_text_font(lbl_pres_val, &lv_font_montserrat_20, 0); + lv_obj_set_style_text_color(lbl_pres_val, COL_MUTED, 0); + lv_obj_align(lbl_pres_val, LV_ALIGN_TOP_MID, 0, 34); + + lbl_pres_hint = lv_label_create(p_pres); + lv_label_set_text(lbl_pres_hint, "waiting"); + lv_obj_set_style_text_font(lbl_pres_hint, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_pres_hint, COL_MUTED, 0); + lv_obj_align(lbl_pres_hint, LV_ALIGN_BOTTOM_MID, 0, 2); + + lv_obj_t *p_bot = make_panel(scr, UI_M, UI_BOT_Y, UI_BOT_W, UI_BOT_H); + + lv_obj_t *info = lv_obj_create(p_bot); + lv_obj_set_size(info, UI_INFO_W, UI_BOT_H - 12); + lv_obj_align(info, LV_ALIGN_LEFT_MID, 0, 0); + lv_obj_set_style_bg_opa(info, LV_OPA_TRANSP, 0); + lv_obj_set_style_border_width(info, 0, 0); + lv_obj_set_style_pad_all(info, 0, 0); + lv_obj_clear_flag(info, LV_OBJ_FLAG_SCROLLABLE); + + lbl_state = lv_label_create(info); + lv_label_set_text(lbl_state, "WAIT"); + lv_obj_set_style_text_font(lbl_state, &lv_font_montserrat_14, 0); + lv_obj_set_style_text_color(lbl_state, COL_WARN, 0); + lv_obj_set_width(lbl_state, UI_INFO_W); + lv_label_set_long_mode(lbl_state, LV_LABEL_LONG_CLIP); + lv_obj_align(lbl_state, LV_ALIGN_TOP_LEFT, 0, 0); + + bar_presence = lv_bar_create(info); + lv_obj_set_size(bar_presence, UI_INFO_W - 4, 8); + lv_obj_align(bar_presence, LV_ALIGN_TOP_LEFT, 0, 20); + lv_bar_set_range(bar_presence, 0, 100); + lv_bar_set_value(bar_presence, 0, LV_ANIM_OFF); + lv_obj_set_style_bg_color(bar_presence, COL_ARC_BG, LV_PART_MAIN); + lv_obj_set_style_bg_opa(bar_presence, LV_OPA_COVER, LV_PART_MAIN); + lv_obj_set_style_radius(bar_presence, 4, LV_PART_MAIN); + lv_obj_set_style_bg_color(bar_presence, COL_WARN, LV_PART_INDICATOR); + lv_obj_set_style_radius(bar_presence, 4, LV_PART_INDICATOR); + + lbl_fw = lv_label_create(info); + lv_label_set_text(lbl_fw, "FW ----"); + lv_obj_set_style_text_font(lbl_fw, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_fw, COL_TEXT, 0); + lv_obj_set_width(lbl_fw, UI_INFO_W); + lv_label_set_long_mode(lbl_fw, LV_LABEL_LONG_CLIP); + lv_obj_align(lbl_fw, LV_ALIGN_TOP_LEFT, 0, 34); + + lbl_baud = lv_label_create(info); + lv_label_set_text(lbl_baud, "UART --"); + lv_obj_set_style_text_font(lbl_baud, &lv_font_montserrat_12, 0); + lv_obj_set_style_text_color(lbl_baud, COL_MUTED, 0); + lv_obj_set_width(lbl_baud, UI_INFO_W); + lv_label_set_long_mode(lbl_baud, LV_LABEL_LONG_CLIP); + lv_obj_align(lbl_baud, LV_ALIGN_TOP_LEFT, 0, 48); + + chart = lv_chart_create(p_bot); + lv_obj_set_size(chart, UI_CHART_W, UI_BOT_H - 16); + lv_obj_align(chart, LV_ALIGN_RIGHT_MID, 0, 0); + lv_chart_set_type(chart, LV_CHART_TYPE_LINE); + lv_chart_set_point_count(chart, HISTORY_LEN); + lv_chart_set_range(chart, LV_CHART_AXIS_PRIMARY_Y, 0, DIST_ARC_MAX); + lv_chart_set_range(chart, LV_CHART_AXIS_SECONDARY_Y, 0, 100); + lv_chart_set_update_mode(chart, LV_CHART_UPDATE_MODE_SHIFT); + lv_obj_set_style_bg_color(chart, COL_CHART_BG, 0); + lv_obj_set_style_bg_opa(chart, LV_OPA_COVER, 0); + lv_obj_set_style_border_color(chart, COL_EDGE, 0); + lv_obj_set_style_border_width(chart, 1, 0); + lv_obj_set_style_radius(chart, 8, 0); + lv_obj_set_style_pad_all(chart, 4, 0); + lv_obj_set_style_line_width(chart, 2, LV_PART_ITEMS); + lv_chart_set_div_line_count(chart, 2, 4); + lv_obj_set_style_line_color(chart, COL_EDGE, LV_PART_MAIN); + lv_obj_set_style_line_opa(chart, LV_OPA_40, LV_PART_MAIN); + ser_dist = lv_chart_add_series(chart, COL_DIST, LV_CHART_AXIS_PRIMARY_Y); + ser_pres = lv_chart_add_series(chart, COL_PRES, LV_CHART_AXIS_SECONDARY_Y); + + lv_obj_move_foreground(title); + lv_obj_move_foreground(lbl_uptime); + lv_obj_move_foreground(lbl_status); + lv_obj_move_foreground(led_status); + lv_obj_move_foreground(lbl_hint); +} + +static void refresh_meta(void) { + char buf[48]; + uint32_t up = millis() / 1000; + lv_snprintf(buf, sizeof(buf), "up %02lu:%02lu bl%u", + (unsigned long)(up / 60), (unsigned long)(up % 60), (unsigned)bright_level); + lv_label_set_text(lbl_uptime, buf); + + if (hint_until_ms && (int32_t)(millis() - hint_until_ms) >= 0) { + hint_until_ms = 0; + lv_obj_add_flag(lbl_hint, LV_OBJ_FLAG_HIDDEN); + } + + if (sensor_ok && (millis() - last_ok_ms) < SENSOR_STALE_MS) { + uint32_t age = (millis() - last_ok_ms) / 1000; + lv_snprintf(buf, sizeof(buf), "LIVE %lus", (unsigned long)age); + lv_label_set_text(lbl_status, buf); + lv_led_set_color(led_status, presence ? COL_PRES : COL_OK); + } else if (fw_ok) { + lv_label_set_text(lbl_status, "IDLE"); + lv_led_set_color(led_status, COL_WARN); + } else { + lv_label_set_text(lbl_status, "NO LINK"); + lv_led_set_color(led_status, COL_BAD); + } +} + +static void update_ui(void) { + char buf[40]; + + lv_snprintf(buf, sizeof(buf), "FW %s", fw_version); + lv_label_set_text(lbl_fw, buf); + lv_obj_set_style_text_color(lbl_fw, fw_ok ? COL_TEXT : COL_BAD, 0); + + lv_snprintf(buf, sizeof(buf), "%lu %s", (unsigned long)radar_baud, + energy_mode ? "E" : "S"); + lv_label_set_text(lbl_baud, buf); + + if (!sensor_ok && !fw_ok) { + lv_label_set_text(lbl_state, "NO LINK"); + lv_obj_set_style_text_color(lbl_state, COL_BAD, 0); + lv_label_set_text(lbl_pres_val, "----"); + lv_obj_set_style_text_color(lbl_pres_val, COL_MUTED, 0); + anim_bar(bar_presence, 0); + refresh_meta(); + return; + } + + if (presence) { + lv_label_set_text(lbl_state, "OCCUPIED"); + lv_obj_set_style_text_color(lbl_state, COL_PRES, 0); + lv_label_set_text(lbl_pres_val, "ON"); + lv_obj_set_style_text_color(lbl_pres_val, COL_PRES, 0); + anim_arc(arc_pres, 100); + anim_bar(bar_presence, 100); + lv_obj_set_style_bg_color(bar_presence, COL_PRES, LV_PART_INDICATOR); + if (presence_since_ms) { + uint32_t sec = (millis() - presence_since_ms) / 1000; + lv_snprintf(buf, sizeof(buf), "held %lus", (unsigned long)sec); + lv_label_set_text(lbl_pres_hint, buf); + } + } else { + lv_label_set_text(lbl_state, "CLEAR"); + lv_obj_set_style_text_color(lbl_state, COL_MUTED, 0); + lv_label_set_text(lbl_pres_val, "OFF"); + lv_obj_set_style_text_color(lbl_pres_val, COL_MUTED, 0); + anim_arc(arc_pres, 0); + anim_bar(bar_presence, 0); + lv_obj_set_style_bg_color(bar_presence, COL_MUTED, LV_PART_INDICATOR); + lv_label_set_text(lbl_pres_hint, "no target"); + } + + if (!isnan(disp_dist)) { + lv_color_t dc = dist_color(disp_dist); + lv_snprintf(buf, sizeof(buf), "%.0f", disp_dist); + lv_label_set_text(lbl_dist_val, buf); + lv_obj_set_style_text_color(lbl_dist_val, dc, 0); + lv_obj_set_style_arc_color(arc_dist, dc, LV_PART_INDICATOR); + anim_arc(arc_dist, (int)lroundf(constrain(disp_dist, 0.0f, (float)DIST_ARC_MAX))); + + if (!isnan(min_dist) && !isnan(max_dist)) { + lv_snprintf(buf, sizeof(buf), "%.0f / %.0f", min_dist, max_dist); + lv_label_set_text(lbl_dist_range, buf); + } + } + + uint32_t now = millis(); + if (now - last_chart_ms >= CHART_PUSH_MS) { + last_chart_ms = now; + int32_t d = isnan(disp_dist) ? 0 : (int32_t)lroundf(constrain(disp_dist, 0.0f, (float)DIST_ARC_MAX)); + lv_chart_set_next_value(chart, ser_dist, d); + lv_chart_set_next_value(chart, ser_pres, presence ? 100 : 0); + } + + refresh_meta(); +} + +void setup() { + Serial.begin(115200); + delay(200); + + ledcSetup(0, 5000, 8); + ledcAttachPin(TFT_BL_PIN, 0); + set_backlight(2); + + Serial.println("CYD LVGL LD2420 Radar Dashboard"); + Serial.printf("LVGL %d.%d.%d OT1->GPIO%d RX->GPIO%d\n", + lv_version_major(), lv_version_minor(), lv_version_patch(), + LD2420_RX_PIN, LD2420_TX_PIN); + + lv_init(); + + touchscreenSPI.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS); + touchscreen.begin(touchscreenSPI); + touchscreen.setRotation(2); + + lv_display_t *disp = lv_tft_espi_create(240, 320, draw_buf, sizeof(draw_buf)); + lv_display_set_rotation(disp, LV_DISPLAY_ROTATION_270); + + lv_indev_t *indev = lv_indev_create(); + lv_indev_set_type(indev, LV_INDEV_TYPE_POINTER); + lv_indev_set_read_cb(indev, touchscreen_read); + + create_ui(); + + bool linked = radar_init(); + if (linked) { + char hint[32]; + lv_snprintf(hint, sizeof(hint), "FW %s", fw_version); + show_hint(hint, 2000); + } else { + show_hint("radar no ACK", 2500); + } + update_ui(); +} + +void loop() { + radar_poll(); + + uint32_t now = millis(); + if (now - last_ui_ms >= UI_REFRESH_MS) { + last_ui_ms = now; + update_ui(); + } + + static uint32_t last_meta_ms = 0; + if (now - last_meta_ms >= 1000) { + last_meta_ms = now; + refresh_meta(); + } + + if (now - last_dbg_ms >= 1000) { + last_dbg_ms = now; + Serial.printf("pres=%s dist=%.0f cm FW=%s\n", + presence ? "ON" : "OFF", + isnan(disp_dist) ? -1.0f : disp_dist, + fw_version); + } + + lv_timer_handler(); + lv_tick_inc(5); + delay(5); +}