49 Commits

Author SHA1 Message Date
julian 1cba9f30bc Reverse lights on DO0, Sport + Vehicle screens, per-DDE live data, ECU identification
Firmware / build (push) Successful in 10m49s
- ReverseLight: isolated output DO0 (CH422G OC0 -> PC817 -> NPN sink) drives the
  reverse-lamp relay while the lever is in R on a live bus with ignition on; 10 Hz
  decision confirmed over 200 ms, written through the panel library's expander
  object so the backlight cannot undo it; `reverse status|on|off|force` console,
  default ON (NVS `revlight_en`). Wiki page reverse-lights-output with the wiring.
- Sport screen: BMW-style power + torque gauges (lv_meter on a dial-face image,
  image needle); PNG sources in assets/, tools/png2lvgl.py converter.
- Vehicle: final drive ratio + tyre circumference -> road speed, hp from torque;
  Settings > Vehicle page; `vehicle` console.
- Bench simulation (`sim` console) overlays torque / rpm / shaft on the snapshot.
- EcuIdent: KWP 1A 86 / 1A 80 read once, stored in NVS, shown on Settings >
  Vehicle, passive ECU CHANGED? check; `ecu` console.
- Ignition fallback from the 0x1D2 lever byte on buses without 0x3B4 (Patrol 2).
- Engine data: per-DDE `2C 10` identifier profiles (Patrol 1 vs Patrol 2
  rail 00C2 / boost 003A / battery 002F); DiagProbe liveConfigure().
- Wiki: Patrol 2 captures, vehicles page, obd identifier table per DDE, logs.
2026-10-28 16:46:42 +01:00
julian 8ded9c2a08 Merge origin/main (27 commits from the other machine) with the Engine data screen
Firmware / build (push) Successful in 7m2s
All incoming changes kept as they were. Conflicts resolved by adding the
Engine-data pieces next to them:
- main.cpp: StatusOverlay::tick() and EngineScreen::tick()
- driveline_screen.cpp: both include sets; the old mismatch label stays
  removed (overlay owns it); the Engine data button moves to y 60, left of
  the diff-lock drawing, clear of the overlay band
- CLAUDE.md: Engine data bullet added; DiagProbe paragraph keeps its text
  plus the live-mode sentence
- wiki: all incoming log entries kept, the 2026-10-07 entry appended;
  open-questions #12 keeps the renamed line plus the 2026-10-07 update

Built clean locally (custom_sdkconfig core rebuild).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 11:51:53 +02:00
julian a28cbada59 Engine data screen: live rail, boost, charge-air temp, battery from the DDE
New screen (Engine data button on Driveline) polls the DDE with the
Launch's KWP `2C 10 <id>` reads: 00DF rail (bar = raw x 0.03, verified),
0091 boost (mbar = raw / 8), 16A8 charge-air temp, 0093 battery - the last
three provisional (one engine-off point each), tagged on screen with the
raw value shown for calibration.

DiagProbe live mode: `2C 10 15 E0` once, then the four reads in turn, one
in flight, ~100 ms apart, quiet on the console, paused by the foreign-tester
guard, stops 1.5 s after the screen stops asking. 2C stays forbidden from
the console. CANDriver::transmit gains an echo flag (live frames echoed only
with CANRAW on). Wiki: the three CANNY captures ingested, identifier table
and the no-password decision recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 19:48:00 +02:00
julian 9bfcd99dee Settings: diff-lock row's switch box aligned START - END collapsed its content width and clipped the Inverted switch
Firmware / build (push) Successful in 6m49s
2026-09-29 15:41:19 +02:00
julian b431cdfa16 Diff locks: per-board polarity ('Inverted' switch in the Settings row, 'difflock invert on|off', NVS difflock_inv) - in the car the lock wires carry 12 V while unlocked
Firmware / build (push) Successful in 7m6s
2026-09-29 15:18:23 +02:00
julian 0254bf19e9 Diff-lock drawing: wheelbase -20 %, same square tyres all round, locked axle's tyres filled, no caption text
Firmware / build (push) Successful in 7m5s
2026-09-29 10:53:48 +02:00
julian 01f7501ae7 Diff locks on the Driveline: chassis top view after the user's sketch (steered front wheels, prop shaft, rear axle); locked axle amber with an X on its diff, front-only red, caption
Firmware / build (push) Successful in 6m59s
2026-09-29 10:30:46 +02:00
julian 31ca44187e Diff-lock inputs: DI0 rear / DI1 front via CH422G EXIO0/EXIO5 (bank flipped to input per read), Settings > System switch default OFF, DIFF LOCK pills on the Driveline, 'difflock' console; wiki diff-lock-inputs
Firmware / build (push) Successful in 7m26s
2026-09-29 09:48:57 +02:00
julian f07590bbc5 Remove the deep-sleep feature entirely (user decision): power manager, Settings switch, NVS key, sleep bit in the shared header, wiki page and cheat-sheet entries
Firmware / build (push) Successful in 6m59s
2026-09-28 17:20:54 +02:00
julian 59fae2c219 Sleep: drive and hold the 20 RGB panel lines low before deep sleep (white flickering edges seen on the bench)
Firmware / build (push) Successful in 7m7s
2026-09-28 16:53:16 +02:00
julian 803af7568f Rename Controller A/B -> Main CTRL / Inst. Cluster (user); Sleep when the car is off: Settings switch, deep sleep on quiet CAN + idle screen, CAN RX wake, switch mirrored to the cluster; docs
Firmware / build (push) Successful in 7m22s
2026-09-28 16:38:13 +02:00
julian 7a74c02b20 docs: COMMANDS.md - build, upload, monitor and console cheat-sheet for both controllers
Firmware / build (push) Failing after 6m11s
2026-09-28 10:21:06 +02:00
julian 63d64362e8 No invented data: shared structure starts with nothing valid, cleared on CAN stop and bus silence; DEFAULT_* removed from the shared header
Firmware / build (push) Successful in 7m19s
2026-09-28 09:30:59 +02:00
julian ae9327d91b Status overlay on every screen: Wi-Fi chip top-right, blinking alert banner; Driveline values red on crossed thresholds, ring red on gear mismatch
Firmware / build (push) Successful in 7m12s
2026-09-27 21:40:37 +02:00
julian 7ae1ab726a link: separator in the Controller B update log line; wiki: B update verified end-to-end
Firmware / build (push) Successful in 7m29s
2026-09-27 20:47:35 +02:00
julian 3e86ca3733 Controller B updates from A: link_peer (pairing over the wire, encrypted credential handoff, B status + commands), ESP-NOW receive/unicast, Updates page with two cards; shared header maintenance frames; docs + wiki
Firmware / build (push) Successful in 7m1s
2026-09-27 20:26:44 +02:00
julian 8338e4e300 Wiki: v0.1.7 published, manifest verified off-device
Firmware / build (push) Successful in 5s
2026-09-27 18:29:46 +02:00
julian 8e739fa24e CI: install pioarduino's PlatformIO core fork (upstream core lacks FortranCommon with the pinned SCons on the ESP-IDF build path)
Firmware / build (push) Successful in 7m4s
2026-09-27 18:21:28 +02:00
julian 929fdfa877 Wiki: v0.1.7 release note (display work merged)
Firmware / build (push) Failing after 3m38s
2026-09-27 18:07:01 +02:00
julian 990ba68590 OTA: screen stays on with a progress bar and 'do not switch off' (flash writes no longer blank the panel under XIP); wiki step 4 2026-09-27 18:00:33 +02:00
julian 26e61190f9 Wiki: step 3 verified - OTA download keeps 24 panel frames/s under XIP from PSRAM 2026-09-27 17:48:40 +02:00
julian f69d195e2a display-xip: rebuild core with XIP_FROM_PSRAM + LCD_RGB_ISR_IRAM_SAFE; drop unused IDF components 2026-09-27 17:45:40 +02:00
julian 518358a2ab Correct the record: bounce buffers (10 lines) and 21 MHz clock come from the board header; drop dead ESP_PANEL_LCD_RGB flags; dots = late bounce refills
Firmware / build (push) Successful in 4m3s
2026-09-27 17:08:05 +02:00
julian 5a874ff943 Wiki: dots are sub-frame DMA glitches (panel 24/s while visible); OTA drops panel to 4-8 fps
Firmware / build (push) Successful in 6s
2026-09-27 17:03:36 +02:00
julian 6593abe9f5 Driveline: write labels only on change (idle 9.7 fps -> 0); perf: panel vsync counter + esp_timer reporting
Firmware / build (push) Successful in 4m2s
2026-09-27 16:57:06 +02:00
julian 94c70a572b Wiki: display baseline session analysed (perf-baseline-2026-09-27); Q13 plan amended with step 1b
Firmware / build (push) Successful in 6s
2026-09-27 16:52:11 +02:00
julian bbfa5d9e80 tools/perf_session.py: log PERF lines + typed markers while provoking display symptoms
Firmware / build (push) Successful in 4m10s
2026-09-27 16:44:29 +02:00
julian d3e499efed Add perf console (render fps, flush cost, CPU idle, heap) for the display work; record idle baseline
Firmware / build (push) Successful in 4m8s
2026-09-27 16:43:53 +02:00
julian 43ca6b96ec Wiki: Q13 becomes a must-fix (dots persist, OTA needs on-screen progress); log the review
Firmware / build (push) Successful in 6s
2026-09-27 16:31:21 +02:00
julian 23b7027d40 Wiki: board schematic re-downloaded; VOUT = H8 solder jumper (3V3 default / 5V), 5 V rail budget, SD pins
Firmware / build (push) Successful in 6s
2026-09-27 16:15:07 +02:00
julian 40a21557f0 Wiki: display platform plan (open-questions #13), SquareLine decommissioned
Firmware / build (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 08:29:02 +02:00
julian 34b3fc7ec0 Decommission SquareLine: delete include/ui, theme set in display_init
Firmware / build (push) Successful in 4m1s
include/ui (SquareLine export: ui_init, placeholder screen, helpers, theme
manager, project metadata) is no longer used - every screen is hand-coded.
The one live line, the dark default LVGL theme, moves to display_init.cpp.
Build filter and include path drop include/ui. Comments, CLAUDE.md and the
stale README sections (features, layout, partitions) updated.

Verified on the board (USB, dev): Wi-Fi on/forget/scan/join, dark keyboard
and dialogs, update check + install of v0.1.5 from the screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 08:17:01 +02:00
julian 5d495f8ad1 Wiki: v0.1.5 UX refactor, remembered Wi-Fi, on-screen updates
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 07:55:09 +02:00
julian e68fad73b6 Hand-coded Settings + tabbed Gauge Tuning; remembered Wi-Fi; on-screen updates
Firmware / build (push) Successful in 3m58s
Settings (replaces the SquareLine screen, now deleted): sidebar with
Wi-Fi (switch, status card with failure reasons, networks nearby,
full-screen password page), Updates (installed vs latest, Check, Install
behind a confirm dialog) and System (CAN / link / perf overlay switches,
live link, CAN, memory, uptime).

Gauge Tuning: tabs Tachometer / Coolant gauge / Alerts / Simulation,
56 px -/+ rows with hints and real units, accelerating hold-to-repeat,
per-tab Reset with confirm, save indicator, SIMULATION ON chip, swipe
left to go back.

WiFiManager rewritten without LVGL code: one remembered network (NVS
"wifi"), auto-join at boot, scans only on request, no endless reconnect
(keeps the ESP-NOW channel stable), failure reasons from the disconnect
event, password never logged. Ota gains getStatus()/requestCheck()/
requestInstall() for the screen. CAN/UART switches become setEnabled().
Shared ui_kit (header, buttons, switches, confirm dialog); Montserrat
20/24 enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 07:38:17 +02:00
julian 766019a01e Fix UI freeze/reboots: LVGL pool to PSRAM, dangling SSID buttons, scan policy
Firmware / build (push) Successful in 4m24s
- lv_conf: LVGL widget pool 48 KB internal -> 512 KB PSRAM (LV_MEM_POOL_ALLOC).
  It ran out after a few Settings visits (87% used, 31% frag, 4.5 KB biggest
  block; lv_mem_buf_get() failed in a label draw - decoded backtrace). Also
  frees 48 KB of internal RAM: free 16 -> 69 KB, largest block 7.6 -> 31.7 KB
- lv_conf: LV_ASSERT_HANDLER abort() instead of while(1), which spun inside the
  task holding the LVGL lock and froze the UI + console
- wifi_manager: SSID buttons clear their g_ssid_buttons[] slot on
  LV_EVENT_DELETE (SquareLine deletes the Settings screen on leave; stale
  pointers were lv_obj_del()'d on the next scan). Scan only while the list is
  on screen and not connected - 10 s background scans caused the display dots
- main: `mem` console command (internal heap, PSRAM, LVGL pool)
- docs: board page lessons, open-questions #13/#14, ota-updates, CLAUDE.md, log

Verified: 10 Settings visits + 9 list rebuilds, pool peak 4%, 0 crashes; user
confirms no freeze, no reboot, no dots, swipes better.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 00:32:18 +02:00
julian 842f270398 Wiki sweep for the OTA/display session
Firmware / build (push) Successful in 6s
- ota-updates: status table of every OTA cycle (incl. the 570 B abort and the
  clean failure path), v0.1.3 published/not installed, 'installs are done by the
  running firmware', flicker cause verified, Wi-Fi lost on reboot, console
  without reset, B repo now public
- esp32-s3-touch-lcd-5b: drop the unmeasured ~50 FPS claim, USB serial is
  native CDC with the DTR/RTS reset gotcha, new lessons (flash-write flicker,
  fade stutter, internal RAM, never power the radio off, dual-slot partitions)
- dual-controller-architecture: ESP-NOW/Wi-Fi radio sharing, disconnect(true)
  bug, B updates via A over ESP-NOW
- open-questions #14: Wi-Fi UX redesign, remember network, delete v0.1.0
- CLAUDE.md: same FPS / USB-serial corrections; index + log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 00:05:13 +02:00
julian 29711fa25e CI: skip main builds for tagged or docs-only commits
Firmware / build (push) Successful in 3m56s
A main push now skips itself when its commit already carries a v* tag (the tag
build covers it - release with git push --follow-tags) or when it only changes
wiki/** or *.md. Checked inside the job, so tag builds are never path-filtered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:58:32 +02:00
julian 51fd4a868a OTA: don't abort a download on a momentary connected()==false
Firmware / build (push) Successful in 4m0s
A forced reinstall aborted at 570 B when the TLS client briefly reported
disconnected between records; the retry went through. A drop now only counts
after 2 s without data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:19:12 +02:00
julian eb9cbd985f Display quick fixes: instant screen switches, deferred NVS saves, dark OTA writes, version label
Firmware / build (push) Successful in 4m30s
- screen switches use LV_SCR_LOAD_ANIM_NONE: full-screen fades were re-rendered
  and blended in software every frame and stuttered at 1024x600
- Tunables: NVS write 3 s after the last change or on leaving the Tuning screen
  (Tunables::flush()), not per tap - each flash write flickers the RGB panel
- OTA: backlight off while the image is written, with full-screen notices
  before and after; tunables flushed before any reboot
- firmware version shown bottom-right on every screen (lv_layer_top)
- docs: CLAUDE.md, wiki ota-updates, open-questions #13, log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:00:28 +02:00
julian 0a76cd8c0e Wiki: first OTA update verified end-to-end (dev -> v0.1.1)
Firmware / build (push) Successful in 4m21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 22:49:59 +02:00
julian bb0895674a OTA bring-up fixes: loop-task jobs + PSRAM TLS, ESP-NOW survives Wi-Fi, wifi console
Firmware / build (push) Successful in 4m24s
- ota: internal RAM has 15.9 KB free / 7.6 KB largest block with Wi-Fi up, so
  jobs now run in the loop task (8 KB stack; 3.6 KB headroom measured on
  `ota check`) with mbedtls allocations routed to PSRAM during the job
- wifi_manager: WiFi.disconnect(true) powered the radio off and killed ESP-NOW
  whenever Wi-Fi was used; now disconnect() only. showConnectionResult() waits
  for the LVGL lock and null-checks widgets. New `wifi join|status|off` console
- espnow_link: send() re-initialises ESP-NOW if the driver dropped it
- wiki: ota-updates memory + bugs sections, open-questions #13 (internal RAM),
  log; CLAUDE.md notes

Verified on the board: `wifi join` connects, ESP-NOW 195 sent / 0 failed while
joined, `ota check` verifies v0.1.0's signature on-device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 22:37:08 +02:00
julian f5b7f43e7c Re-enable the Settings Wi-Fi switch at runtime
The SquareLine export has shipped ui_Toggle_Wifi_Switch with LV_STATE_DISABLED
since the first commit, so it ignored every touch. OTA needs Wi-Fi joined, so
clear the state in UIStateManager's sync (survives SquareLine re-exports).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 22:18:18 +02:00
julian 1ec93dc413 Rename signing secret to BMW_NISSAN_FIRMWARE_SIGNING_KEY
Firmware / build (push) Successful in 4m5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 22:05:16 +02:00
julian effa949429 OTA updates for Controller A: dual-slot partitions, signed Gitea releases
- partition table: two 7.9 MB OTA slots, SPIFFS dropped, nvs/otadata offsets
  unchanged (tunables survived the one-time USB flash)
- ota_update.cpp: manual `ota status|check|install|rollback` console; HTTPS
  pull from the public repo's latest release, ECDSA P-256 signature over
  "patrol-a|version|sha256" checked before download, streamed image must match,
  parked gate before download and before the slot switch, 30 s
  confirm-or-rollback (verifyRollbackLater override)
- ota_config.h: server/repo, ISRG Root X1 + Root YR, signing public key
- .gitea/workflows/firmware.yml: main -> rolling unsigned pre-release
  main-latest; v* tag -> signed release (needs secret FIRMWARE_SIGNING_KEY)
- wiki: pages/ota-updates.md (design, decisions, B-over-ESP-NOW plan);
  CLAUDE.md, index, log, open-questions #12 updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 21:59:46 +02:00
julian da4c96903b Clarify self-poll needs no session/security; record Diagnostics-screen plan
- capture proof: Launch used only 1A/2C/22/23 - no 10/27/3E. Self-polling a
  2C live value needs just the define + poll, no session or security seed.
  Corrected the earlier "needs session handshake" wording.
- design decision: active polling (if built) lives behind a password-
  protected Diagnostics screen - authorized-tech gate, manual, refuses with
  a scan tool connected, read-oriented services. open-questions #12.
- wiki: launch-capture + obd-diagnostic-polling tightened; project memory
  added so the capability and guard rails are not re-researched later

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-23 17:06:20 +02:00
julian 6bdf4d43a9 Launch capture: decode rail pressure (service 2C, bar = raw x 0.03)
- capture-with-Launch session: live data on this DDE comes via KWP service
  2C (2C 10 00 DF -> 6C 10 HHLL), not the 22 D1xx identifiers (absent) or
  the session-gated 21 blocks
- rail pressure actual VERIFIED two-point vs the Launch display:
  bar = HHLL x 0.03 (idle ~305, 2500 rpm ~430)
- recipe now generalises to any Launch-visible value; self-poll needs the
  session/define handshake (captured, deferred design decision)
- wiki: sources/launch-capture-2026-09-23.md, obd-diagnostic-polling,
  open-questions #7, index; raw serial capture (~13 MB)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-23 16:48:10 +02:00
julian 61e190b1b9 Diag scans: 22 D1xx refuted, 21 xx session-locked; add diag raw toggle + scanner
- diag probe: `diag raw on|off` console command (mutes CANRAW during scans)
- tools/diag_scan.py: identifier-space sweeper via `diag bmw`
- findings: whole 22 D1xx block NRCs (clipping identifiers wrong for this
  DDE); 21 xx sparse - 21 20 = O_269962, measurement blocks gated behind
  diagnostic session / security access -> Launch capture is the path to
  live data
- wiki: route-b source page + obd-diagnostic-polling updated, raw scan logs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-23 16:02:18 +02:00
julian 7a7398243b Diag day: Route A+B verified live, DTCs read, donor identified as E60 530d
- diag probe: add mode 03 (diag dtc), BMW KWP on 0x6F1 with extended
  addressing (diag ident, diag bmw), read-only service whitelist
  (1A/18/21/22), MAX_PAYLOAD 64->384, full hex+ascii dump of BMW replies
- tools/diag_session.py: one-session probe runner, logs into wiki/raw/
- wiki: Route A results (11 mode-01 PIDs, rpm/coolant cross-checked, mode
  09 silent), Route B verified (0x6F1 [12] -> 0x612), 1A 86 ident with
  VIN prefix WBANC92090 (E60 530d), DTCs P0101/P0113/P0500/P0545/P0030
  (disconnected-sensor swap leftovers), open-questions #2/#7 updated

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-23 12:54:24 +02:00
julian e9fc24778a Gauge drive day: CANNY comparison, cluster signal research, serial tools
Wiki: two new pages - canny-5-3-pico-gauge-drive (why the CANNY's 12V
negative output moved the needles and 3.3V push-pull could not; 2SK3069
low-side stage) and patrol-instrument-cluster (tach 2 ppr + trim -13
calibration, NTC temp sender curve, 20 kHz PWM flutter fix, and the
four-layer steppy-needle diagnosis ending at the cluster's ~150 rpm
count quantization, defeated with adaptive dither on B).

Tools: serial_logger.py (multi-port capture to wiki/raw), serial_cmd.py
(one-shot cfg commands to A), dual_serial_capture.py (bench snapshots),
tach_ramp.py / tach_ramp2.py (synthetic rpm sweeps via cfg override).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-23 11:12:20 +02:00
163 changed files with 582929 additions and 3340 deletions
+179
View File
@@ -0,0 +1,179 @@
name: Firmware
# Main CTRL firmware, built by PlatformIO on every push. Two outputs:
#
# - push to main -> rolling PRE-release `main-latest` (firmware.bin + .elf),
# unsigned, no manifest. For bench testing / USB flashing.
# The device never installs it: it only reads
# /releases/latest, which skips pre-releases, and it
# needs a signed manifest.txt anyway.
# - push tag v* -> the OTA release: firmware.bin + firmware.elf +
# manifest.txt (size, sha256, ECDSA P-256 signature over
# "patrol-a|<tag>|<sha256>"). This is what `ota install`
# on the controller pulls.
#
# Signing key: repo secret BMW_NISSAN_FIRMWARE_SIGNING_KEY (PEM, EC P-256). Its public
# half is compiled into the firmware (include/config/ota_config.h) and kept in
# tools/ota/firmware_signing_pub.pem, which this job uses to self-check the
# signature before publishing. See wiki/pages/ota-updates.md.
#
# Releases go through the Gitea API with plain curl (actions/upload-artifact
# is unreliable on this runner - same pattern as parking_solution).
#
# A main push skips itself (step "Skip?") when (a) the commit already carries a
# v* tag - the tag build covers it; release with ONE push so the tag exists
# when this runs: git push --follow-tags origin main - or (b) it only
# changes docs (wiki/**, *.md). Done in-job rather than with paths-ignore so a
# tag build can never be skipped by a path filter. Tag builds always run.
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Skip?
env:
BEFORE: ${{ github.event.before }}
run: |
SKIP=false
if [ "${GITHUB_REF#refs/tags/}" = "${GITHUB_REF}" ] && [ "${GITHUB_EVENT_NAME}" = "push" ]; then
# (a) already tagged v* ? (annotated tags list their commit as <tag>^{})
if git ls-remote --tags origin 'v*' | grep -q "^${GITHUB_SHA}"; then
echo "commit ${GITHUB_SHA:0:7} is tagged - the tag build covers it"; SKIP=true
# (b) docs only? Needs the previous head; a new branch / force push just builds.
elif [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] &&
git fetch -q --depth=1 origin "$BEFORE" 2>/dev/null; then
CHANGED=$(git diff --name-only "$BEFORE" "$GITHUB_SHA")
echo "changed files:"; echo "$CHANGED"
if [ -n "$CHANGED" ] && ! echo "$CHANGED" | grep -qvE '^wiki/|\.md$'; then
echo "docs-only change - no firmware build"; SKIP=true
fi
fi
fi
echo "SKIP=${SKIP}" >> "$GITHUB_ENV"
- name: Version
if: env.SKIP != 'true'
run: |
if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
VERSION="${GITHUB_REF_NAME}"
else
VERSION="main-${GITHUB_SHA:0:7}"
fi
case "$VERSION" in *[!A-Za-z0-9._-]*) echo "::error::bad version '$VERSION'"; exit 1;; esac
[ ${#VERSION} -lt 32 ] || { echo "::error::version too long"; exit 1; }
echo "VERSION=${VERSION}" >> "$GITHUB_ENV"
echo "version: ${VERSION}"
- name: Cache PlatformIO
if: env.SKIP != 'true'
uses: actions/cache@v4
with:
path: |
~/.platformio/packages
~/.platformio/platforms
.pio/libdeps
key: pio-${{ hashFiles('platformio.ini') }}
# pioarduino's fork of the PlatformIO core, NOT upstream: the platform pins
# its own SCons 4.8.1 without the Fortran tools, and since the core rebuild
# (custom_sdkconfig, v0.1.7) the ESP-IDF build path is exercised, where the
# upstream core imports SCons.Tool.FortranCommon and dies
# ("ModuleNotFoundError: No module named 'SCons.Tool.FortranCommon'",
# first seen on the v0.1.7 tag build). The pin mirrors
# platform-espressif32/builder/penv_setup.py :: python_deps["platformio"].
- name: Install PlatformIO (pioarduino core)
if: env.SKIP != 'true'
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
uv tool install "https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.18.zip"
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
pio --version
- name: Build
if: env.SKIP != 'true'
run: |
export PLATFORMIO_BUILD_FLAGS="-DFW_VERSION=\\\"${VERSION}\\\""
pio run
mkdir -p dist
cp .pio/build/waveshare_esp32_s3_lcd_5b/firmware.bin dist/
cp .pio/build/waveshare_esp32_s3_lcd_5b/firmware.elf dist/
grep -q "${VERSION}" dist/firmware.bin || { echo "::error::FW_VERSION not baked into the image"; exit 1; }
ls -la dist/
- name: Sign + manifest (tags only)
if: env.SKIP != 'true' && startsWith(github.ref, 'refs/tags/')
env:
BMW_NISSAN_FIRMWARE_SIGNING_KEY: ${{ secrets.BMW_NISSAN_FIRMWARE_SIGNING_KEY }}
run: |
set -e
[ -n "$BMW_NISSAN_FIRMWARE_SIGNING_KEY" ] || { echo "::error::secret BMW_NISSAN_FIRMWARE_SIGNING_KEY is not set"; exit 1; }
SHA=$(sha256sum dist/firmware.bin | cut -d' ' -f1)
SIZE=$(stat -c%s dist/firmware.bin)
printf '%s' "patrol-a|${VERSION}|${SHA}" > stmt.txt
umask 077
printf '%s\n' "$BMW_NISSAN_FIRMWARE_SIGNING_KEY" > key.pem
openssl dgst -sha256 -sign key.pem -out sig.der stmt.txt
rm -f key.pem
# Self-check against the public key the firmware carries.
openssl dgst -sha256 -verify tools/ota/firmware_signing_pub.pem -signature sig.der stmt.txt
SIG=$(od -An -v -tx1 sig.der | tr -d ' \n')
printf 'target=patrol-a\nversion=%s\nsize=%s\nsha256=%s\nsig=%s\n' \
"$VERSION" "$SIZE" "$SHA" "$SIG" > dist/manifest.txt
cat dist/manifest.txt
- name: Publish release
if: env.SKIP != 'true'
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.api_url }}
REPO: ${{ github.repository }}
run: |
set -e
auth="Authorization: token ${TOKEN}"
if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
TAG="${GITHUB_REF_NAME}"
PRE=false
NAME="Main CTRL ${TAG}"
BODY="Signed OTA release. Install on the controller with \`ota install\` (parked, Wi-Fi joined)."
else
TAG="main-latest"
PRE=true
NAME="Main CTRL main build"
BODY="Unsigned build of main @ ${GITHUB_SHA}. Rolling - overwritten each push. Not installable over OTA; flash over USB for bench tests."
# Rolling: drop the previous release and its tag, recreate at this commit.
OLD=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
if [ -n "$OLD" ]; then
curl -sS -X DELETE -H "$auth" "${API}/repos/${REPO}/releases/${OLD}" || true
curl -sS -X DELETE -H "$auth" "${API}/repos/${REPO}/git/refs/tags/${TAG}" || true
fi
fi
REL=$(curl -sS -X POST -H "$auth" -H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG}\",\"target_commitish\":\"${GITHUB_SHA}\",\"name\":\"${NAME}\",\"body\":\"${BODY}\",\"draft\":false,\"prerelease\":${PRE}}" \
"${API}/repos/${REPO}/releases" || true)
REL_ID=$(printf '%s' "$REL" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
if [ -z "$REL_ID" ]; then
REL_ID=$(curl -sS -H "$auth" "${API}/repos/${REPO}/releases/tags/${TAG}" \
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2 || true)
fi
[ -n "$REL_ID" ] || { echo "::error::could not create release: $REL"; exit 1; }
echo "release id: ${REL_ID}"
for f in dist/*; do
name=$(basename "$f")
echo "uploading ${name}"
code=$(curl -sS -o /tmp/up.json -w '%{http_code}' -X POST -H "$auth" \
-H "Content-Type: application/octet-stream" --data-binary @"${f}" \
"${API}/repos/${REPO}/releases/${REL_ID}/assets?name=${name}")
[ "$code" = "201" ] || { echo "::error::upload ${name} failed (HTTP ${code}): $(cat /tmp/up.json)"; exit 1; }
done
echo "published ${TAG}"
+6
View File
@@ -25,3 +25,9 @@ Thumbs.db
ESP32-S3-Touch-LCD-5-Demo/
# Excel lock/temp files (created while a spreadsheet is open)
~$*
# pioarduino custom_sdkconfig build artefacts (regenerated on every core rebuild)
.dummy/
managed_components/
sdkconfig.defaults
sdkconfig.waveshare_esp32_s3_lcd_5b
+93 -95
View File
@@ -4,14 +4,16 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
Automotive display controller for **Waveshare ESP32-S3-Touch-LCD-5B** (1024x600 RGB LCD). This is a dual-controller system where Controller A (this ESP32-S3-LCD-5B) communicates automotive sensor data via UART to Controller B (ESP32-S3-LCD-1.3).
Automotive display controller for **Waveshare ESP32-S3-Touch-LCD-5B** (1024x600 RGB LCD). This is a dual-controller system where Main CTRL (this ESP32-S3-LCD-5B) communicates automotive sensor data via UART to Inst. Cluster (ESP32-S3-LCD-1.3).
**Hardware**: ESP32-S3 dual-core @ 240MHz, 16MB Flash, 8MB OPI PSRAM, 5-inch capacitive touch LCD
**Key Features**: WiFi scanning, UART data transmission @ 5Hz, debug metrics (FPS/CPU), NVS settings persistence, LVGL 8.4.0 UI (SquareLine Studio exports)
**Key Features**: CAN decode, link to B (UART + ESP-NOW @ 5 Hz), remembered Wi-Fi + on-screen OTA updates, gauge tuning, NVS settings persistence, LVGL 8.4.0 UI (hand-coded screens)
## Build & Development Commands
The complete cheat-sheet for BOTH controllers (build, upload, monitor, every console command, pairing, releasing) is `docs/COMMANDS.md`. Keep it current when a command changes.
### PlatformIO CLI
```bash
@@ -54,7 +56,7 @@ Use PlatformIO extension toolbar:
The application uses **dual-core architecture** to maximize performance:
- **Core 1** (Arduino core): LVGL rendering task (Priority 2)
- UI rendering at ~50 FPS @ 1024x600 resolution
- UI rendering @ 1024x600 (real render FPS never measured - the Debug "FPS" counts loop() passes)
- Touch input handling
- CPU load ~80% under normal operation
@@ -74,16 +76,32 @@ The project follows a clean, organized structure with logical separation of conc
src/
main.cpp # Main application logic only
modules/
wifi_manager.cpp # WiFi scanning and connection
wifi_manager.cpp # Wi-Fi: one remembered network, scans on request (no LVGL code)
settings_screen.cpp # Hand-coded Settings screen: Wi-Fi / Updates / System / Vehicle (swipe left from Driveline)
ui_kit.cpp # Shared look for hand-coded screens: header, buttons, switches, confirm dialog
uart_manager.cpp # Link transmitter: v2 DATA/CONFIG frames on UART1 + ESP-NOW
tunables.cpp # Gauge calibration + alert thresholds (NVS, 'cfg' serial console)
espnow_link.cpp # ESP-NOW broadcast leg of the link
tuning_screen.cpp # Hand-coded LVGL Gauge Tuning screen (swipe right from Driveline)
tuning_screen.cpp # Hand-coded Gauge Tuning screen, 4 tabs (swipe right from Driveline)
diag_probe.cpp # On-demand OBD-II requests ('diag' console) - the ONLY CAN transmitter
perf_monitor.cpp # 'perf' console: render fps, flush cost, LVGL/CPU idle, heap (display experiments)
ota_update.cpp # Manual firmware updates from Gitea releases ('ota' console)
link_peer.cpp # Inst. Cluster over the link: its STATUS frames, 'link pair' (key over the wire), encrypted credential handoff, B's updates ('link' console)
status_overlay.cpp # lv_layer_top() on EVERY screen: Wi-Fi chip top-right, blinking red / steady amber alert banner top-centre
diff_locks.cpp # Diff-lock inputs DI0 rear / DI1 front via CH422G EXIO0/EXIO5 ('difflock' console, Settings switch, default OFF)
reverse_light.cpp # Reverse-light relay on isolated output DO0 (CH422G OC0): follows the lever in R ('reverse' console, default ON)
settings_manager.cpp # NVS persistent storage
ui_state_manager.cpp # UI synchronization logic
ui_state_manager.cpp # Debug flag (performance overlay, sent to B)
display_init.cpp # Display initialization; boots into DrivelineScreen
driveline_screen.cpp # Hand-coded LVGL boot screen (gear, temps, rpm, status)
engine_screen.cpp # Live DDE values: rail, boost, charge-air temp, battery (Engine data button)
sport_screen.cpp # BMW-style Sport displays: torque + power gauges (lv_meter), Sport button on Driveline
vehicle.cpp # Final drive ratio + tyre circumference -> road speed; hp from torque x rpm ('vehicle' console, Settings > Vehicle)
bench_sim.cpp # 'sim' console: bench torque / rpm / output shaft overlaid on the driveline snapshot (never saved, off at boot)
ecu_ident.cpp # Which DDE this board is on: KWP ident read ONCE via DiagProbe, stored in NVS, UNKNOWN ECU until then ('ecu' console, Settings > Vehicle)
assets/
needle_img.c # Sport needle image (generated by tools/png2lvgl.py from assets/needle.png - never edit by hand)
dial_img.c # Sport dial face (generated from assets/dial.png - never edit by hand)
drivers/
can_driver.cpp # CAN Bus driver (TWAI)
@@ -96,22 +114,18 @@ include/
can_driver.h # CAN Bus driver interface
protocol/
automotive_data.h # UART protocol and CAN ID mappings
ui/
ui*.c/h # SquareLine Studio generated UI files
```
**src/main.cpp** (~1530 lines)
- Main application logic, event handlers, FreeRTOS task implementations
- WiFi state machine: `wifiTask()` on Core 0 with async scanning
- UART state machine: `uartTask()` on Core 0 with periodic transmission
- Settings synchronization: `applySavedStatesToUI()` syncs toggle states when Settings screen loads
- Thread-safe UI updates via `lvgl_port_lock()`/`unlock()`
- Console command routing (`cfg`, `diag`, `ota`, `wifi`, `mem`, `perf`, `link`, `difflock`, `reverse`, `vehicle`, `sim`, `ecu`), setup order, `loop()` ticks for every screen
**include/protocol/automotive_data.h**
- **Shared with Controller B, must stay byte-identical in both repos.** Protocol v2 (2026-09-21).
- **Shared with Inst. Cluster, must stay byte-identical in both repos.** Protocol v2 (2026-09-21).
- `automotive_data_t` (DATA payload): gear lever + target/engaged nibbles, rpm, 3 temperatures, battery, alert bitmap, valid flags
- `link_config_t` (CONFIG payload): Patrol gauge calibration + alert thresholds, pushed A → B
- Frame: `0xAA | version | type | length | payload | XOR | 0x55`; helpers `frame_build()` / `frame_parse()`
- Maintenance frames (2026-09-27, `PACKET_VERSION` unchanged): `STATUS` 0x03 B → A, `PAIR` 0x04 A → B **wire only**, `SECURE` 0x05 A → B (AES-256-GCM, `include/protocol/link_secure.h` - shared and byte-identical too). `PACKET_MAX_PAYLOAD` is 160
- Spec: `docs/UART_PROTOCOL.md`
- **BMW CAN Bus ID mappings**: 11-bit PT-CAN IDs verified live on the swap bus (evidence: `wiki/pages/can-id-candidates.md`)
- UART config: 115200 baud on GPIO 44 (TX) / 43 (RX, unused) — leaves the board via the SP3485 RS485 transceiver
@@ -133,42 +147,25 @@ include/
- LVGL 8.4.0 configuration file
- Memory settings, theme configuration, widget enables
**include/ui/** directory (SquareLine Studio exports)
- `ui_Settings_Screen.c/h`: WiFi, UART, CAN Bus, Debug toggle switches and containers. Its right-swipe calls `app_show_driveline()` (C entry point in `driveline_screen.cpp`)
- The SquareLine **Home screen was removed on 2026-09-21** (its meters module too). `ui_init()` loads an empty placeholder; `display_init.cpp` then shows the Driveline screen. If SquareLine re-exports a Home screen, delete it from the SquareLine project — do not wire it back in
- External UI references: `uic_Toggle_Wifi_Switch`, `uic_Toggle_UART_Switch`, `uic_Toggle_CAN_Bus_Switch`, `uic_Toggle_Debug_Switch`, `uic_Wifi_Container`, `uic_Settings_Loading_Container`, `uic_Device_State_Container`
- Event handlers: `onWifiToggle()`, `onUARTToggle()`, `onCANBusToggle()`, `onDebugToggle()`
- **Important**: SquareLine Studio exports to `include/ui/` directory to avoid overwriting custom code in `src/`
**UI**: every screen is hand-coded in `src/modules` (see Screens). SquareLine Studio was decommissioned on 2026-09-27 (`include/ui/` deleted); the LVGL theme is set in `display_init.cpp`. Don't reintroduce a UI generator. **Image assets** (2026-10-13): source PNGs and their editable `.pcraft` files live in `assets/`, drawn with PhotoCraft (open-source Photoshop clone, installed portable with an MCP server `photocraft` registered in Claude Code - headless engine, file root `~/projects`); `python tools/png2lvgl.py <png> src/assets/<name>.c <name>` turns a PNG into an LVGL 8 `LV_IMG_CF_TRUE_COLOR_ALPHA` C array (needs Pillow). Declare them `extern "C" { LV_IMG_DECLARE(name); }` in C++ - the generated file is C.
### NVS Persistent Storage
Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Namespace: "settings"
- Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en` (boolean values)
- Keys: `wifi_en`, `uart_en`, `can_en`, `debug_en`, `difflock_en`, `difflock_inv`, `revlight_en` (boolean values); `final_x100`, `tyre_mm` (uint16, `Vehicle`, written 3 s after the last edit or on leaving Settings); `ecu_id86`, `ecu_id80` (blobs, `EcuIdent`: the DDE's raw KWP `1A 86` / `1A 80` identification payloads, written once when first read, removed by Re-read ECU / `ecu forget`)
- Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()`
- Namespace "wifi": `ssid`, `pass` - the one remembered network (`WiFiManager`); the password is never printed
### WiFi Architecture
**State Machine**: `WIFI_STATE_OFF` → `WIFI_STATE_SCANNING` → `WIFI_STATE_SCAN_COMPLETE` → `WIFI_STATE_CONNECTED`
`WiFiManager` (`wifi_manager.cpp`) owns **no LVGL objects**: the Settings screen polls `getStatus()` / `getNetworks()` and calls `setEnabled()`, `requestScan()`, `connect()`, `connectSaved()`, `forget()`. All radio work runs in `wifiTask()` (Core 0) from a command queue.
**Task Communication**:
- Main thread → WiFi task: Via `g_wifi_event_queue` (FreeRTOS queue)
- Event types: `WIFI_UI_EVENT_TOGGLE_ON/OFF`, `WIFI_UI_EVENT_SCAN_START`, `WIFI_UI_EVENT_CONNECT`, `WIFI_UI_EVENT_DISCONNECT`
- Shared data protection: `g_wifi_mutex` (FreeRTOS semaphore) guards `g_scanned_networks[]` array
**Dynamic SSID Buttons**:
- WiFi scan results create dynamically-generated LVGL buttons (`lv_btn_create()` in `updateSSIDList()`)
- Button array: `g_ssid_buttons[WIFI_SCAN_MAX_NETWORKS]` (max 20 networks)
- Each button stores network index in user data: `lv_obj_set_user_data(btn, (void*)(intptr_t)i)`
- Click handler: `onSSIDButtonClick()` → shows password entry UI (keyboard + text area) for secured networks, or connects directly for open networks
**Connection Flow**:
1. User clicks SSID button → `onSSIDButtonClick()`
2. If secured: Show `uic_Wifi_Passkey_TB` (password text area) + `uic_Keyboard`
3. User enters password → `onKeyboardEvent()` (LV_EVENT_READY)
4. Allocate `wifi_credentials_t`, send `WIFI_UI_EVENT_CONNECT` to WiFi task
5. WiFi task: `WiFi.begin(ssid, password)` with 10-second timeout
6. Result: `showConnectionResult()` updates UI with success/failure
- **One remembered network** (NVS namespace `wifi`), saved after a successful join, joined automatically ~3 s after boot when Wi-Fi is on (verified 2026-09-27)
- **Scans only on request** (Wi-Fi page opened while not connected, or the Scan button) - background scans every 10 s caused display glitches and hop the radio ESP-NOW uses
- **No endless reconnect**: `setAutoReconnect(false)`; one attempt at boot, one retry after a drop, then idle back on `ESPNOW_CHANNEL`
- Failure reasons come from the STA_DISCONNECTED event (wrong password, not in range, ...) and show on the screen
- Console: `wifi status | join <ssid> [pass] | forget | scan | on | off`
### UART Architecture
@@ -205,7 +202,8 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- `0x1A2` [bytes 0-1] → Turbine speed
- `0x0AA` [bytes 4-5] → Engine RPM (× 0.25); [byte 3] pedal position
- `0x0A8` [bytes 1-2] → Available engine torque
- `0x3B4` [12-bit LE × 0.015] → Battery voltage; [byte 2 low nibble] ignition
- `0x3B4` [12-bit LE × 0.015] → Battery voltage; [byte 2 low nibble] ignition. **Patrol 1 only**: Patrol 2's bus has no 0x3B4 (nor 0x332 / 0x3B3; captures 2026-10-18), so while no 0x3B4 has been seen for 10 s `ignition_on` follows the **0x1D2 lever byte** (a P/R/N/D code = key on, `0xF0` = key off; flips within one 200 ms frame, verified on the captures). `driveline_t.ignition_src` says which one decided; the CAN driver logs each change
- Different DDEs broadcast the same frames: the two Patrols' DDEs (part numbers 7796678 / 2006 vs 7794904 / 2004) were byte-for-byte identical on every ID above. Setup differences come from **which other modules are on the bus** - adapt by presence of frames, never by ECU identity for anything broadcast (the identity is a label, see `EcuIdent`; one row per setup in wiki `vehicles`). **The one exception is diagnostic live data**: the KWP `2C 10 <id>` identifiers are addresses inside each DDE's software - Patrol 1's set read junk on Patrol 2 (2026-10-18) - so the Engine data screen selects its identifier set by the identified part number (`PROFILES[]` in `engine_screen.cpp`)
**Task Flow**:
- `canTask()` runs on Core 0 with Priority 1
@@ -222,32 +220,56 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
### Tunables (gauge calibration, alert thresholds)
`src/modules/tunables.cpp` owns `link_config_t`: tach pulses/rev + trim + clamps, coolant PWM frequency + duty law + min temp, per-output enables, a bench override (force rpm / duty), and the alert thresholds. Stored as an NVS blob (namespace `tunables`). Edited over the USB serial console: `cfg show`, `cfg set <name> <value>`, `cfg override rpm <n> | duty <n> | both <rpm> <duty> | off`, `cfg reset`. Every change bumps `cfg_version`, which makes the UART task push a CONFIG frame. Overrides are pushed but never saved. The **Gauge Tuning screen** (`src/modules/tuning_screen.cpp`, hand-coded like the driveline screen so SquareLine exports cannot clobber it; Home → swipe right → Driveline → swipe right → Tuning) edits the same values with −/+ buttons, enable switches, and an override panel with RPM and duty sliders. Overrides are never written to NVS (`save()` strips them).
`src/modules/tunables.cpp` owns `link_config_t`: tach pulses/rev + trim + clamps, coolant PWM frequency + duty law + min temp, per-output enables, a bench override (force rpm / duty), and the alert thresholds. Stored as an NVS blob (namespace `tunables`), written 3 s after the last change or on leaving the Tuning screen (`Tunables::flush()`, `isDirty()` drives the screen's save indicator) - every flash write flickers the RGB panel, so no write per tap. Edited over the USB serial console: `cfg show`, `cfg set <name> <value>`, `cfg override rpm <n> | duty <n> | both <rpm> <duty> | off`, `cfg reset`. Every change bumps `cfg_version`, which makes the UART task push a CONFIG frame. Overrides are pushed but never saved. The **Gauge Tuning screen** (`src/modules/tuning_screen.cpp`, see Screens) edits the same values with −/+ buttons, enable switches, and a Simulation tab with RPM and duty sliders. Overrides are never written to NVS (`save()` strips them).
### Diagnostic probe (`diag` console)
`src/modules/diag_probe.cpp` is the only code allowed to call `CANDriver::transmit()`. It sends single OBD-II requests on `0x7DF` and reassembles ISO-TP replies from `0x7E8..0x7EF`: `diag pids` (supported-PID bitmap scan), `diag pid <hex>`, `diag vin`, `diag ecu`, `diag status`. One request in flight, single-shot frames, refused for 3 s after any foreign tester frame (`0x7DF`, `0x7E0-7`, `0x6F1`), services 01/09 only. Transmitted frames are echoed as `CANTX,` lines in the same format as `CANRAW,`. Console lines that `cfg` does not recognise are passed to it via `Tunables::setExtraCommandHandler()`. Background and test procedure: `wiki/pages/obd-diagnostic-polling.md`.
`src/modules/diag_probe.cpp` is the only code allowed to call `CANDriver::transmit()`. It sends single diagnostic requests and reassembles the ISO-TP replies, on two routes: generic OBD-II on `0x7DF` (replies `0x7E8..0x7EF`) and BMW-addressed KWP2000 on `0x6F1` with target byte (replies `0x600`+addr, extended addressing). Commands: `diag pids` (supported-PID bitmap scan), `diag pid <hex>`, `diag dtc` (mode 03), `diag vin`, `diag ecu`, `diag ident [addr]` (KWP `1A 80`), `diag bmw <addr> <hex...>` (raw, whitelisted), `diag raw on|off` (CANRAW mute for scans), `diag status`. **Live mode** (`liveConfigure()` / `liveKeepAlive()` / `liveStop()` / `liveValue()`, used by the Engine data screen): the identifier set installed by the screen for the identified DDE (`live_set_t`: optional one-time define + one `2C 10 <id>` per slot, 0 = never asked; Patrol 1: define `15E0`, then `00DF/0091/16A8/0093`; Patrol 2: rail `00C2`, boost `003A`, battery `002F`, no charge-air temp yet), polled in turn, one in flight, ~100 ms apart, quiet on the console (CANTX echoed only with CANRAW on), paused by the tester guard; nothing is asked until a set is installed; `2C` is never allowed from the console. One request in flight, single-shot frames, refused for 3 s after any foreign tester frame (`0x7DF`, `0x7E0-7`, `0x6F1`); read-only services only — generic 01/03/09, BMW `1A`/`18`/`21`/`22` (whitelist enforced in `sendBmwRequest()`), never session control or writes. Transmitted frames are echoed as `CANTX,` lines in the same format as `CANRAW,`. Console lines that `cfg` does not recognise are passed to it via `Tunables::setExtraCommandHandler()`. Background and test procedure: `wiki/pages/obd-diagnostic-polling.md`. **Identification hooks (2026-10-18)**: `canSendNow()` (the guards without the console refusal lines), `requestIdent(sub)` (`1A 86` / `1A 80` to the DDE) and `setIdentHandler(cb)` - the handler gets every complete `5A xx` payload the DDE puts on 0x612, from our own request (`ours`) or reassembled **passively** from another tester's exchange (the Launch re-reads `1A 80` every ~270 ms; we see the DDE's frames without sending anything). Used by `EcuIdent` only; it is still DiagProbe doing the transmitting.
### OTA updates (`ota` console)
`src/modules/ota_update.cpp` pulls signed firmware from this repo's Gitea releases (`include/config/ota_config.h`: server, repo, Let's Encrypt roots, signing public key). Manual only: Settings → Updates (Check, then Install behind a confirm dialog; verified end-to-end from the screen 2026-09-27) or the console `ota status | check | install [force] | rollback`. `Ota::getStatus()` gives the screen a phase + latest tag + failure reason. Install is refused unless parked (engine off, shaft still, lever not in a drive gear; silent bus = parked), checked before download and again before the slot switch. The manifest's ECDSA P-256 signature over `patrol-a|version|sha256` is checked before download; the streamed image must match that sha256. `verifyRollbackLater()` is overridden so a new image stays pending until `Ota::tick()` confirms it after 30 s - a reset before that rolls back. CI: `.gitea/workflows/firmware.yml` (push `main` -> rolling unsigned pre-release `main-latest`; tag `v*` -> signed release, needs repo secret `BMW_NISSAN_FIRMWARE_SIGNING_KEY`). CI installs **pioarduino's fork of the PlatformIO core** (v6.1.18 zip, same pin as the platform's `penv_setup.py`), not upstream `platformio`: with `custom_sdkconfig` the build goes through the ESP-IDF path, where the upstream core imports `SCons.Tool.FortranCommon` that pioarduino's SCons 4.8.1 does not ship. The core rebuild makes the first CI build after a `platformio.ini` change ~20 min (esp-idf download + rebuild), cached afterwards. Release with one push so only the tag build runs: `git tag -a vX.Y.Z -m "..." && git push --follow-tags origin main` (a main push skips itself when its commit is tagged, or when it only touches `wiki/**` / `*.md`). Never put secrets in firmware source - the repo and its release binaries are public. Jobs run inside the loop task (8 KB stack) with mbedtls routed to PSRAM - internal RAM is too tight for a TLS task (15.9 KB free, largest block 7.6 KB with Wi-Fi up). Wi-Fi is joined on the Settings screen (remembered) or with `wifi join`. Details: `wiki/pages/ota-updates.md`.
### Performance monitor (`perf` console)
`src/modules/perf_monitor.cpp` hooks the LVGL port (`monitor_cb` per rendered frame, a timer around `drawBitmap()` in `flush_callback`) and reads FreeRTOS run-time stats. `perf` prints one `PERF,` CSV line (ts, fps, avg/max ms per frame, kpx per frame, ms per second spent copying into the PSRAM framebuffer, LVGL idle %, core 0/1 idle %, internal free/largest, PSRAM free, **panel vsync/s, longest vsync gap in µs**); `perf on [sec]` prints one every few seconds (from an esp_timer, so it keeps running while the OTA job blocks `loop()`); `perf off`. The vsync columns come from the RGB panel's refresh-finished interrupt (attached in `lvgl_v8_port.cpp` when tearing-avoidance is off): healthy = ~24/s with a 41.5 ms gap; a DMA underrun/restart (flicker, dots) stretches the gap to two frames or more - this is the direct measure for the display work in wiki open-questions #13. Idle Driveline baseline (bench, 2026-09-27, after the `setText()` fix): 0 fps rendered, 0 ms/s flushes, LVGL idle 96 %, core 1 idle 96 % (before the fix: 9.7 fps, 30 ms/frame, 52 ms/s, 68 % / 66 % - the tick re-set every label at 10 Hz). Rule for every screen `tick()`: only write a label or style when the value changed (`lv_label_set_text()` and style setters invalidate even for identical values).
### ESP-NOW link
`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association (it no longer calls `WiFi.mode(WIFI_OFF)`). If Wi-Fi joins an AP the channel follows the AP; B hops to find it.
`src/modules/espnow_link.cpp` broadcasts every frame on Wi-Fi channel `ESPNOW_CHANNEL` (1). The radio stays in STA mode permanently — `WiFiManager`'s "off" only stops scanning/association. Never call `WiFi.disconnect(true)` or `WiFi.mode(WIFI_OFF)`: powering the radio off de-initialises ESP-NOW (`send()` re-inits it as a safety net). If Wi-Fi joins an AP the channel follows the AP; B hops to find it. Since 2026-09-27 it also receives (`setReceiveHandler()`, runs in the Wi-Fi task - copy and return) and unicasts to one MAC (`sendTo()`, plain peer added on first use); both are used by `LinkPeer` only.
### UI State Synchronization
### Inst. Cluster over the link (`link` console)
**Problem**: SquareLine Studio screens get destroyed/recreated when swiping between screens, losing runtime state.
`src/modules/link_peer.cpp` keeps B's last `STATUS` frame (version, update phase, progress, flags; "not heard" after 15 s), owns the pairing key (NVS `linkpeer`) and drives B's updater. `link pair` generates a 32-byte key and sends it **three times over UART1 only** (`UARTManager::sendWire()`, never ESP-NOW - both repos are public, this is the one secret); B confirms with `key_fp` in its next STATUS. `tick()` pushes the remembered Wi-Fi network to B in an encrypted `SECURE` frame whenever B lacks it or it changed (hash-compared, ≥ 15 s apart; `WiFiManager::getSavedCredentials()` exists for this alone - never print the password), and a FORGET when A forgets its network. `requestCheck()` / `requestInstall()` (Settings → Updates, Inst. Cluster card) require: B heard, paired with *this* key, B has credentials, B not busy, A on Wi-Fi (same AP as B ⇒ same channel ⇒ progress frames arrive), and for install `Ota::isParked()`. Console: `link status | pair | unpair | creds | ota check | ota install [force] | ota rollback`. Design + procedure: B's wiki `controller-b-ota`.
**Solution**: `applySavedStatesToUI()` function (called continuously in `loop()`)
- Detects when Settings screen loads by checking if `uic_Toggle_Wifi_Switch != NULL`
- Tracks screen instance via `g_last_synced_screen` pointer to prevent redundant syncing
- Syncs toggle switches with actual service states: `g_wifi_state`, `g_uart_state`, `g_debug_enabled`
- Shows loading spinner during sync for smooth UX
### Diff-lock inputs (`difflock` console)
**Screens**: Driveline (boot, hand-coded) ← swipe left → Settings (SquareLine); Driveline → swipe right → Gauge Tuning (hand-coded).
`src/modules/diff_locks.cpp` reads the Patrol's two diff-lock signals (+12 V = locked) on the isolated inputs: DI0 = rear, DI1 = front, `DI_COM` to vehicle ground. The PC814 outputs reach the ESP32 only through the CH422G (DI0 = EXIO0, DI1 = EXIO5, active LOW), and the CH422G's IO0-7 are one bank, all in or all out - the same bank drives touch reset (EXIO1), backlight (EXIO2) and LCD reset (EXIO3). Each poll (4 Hz, under the LVGL lock so no touch read shares the bus) writes WR_SET input (0x24 <- 0x00), reads 0x26, and writes output back (0x01), restore retried; the chip keeps its output latch. Raw I2C on host 0 (legacy driver, as the panel library), never the library's `enableAllIO_Input()` (it sleeps 2 ms with the bank floating). A state counts after two equal reads. Polarity is a per-board setting (`difflock_inv`, the "Inverted" switch in the same Settings row, `difflock invert on|off`): in the car the lock wires carry 12 V while UNLOCKED, so the car board needs it on, the bench (12 V = locked) needs it off. Behind the Settings → System switch, default OFF, so a board without the wiring never flips the bank. The Driveline shows a top view of the chassis in the top-right corner, drawn from the user's sketch with `lv_line` objects and two border boxes, geometry in sketch pixels scaled by `DL_S`. All four tyres are the same square-cornered rectangle, and the wheelbase is the sketch's shortened by 20 %. A locked axle turns amber: axle, tyres filled solid, and an X on its diff. A filled tyre is one `lv_line` as wide as the tyre with square ends, because LVGL 8 cannot rotate a box. The front axle turns red if it reads locked without the rear. There is no text caption (user). The whole drawing is hidden when the switch is off; the System row's sub-line shows the live state for testing. Wiring and evidence: wiki `diff-lock-inputs`.
**Debug Mode**:
- Toggle in Settings screen shows/hides `uic_Device_State_Container`
- Updates FPS (`uic_FPS_Values_LBL`) and CPU usage (`uic_CPU_Values_LBL`) every second
- Frame counting: `g_frame_count` incremented in `updateDebugMetrics()` called from `loop()`
### Reverse lights (`reverse` console)
`src/modules/reverse_light.cpp` drives the isolated output **DO0** (terminal block) so a 12 V relay lights the Patrol's reverse lamps while the **lever is in R** (`driveline_t.lever == GEAR_REVERSE` from 0x1D2 byte 0, with CAN running and ignition on - the same snapshot the Driveline shows). DO0 is the collector of an NPN power transistor (450 mA sink, emitter on board GND) behind a PC817 driven from the CH422G's **OC0** pin: OC0 LOW = relay on. Written through the panel library's expander object (`DisplayInit::expander()`, pin 8 in its numbering), never raw I2C, because the backlight writes the library's cached OC register back to the chip on every on/off - a raw write would be undone during OTA. The chip and the library both default OC0 high, so DO0 is off from reset; `init()` writes it off once more. Decision at 10 Hz, applied after two equal decisions (200 ms) so a one-frame glitch cannot chatter the relay; the CAN driver's 2 s silence clear and the key-off lever code (`0xF0`) turn it off. Failed writes are retried every tick (one console line after 3 in a row). `reverse status | on | off | force on|off|auto` - `force` is for the wiring check, never saved, ends itself after 60 s. Enabled by default (`revlight_en`; an unwired DO0 is harmless); no Settings row because the System page is full at four. Wiring: wiki `reverse-lights-output`.
### Vehicle (road speed, power) - `vehicle` console
`src/modules/vehicle.cpp` holds the two swap-specific numbers that turn the gearbox output shaft (0x0BA bytes 3-4, the only road-speed signal on this bus) into road speed: **final drive ratio** (x100, default 411 = 4.11:1, user 2026-10-13) and **tyre rolling circumference** (mm, default 2440 = a 265/70 R16). `speedKmhX10(raw)` = `can_output_shaft_rpm(raw)` / ratio x circumference x 60 / 1000, integer maths; the shaft factor (0.1074) is still provisional, so every speed on screen carries a `~`. `powerHpX10(torque_x10, rpm)` = Nm x rpm / 9.5488 W, / 745.7 hp (negative torque = 0). Edited on Settings > Vehicle (-/+ rows, hold to repeat, Reset with confirm, live preview, Saving.../saved footer) or `vehicle show | set final <x.xx> | set tyre <mm> | reset`. NVS writes are deferred like the tunables (3 s idle, `flush()` when Settings is left) because every flash write flickers the panel.
**ECU identification (`ecu` console, `src/modules/ecu_ident.cpp`, 2026-10-18)**: which DDE the board is on, read **once** and remembered (user's rule: never re-asked at boot; UNKNOWN ECU until read). While nothing is stored, `tick()` sends `1A 86` (verified answered on Patrol 1 from this board; `1A 80` was silent that day) and then `1A 80` (what the Launch asks; answered on both Patrols) through `DiagProbe::requestIdent()`, up to 3 spaced attempts each per boot, only with CAN on, ignition on for 5 s, no `sim`, no scan tool for 3 s. The raw payloads are stored as NVS blobs; decode offsets are the observed ones (`1A 86`: `"@B892524 "`, BCD date at 11-13, part numbers from byte 16, VIN prefix at 53-62; `1A 80`: part number BCD at 4-7, date at 15-17) - a block that does not fit is still stored and shown by length. Once anything is stored the module never transmits again until **Re-read ECU** (Settings > Vehicle, confirm) or `ecu forget`. Free passive check: a Launch on the bus reads `1A 80` every cycle; if that block differs from the stored one the Vehicle page shows **ECU CHANGED? bus X, stored Y** in amber. `ecu show | dump | forget`. The identity is a label for captures and the wiki (`vehicles` page); broadcast decoding never depends on it - only the Engine data screen's live-data identifier profile does (`hasPart()`).
**Bench simulation (`sim` console, `src/modules/bench_sim.cpp`)**: `sim torque <Nm> [rpm <n>] [shaft <rpm>] | rpm | shaft | status | off`. `CANDriver::getDriveline()` overlays the values (plus ignition on, engine running) on every snapshot while active, and the Driveline, Sport and Vehicle pages count it as a live bus; the Driveline chip reads `IGN SIM`, the Sport status line says SIMULATION. Off at boot, never saved, nothing transmitted, the Inst. Cluster unaffected. `Ota::isParked()` sees the simulated rpm too, so `sim off` before an install with CAN on.
### Screens
All hand-coded in `src/modules`, built once and kept (never deleted - the old generated screens were deleted on leave, which left dangling pointers and caused the 2026-09-27 freezes). Shared look in `ui_kit.cpp` (20/24 px text, >= 56 px touch targets, no shadows/animations, `UiKit::confirm()` modal dialog). Each screen has a `tick()` called from `loop()` that refreshes values under the LVGL lock, only while it is shown, and only re-sets label text that changed.
- **Driveline** (boot) - swipe left: Settings, swipe right: Gauge Tuning, **Sport** and **Engine data** buttons (y 60, left of the diff-lock drawing). Bottom row: torque, pedal, output shaft (~rpm), **speed (~km/h)** from `Vehicle`
- **Sport** (`sport_screen.cpp`, 2026-10-13) - BMW iDrive "Sport displays" after the user's photo: two `lv_meter` gauges on black, Power (0-320 hp, `Vehicle::powerHpX10`) left and Torque (0-600 Nm, 0x0A8 TORQ_AVL floored at 0) right. Each gauge is a **dial-face image** (`assets/dial.png` 420x420, source `assets/dial.pcraft`, geometry `assets/dial_geometry.json`, C array `src/assets/dial_img.c` 529 KB) rebuilt element by element from the photo (straightened crop + zooms in `assets/reference/`): cells ring r 158-190 with a radial gradient (orange inner edge to dark red) cut into 16 cells by 15 dark gaps, dark ruler ring r 195-207 with 81 rungs (5 per cell), bright lines at r 193-195 and the rim r 207-210 with a halo, 5 light spokes at the numbers; sweep 230 degrees starting at 155 (open at the bottom, like the photo - not 270). An `lv_meter` sits on top with ZERO-WIDTH ticks: it draws only the 5 numbers (label radius `LABEL_R` 136) and the needle. The unit large in the middle with the value small under it, the name below. PhotoCraft lesson: a shape's gradient is mapped to the bbox of ALL its subpaths, subtracted ones included, so the open-bottom wedge must stay symmetric about the dial centre (y to 400, not 800). The needle is an **image** (`assets/needle.png` 240x48, drawn in PhotoCraft via its MCP server, source `assets/needle.pcraft`; converted by `tools/png2lvgl.py` into `src/assets/needle_img.c`, RGB565+alpha, declared `extern "C"` in the screen) rotated by `lv_meter_add_needle_img` about pivot (0, 24): transparent for the first 70 px so it starts away from the centre, tapered red body, glowing orange-white tip reaching the rim at x 212. rpm and ~speed under the gauges. Blank with CAN or ignition off, `sim` counts as live; torque and hp also need `ENGINE_RUN_RUNNING` (key on / engine off, 0x0A8 holds junk: 812 Nm on Patrol 2, 245 on Patrol 1 - the Driveline's torque reads `--` then too). 10 Hz tick, needle written only on a change. Swipe right or the Driveline button goes back
- **Engine data** (`engine_screen.cpp`) - rail pressure, boost, charge-air temp, battery from the DDE via `DiagProbe`'s live poll (runs only while the screen is shown, ~1.5 s keep-alive; pauses while another tester is on the bus). **Per-DDE profiles (2026-10-18)**: `PROFILES[]` maps the ECU's part numbers (`EcuIdent::hasPart()`) to its `2C 10 <id>` identifier set and which scalings are provisional - Patrol 1 (7796678 / 7799764...) has all four, Patrol 2 (7794904 / 7796156, E65 donor) has rail `00C2`, boost `003A`, battery `002F` (Patrol 1's scalings, provisional - Launch captures 2026-10-18) and no charge-air temp yet; a slot without an identifier says "identifier not known for this ECU yet", an unidentified ECU or one without a profile polls nothing and the status line says why. The profile is re-evaluated every tick so the first identification takes effect while the screen is open. Scalings live in `CHANNELS[]`; every value shows its raw number and identifier. Swipe right or the Driveline button goes back
- **Settings** (`settings_screen.cpp`) - sidebar: **Wi-Fi** (switch, status card, networks nearby, full-screen password page), **Updates** (two cards: Main CTRL -> `Ota::requestCheck/requestInstall`, Inst. Cluster -> `LinkPeer::requestCheck/requestInstall`; each Installed / Latest / status line / Check / Install behind a confirm dialog; must fit 484 px, pages don't scroll), **System** (CAN / link to B / performance overlay / diff-lock input switches, live ESP-NOW, CAN, memory, uptime on the firmware line - the page is full at four rows), **Vehicle** (final drive ratio and tyre circumference -/+ rows, formula + live "output shaft N rpm = X km/h" preview, the **Engine ECU** line from `EcuIdent` - `DDE 7799764 - 2006-03-07` / muted `UNKNOWN ECU` / amber `ECU CHANGED?` -, Saving.../saved footer, **Re-read ECU** and Reset buttons each behind a confirm; `Vehicle::flush()` on leaving the screen). Swipe right or the Driveline button goes back
- **Gauge Tuning** (`tuning_screen.cpp`) - tabs Tachometer / Coolant gauge / Alerts / Simulation; -/+ rows with hints (hold to repeat, speeds up), per-tab Reset with confirm, "Saving... / All changes saved" footer, SIMULATION ON chip while an override is active. Swipe left or the Driveline button goes back
- Screen switches are instant (`LV_SCR_LOAD_ANIM_NONE`): full-screen fades are software-blended every frame and stutter at 1024x600. The firmware version is a label on `lv_layer_top()` (bottom-right, every screen, `DisplayInit`)
- **StatusOverlay** (2026-09-27, `status_overlay.cpp`, also on `lv_layer_top()`): a 150 px Wi-Fi chip top-right (off / not connected / joining / network name) and an alert banner top-centre that blinks red at 2 Hz while any red alert bit is set (coolant hot, gearbox oil hot, gear mismatch, battery low - text names the value) and is steady amber for gearbox cooling; hidden with CAN or ignition off. The top ~56 px of every screen belong to it: `UiKit::header()` puts the back button at x -176, the Driveline chips start at y 60. On the Driveline the crossed value AND its title go red (amber for cooling) and a gear mismatch turns the hero ring + letter red (the old top-right mismatch label is gone). Blinking is a colour toggle from `tick()` every 500 ms, not an lv_anim (a 1024-wide banner animated per frame would cost real render time)
- The System page's "Performance overlay" switch shows LVGL's own perf monitor (real render FPS / CPU) and sets the debug flag sent to B
## Configuration Files
@@ -255,7 +277,7 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Custom Arduino core: `pioarduino/platform-espressif32` (Arduino 3.3.3 / ESP-IDF 5.5.1) for RGB LCD support
- Board: Custom `esp32-s3-wroom-1-n16r8` (defined in `boards/esp32-s3-wroom-1-n16r8.json`)
- PSRAM: OPI mode (`qio_opi` memory type) - REQUIRED for 8MB OPI PSRAM and 1024x600 display
- Partition: `partition_table.csv` (12.5MB app / 3.375MB SPIFFS) - optimized for 16MB flash
- Partition: `partition_table.csv` (dual OTA: 2 x 7.9MB app slots, no SPIFFS) - see OTA updates below
- Debug level: `CORE_DEBUG_LEVEL=1` (1=Error, 5=Verbose)
- Libraries: ESP32_Display_Panel v1.0.4, LVGL 8.4.0 (from GitHub)
@@ -267,48 +289,23 @@ Settings persist across power cycles via ESP32 NVS (Non-Volatile Storage):
- Critical settings: `memory_type: qio_opi`, `psram_type: opi`
**partition_table.csv** (Partition Table)
- NVS: 20KB @ 0x9000 (settings storage)
- OTA Data: 8KB @ 0xe000 (for future OTA support)
- App: 12.5MB @ 0x10000 (large partition for UI assets)
- SPIFFS: 3.375MB @ 0xC90000 (file system)
- NVS: 20KB @ 0x9000 (settings storage) - never move it, or saved settings/tunables are lost
- OTA Data: 8KB @ 0xe000 (which slot boots)
- app0 / app1: 7.9MB each @ 0x10000 / 0x800000 (OTA slots; firmware ~1.65MB)
- Coredump: 64KB @ 0xFF0000 (crash debugging)
- Changing this table needs one USB flash; OTA can't repartition
**include/lv_conf.h**
- LVGL 8.4.0 configuration
- Memory: Uses PSRAM for large objects
- Memory: LVGL's widget pool (`LV_MEM_SIZE`) is 512 KB in PSRAM via `LV_MEM_POOL_ALLOC` (was 48 KB internal and ran out). `mem` on the console prints internal heap, PSRAM and pool use/fragmentation
- Asserts: `LV_ASSERT_HANDLER` is `abort()` (backtrace + core dump + reboot), never `while(1)`, which froze the UI while holding the LVGL lock
- Theme: Material theme enabled
## Common Patterns
### Adding a New Toggle Switch
### Adding a New Setting
1. Add NVS keys in main.cpp:
```cpp
#define NVS_KEY_FEATURE_ENABLED "feature_en"
```
2. Add save/load functions:
```cpp
void saveFeatureState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false);
preferences.putBool(NVS_KEY_FEATURE_ENABLED, enabled);
preferences.end();
}
```
3. Add global state variable: `static bool g_feature_enabled = false;`
4. Create event handler (called from SquareLine UI):
```cpp
void onFeatureToggle(lv_event_t *e) {
lv_obj_t *target = lv_event_get_target(e);
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
saveFeatureState(state);
// Update state, send to task if needed
}
```
5. Add sync logic in `applySavedStatesToUI()` to restore state when Settings screen loads
See "Adding a setting" under Important Notes: a row + `UiKit::toggle()` on the Settings screen, a `SettingsManager` save/load pair, and a sync line in the page's `refresh*()`.
### Thread-Safe UI Update from Background Task
@@ -350,7 +347,8 @@ xTaskCreatePinnedToCore(
- **CAN Bus**: GPIO 15 (TX), GPIO 16 (RX) - 500 Kbps, TWAI_MODE_NORMAL, onboard TJA1051 on the terminal block
- **UART1**: GPIO 44 (TX), GPIO 43 (RX, unused) - reaches the terminal block only as the RS485 A/B pair (SP3485), 115200 baud. Bench: `485_A` straight into B's IO1 + GND works (verified 2026-09-21)
- **USB Serial**: UART0 (default Serial) - 115200 baud for debug output
- **USB Serial**: native USB-CDC (`Serial`, 303A:1001). Opening the port with default DTR/RTS resets the board - attach with `pio device monitor -p COM10 --dtr 0 --rts 0 --echo`
- **Uploading from a script/pipe on Windows**: set `PYTHONIOENCODING=utf-8` (and `PYTHONUTF8=1`). Otherwise esptool crashes printing its progress bar to a cp1252 pipe *mid-write* and leaves the board frozen until a power cycle (happened 2026-09-27; the bootloader then fell back to the other OTA slot)
### Display Panel
@@ -369,6 +367,7 @@ xTaskCreatePinnedToCore(
### Build Errors
- **Build from PowerShell, not Git Bash**: `idf_tools.py` refuses MSYS ("MSys/Mingw is not supported"). The two projects also share one `framework-arduinoespressif32` package directory, so the first `pio run` after building ESP32-S3-LCD-1.3 reinstalls Arduino 3.3.3 and may fail once with `TypeError: expected str, bytes or os.PathLike object, not NoneType` - run it again.
- **`Failed to install Python dependencies into penv (exit code: 2)`** at the start of `pio run`: the sibling ESP32-S3-LCD-1.3 project (official espressif32@6 platform) installs newer `urllib3`/`esptool` into the shared PlatformIO penv, and this project's pioarduino platform needs `urllib3<2`; its install step hides the error. Run `. ools ix_penv_deps.ps1`, then build again. Never build the two projects at the same time (shared penv).
- **Missing libraries**: Run `pio lib update` then `pio run --target clean`
- **Partition table not found**: Ensure `partition_table.csv` exists in project root
@@ -383,7 +382,7 @@ xTaskCreatePinnedToCore(
- **Screen drift/artifacts**: RGB LCD timing issue - already optimized in `platformio.ini` with high-performance platform packages
- **White flash on boot**: Backlight control sequence in setup() minimizes this (lines 1383-1414)
- **UI toggles don't match state**: Check `applySavedStatesToUI()` is called in `loop()` - this syncs UI with running services
- **UI switches don't match state**: `SettingsScreen::tick()` must run in `loop()` - it re-reads the live state every 250 ms
- **WiFi/UART task not responding**: Check FreeRTOS queue creation succeeded (NULL check in setup())
- **LVGL crash from background task**: Ensure `lvgl_port_lock()` / `unlock()` wraps ALL LVGL API calls
- **Screen flickering**: This was resolved by fixing the proper board configuration and partition table. The key fixes were:
@@ -396,7 +395,7 @@ xTaskCreatePinnedToCore(
## Performance Metrics
- **FPS**: ~50 FPS @ 1024x600 resolution
- **FPS**: not measured yet (the Debug-panel counter counts loop() passes, not frames) - see wiki open-questions #13
- **CPU Load**: ~80% on Core 1 (LVGL rendering)
- **WiFi Scan**: 1-3 seconds for 10-20 networks
- **UART Overhead**: +1-2% CPU @ 5Hz transmission rate
@@ -404,7 +403,6 @@ xTaskCreatePinnedToCore(
## Important Notes
- **SquareLine Studio Export**: ALWAYS export UI files to `ui/` directory, NEVER to `src/` (prevents overwriting main.cpp)
- **Event Handler Registration**: Event handlers for SquareLine UI elements are registered in `ui_Settings_Screen.c` auto-generated code. When adding new toggles, add event callback registration via `lv_obj_add_event_cb()` and declare handler in `ui_events.h`
- **Adding a setting**: add a row to the right page in `settings_screen.cpp` (`makeSettingRow()` + `UiKit::toggle()`), persist it via `SettingsManager`, and sync it in that page's `refresh*()` function
- **CAN Bus Integration**: BMW CAN IDs are defined in `automotive_data.h` (all 11-bit standard frames, verified live on the swap bus). The CAN driver runs in `TWAI_MODE_NORMAL` (it ACKs frames; not LISTEN_ONLY). Evidence and confidence labels live in `wiki/pages/can-id-candidates.md`. Never add a second caller of `CANDriver::transmit()` without a design discussion — transmitting on the vehicle bus is a safety decision
- **Security**: Password field (`uic_Wifi_Passkey_TB`) is cleared after connection attempt for security (line 1015, 1029)
- **Security**: the Wi-Fi password field is cleared when the password page closes; the saved password lives only in NVS and is never logged (the pre-2026-09-27 code printed it on every join)
+26 -23
View File
@@ -4,12 +4,14 @@ Automotive display controller for Waveshare ESP32-S3-Touch-LCD-5B (1024x600 RGB
## Features
- ✅ **WiFi** - Network scanning with dynamic SSID list
- ✅ **UART** - Automotive data transmission @ 5Hz (GPIO 43/44)
- ✅ **Debug Mode** - FPS and CPU metrics display
- ✅ **Settings Persistence** - NVS storage for toggle states
- ✅ **Touch UI** - LVGL 8.4.0 with SquareLine Studio UI
- ✅ **FreeRTOS** - Multi-core architecture (WiFi/UART on Core 0, LVGL on Core 1)
- ✅ **CAN bus** - decodes the BMW M57N / ZF 6HP powertrain frames (gear, temperatures, rpm, ...)
- ✅ **Link to Inst. Cluster** - data + gauge config @ 5 Hz over RS485 (UART1) and ESP-NOW
- ✅ **Screens** - Driveline (boot), Sport (torque + power gauges), Engine data, Settings (Wi-Fi / Updates / System / Vehicle), Gauge Tuning; LVGL 8.4.0, hand-coded
- ✅ **Wi-Fi** - one remembered network, joined at boot
- ✅ **OTA updates** - signed releases from Gitea, installed from the Settings screen
- ✅ **Reverse lights** - the isolated output DO0 switches a relay while the lever is in R
- ✅ **Settings persistence** - NVS
- ✅ **FreeRTOS** - Wi-Fi / UART / CAN on Core 0, LVGL on Core 1
## Hardware
@@ -34,6 +36,8 @@ pip install -U platformio
## Build & Upload
Full cheat-sheet for both controllers (build, upload, serial monitor, every console command, pairing, releases): [`docs/COMMANDS.md`](docs/COMMANDS.md).
### Using PlatformIO CLI
```bash
@@ -64,32 +68,31 @@ pio run --target upload && pio device monitor
## Project Structure
```
migrate-to-pio/
├── platformio.ini # PlatformIO configuration
├── partition_table.csv # Partition table (3MB app + 1MB SPIFFS)
├── src/ # Source code (non-UI)
│ ├── main.cpp # Main application
│ ├── automotive_data.h # UART data structures
│ └── lvgl_v8_port.h/cpp # LVGL porting layer
├── ui/ # SquareLine Studio exports
│ └── ui*.h/c # UI files (auto-generated)
├── include/
│ └── lv_conf.h # LVGL configuration
└── .pio/ # Build artifacts (gitignored)
platformio.ini # PlatformIO configuration
partition_table.csv # dual OTA slots (2 x 7.9 MB), NVS, coredump
src/
main.cpp # setup, loop, console routing
modules/ # screens, Wi-Fi, link, OTA, tunables, ...
drivers/can_driver.cpp # CAN (TWAI)
include/
config/ # lv_conf.h, ota_config.h, board config
display/ # LVGL port
protocol/automotive_data.h # link protocol shared with Inst. Cluster
wiki/ # project knowledge base
```
**Important**: Configure SquareLine Studio to export UI files to the `ui/` directory. This prevents the auto-generated UI code from overwriting your custom source files in `src/`.
See `CLAUDE.md` for the architecture.
## Configuration
### Partition Scheme
Current: **Huge APP (3MB No OTA / 1MB SPIFFS)**
Dual OTA (see `partition_table.csv`):
- NVS: 20KB (settings storage)
- NVS: 20KB (settings, tunables, Wi-Fi) - never move it
- OTA data: 8KB
- App: 3MB (application code)
- SPIFFS: 1MB (file system)
- app0 / app1: 7.9MB each (firmware ~1.7MB)
- Coredump: 64KB
Edit `partition_table.csv` to customize partition sizes.
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 308 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 315 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 395 KiB

+237
View File
@@ -0,0 +1,237 @@
# Commands cheat-sheet — both controllers
Everything you type to build, flash, watch and drive the two boards. Kept in the
Main CTRL repo (this one); the Inst. Cluster repo's README points here.
| | Main CTRL | Inst. Cluster |
|---|---|---|
| Board | Waveshare ESP32-S3-Touch-LCD-5B (5" touch) | Waveshare ESP32-S3-LCD-1.3 (1.3" round) |
| Repo / branch | `ESP32-S3-Touch-LCD-5B`, `main` | `ESP32-S3-LCD-1.3`, `master` |
| Platform | pioarduino (Arduino 3.3.3 / IDF 5.5) | espressif32@6 (Arduino 2.0.17 / IDF 4.4) |
| Serial | native USB-CDC | CH343 UART |
| Bench port (2026-09-28) | COM14 | COM10 |
| OTA target / release | `patrol-a`, `v*` tags → signed release | `patrol-b`, `v*` tags → signed release |
Windows ports move around: `pio device list` shows what is plugged in.
---
## 1. Rules of the road (Windows, this machine)
- **PowerShell only.** `pio` refuses to run from Git Bash (`MSys/Mingw is not supported`).
- `pio` lives at `$env:USERPROFILE\.platformio\penv\Scripts\pio.exe` (no global install). The commands below assume this alias:
```powershell
Set-Alias pio "$env:USERPROFILE\.platformio\penv\Scripts\pio.exe"
```
- **The two projects share one PlatformIO environment.** Consequences:
- The first `pio run` after building the *other* project reinstalls the Arduino core and may fail once with `TypeError: expected str, bytes or os.PathLike object, not NoneType`. Run it again.
- After **any B build**, repair the environment before building A, or A fails with `Failed to install Python dependencies into penv`:
```powershell
.\tools\fix_penv_deps.ps1 # run inside the A repo
```
- Never build both projects at the same time.
- **A serial monitor on a port blocks uploads to that port.** Close it (Ctrl+C) first.
- Opening a port with DTR/RTS asserted resets the board. Always monitor with `--dtr 0 --rts 0`.
---
## 2. Build and upload
Run inside the respective repo folder.
### Main CTRL
```powershell
cd <path>\ESP32-S3-Touch-LCD-5B
pio run # build only (dev build, version "dev")
pio run -t upload --upload-port COM14 # build + flash over USB
pio run -t clean # wipe the build directory
```
First build after a `platformio.ini` change rebuilds the ESP-IDF core (~20 min, `custom_sdkconfig`); later builds take 1–3 min.
### Inst. Cluster
```powershell
cd <path>\ESP32-S3-LCD-1.3
pio run
pio run -t upload --upload-port COM10
..\ESP32-S3-Touch-LCD-5B\tools\fix_penv_deps.ps1 # ALWAYS after a B build, before the next A build
```
A USB flash writes bootloader, partition table, `boot_app0` and the app into slot 0. It does **not** touch NVS: saved Wi-Fi network, tunables, pairing key and B's cached gauge config survive.
---
## 3. Serial monitor
```powershell
pio device monitor -p COM14 -b 115200 --dtr 0 --rts 0 --echo # Main CTRL
pio device monitor -p COM10 -b 115200 --dtr 0 --rts 0 --echo # Inst. Cluster
```
Type a command, press Enter. `--echo` shows what you type. Ctrl+C leaves.
One-shot commands and logging from a script (A repo, `tools/`):
```powershell
python tools\serial_cmd.py COM14 "link status" 3 # send one line, print 3 s of reply
python tools\serial_logger.py COM14 # log a port to wiki\raw\ until Ctrl+C
python tools\serial_logger.py COM14,COM10 # both ports at once
python tools\perf_session.py COM14 # display-performance session (PERF lines)
python tools\diag_session.py COM14 "diag pids" "diag vin" # scripted OBD probe run with log
```
---
## 4. Main CTRL console
Type `help` for the list. Unknown lines are reported.
### `cfg` — Patrol gauge calibration and alert thresholds (saved in NVS, pushed to B)
```
cfg show
cfg set <name> <value> tach_ppr tach_trim tach_min_hz tach_max_hz
temp_hz temp_slope(x100) temp_offset temp_min temp_duty_max
tach_en temp_en coolant_hot gearbox_hot batt_low(x100)
cfg override off | rpm <n> | duty <n> | both <rpm> <duty> bench test of B's outputs, never saved
cfg reset
```
### `wifi`
```
wifi status connection, saved network, ESP-NOW health
wifi join <ssid> [pass] join and remember a network (no spaces in the SSID)
wifi forget drop the remembered network (B is told to forget too)
wifi scan list networks in range
wifi on | off
```
### `ota` — this controller's own updates
```
ota status version, slot, rollback state
ota check ask Gitea for the latest release (needs Wi-Fi)
ota install [force] download, verify, flash the idle slot, reboot (parked only)
ota rollback boot the previous slot (parked only)
```
### `link` — Inst. Cluster over the link
```
link status B's version, pairing, update phase, credentials
link pair new shared key → B over the UART WIRE (bench, wire connected)
link unpair forget the key here
link creds send the remembered Wi-Fi network to B now (normally automatic)
link ota check | install [force] | rollback drive B's updater (A must be on Wi-Fi, parked)
```
### `diag` — OBD-II probe (the only thing that ever transmits on the CAN bus)
```
diag pids scan mode-01 supported-PID bitmaps
diag pid <hex> one mode-01 request (0C rpm, 70 boost, ...)
diag dtc mode 03, stored generic DTCs
diag vin mode 09 PID 02
diag ecu mode 09 PID 0A
diag ident [addr] BMW KWP 1A 80 identification (default 12 = DDE)
diag bmw <addr> <hex...> raw BMW request on 0x6F1, read-only services only
diag raw on | off CANRAW frame logging
diag status
```
### `difflock` — diff-lock inputs (DI0 = rear, DI1 = front; Settings → System switch, default OFF)
```
difflock status rear / front LOCKED or open, raw CH422G IO byte, read counters
difflock on | off same as the switch (saved)
difflock invert on | off polarity, same as the "Inverted" switch (saved): on = NO current means locked
```
Wiring: lock wire → DI0 / DI1, `DI_COM` → vehicle ground. If the screen shows locked when unlocked (the Patrol's ground-switched lamp wires do this), turn **Inverted** on. Details: wiki `diff-lock-inputs`.
### `reverse` — reverse-light relay on DO0 (follows the gear lever in R; default ON, no Settings row - the System page is full)
```
reverse status enabled?, DO0 on/off, lever / ignition / CAN as seen, write counters
reverse on | off enable / disable (saved); off = DO0 stays off
reverse force on | off drive DO0 regardless of the lever, for the wiring check (not saved, ends after 60 s)
reverse force auto back to the lever
```
Wiring: relay coil between +12 V and `DO0`, flyback diode across the coil (stripe to +12 V); the coil current returns through the board's `GND`. ≤ 450 mA per output. Details: wiki `reverse-lights-output`.
### `vehicle` — road speed from the gearbox output shaft (Settings → Vehicle; saved in NVS)
```
vehicle show final drive ratio, tyre circumference, and what 1000 shaft rpm comes to
vehicle set final <x.xx> final drive (differential) ratio, 2.00..8.00 - 4.11 on this Patrol
vehicle set tyre <mm> tyre rolling circumference, 1500..3500 mm (265/70 R16 ≈ 2440)
vehicle reset back to 4.11:1 and 2440 mm
```
### `ecu` — which engine ECU (DDE) this board is on (read once, saved in NVS)
```
ecu show stored identification: part number, software date, VIN prefix; or UNKNOWN ECU
ecu dump the stored KWP 1A 86 / 1A 80 payloads in hex
ecu forget drop them - UNKNOWN ECU until read again (do this when the board moves to another car)
```
While nothing is stored the board asks the DDE once (`1A 86`, then `1A 80`, up to 3 tries each per boot) as soon as CAN is on, the ignition has been on for 5 s, `sim` is off and no scan tool has spoken for 3 s. Once stored it never asks again. Same thing from the screen: Settings → Vehicle shows the Engine ECU line and has a **Re-read ECU** button. With a Launch connected the board also sees its `1A 80` reads and shows **ECU CHANGED?** if they differ from the stored block.
### `sim` — bench values for the screens (never saved, off at boot, nothing transmitted)
```
sim torque <Nm> [rpm <n>] [shaft <rpm>] e.g. sim torque 350 rpm 2500 shaft 1200
sim rpm <n> | sim shaft <rpm> change one value, the rest stays
sim status
sim off
```
Feeds the Sport gauges, the Driveline's torque / rpm / output / speed and the Vehicle page preview as if the ignition were on; the Driveline's chip reads `IGN SIM` and the Sport screen says SIMULATION meanwhile. The Inst. Cluster is not affected (use `cfg override` for its outputs).
Speed (km/h) = output shaft rpm ÷ ratio × circumference (m) × 60 ÷ 1000. The shaft rpm is still the provisional 0x0BA × 0.1074, so the screens show `~km/h`. The Sport screen's hp = Nm × rpm ÷ 9.5488 ÷ 745.7.
### Diagnostics
```
mem internal heap, PSRAM, LVGL pool
perf one PERF line (fps, flush cost, CPU idle, heap, panel vsync)
perf on [sec] | perf off
```
---
## 5. Inst. Cluster console
```
help
link status pairing, A's MAC, STATUS/SECURE counters, credentials
link unpair forget the pairing key (re-pair from A over the wire)
wifi status stored network name (password never shown)
wifi forget
ota status version, slot, rollback state
ota check join Wi-Fi, ask Gitea for the latest release, leave
ota install [force] download, verify, flash, reboot (parked only)
ota rollback
```
B prints a stats line every 5 s (`applied=… uart … espnow …`) — `uart alive` means the wire works.
---
## 6. Procedures
### Pair a Inst. Cluster (once per board pair)
1. Wire: 5B terminal `485_A` → B `IO1`, GND → GND (a real wire, not just the USB hub), 5B's 120 Ω switch OFF. Both powered. B's stats line must say `uart alive`.
2. A console: `link pair`. Within 5 s A logs `Inst. Cluster confirmed pairing (fingerprint XXXX)`; B logs `PAIRED over the wire`.
3. `link status` on A: `key XXXX (matches)`. About 15 s later `Wi-Fi creds yes` (A pushes them by itself; `link creds` forces it).
The key lives in NVS on both boards and survives every flash and update. Re-pair only after an NVS erase, `link unpair`, or a board swap.
### Release a version
```powershell
git tag -a vX.Y.Z -m "what changed"
git push --follow-tags origin main # A (B: origin master)
```
One push, so only the tag build runs. Gitea builds, signs (`BMW_NISSAN_FIRMWARE_SIGNING_KEY`) and publishes `firmware.bin` + `manifest.txt`: A takes 7–20 min, B 2–5 min. Check: `https://git.infra.msai.al/<owner>/<repo>/releases`. Version strings must stay under 16 characters.
### Update A from the screen
Settings → Updates → Main CTRL → **Check** → **Install vX.Y.Z** (parked, Wi-Fi joined). Progress bar, restart, `A vX.Y.Z` bottom-right. A reset in the first 30 s rolls back.
### Update B from the screen
Settings → Updates → Inst. Cluster → **Check** → **Install** (A on Wi-Fi, parked, B paired). B's round screen shows `Updating vX.Y.Z N%`, the card on A shows the percentage, B restarts and confirms itself after 30 s. Console equivalent: `link ota check`, `link ota install`.
### Something is wrong after an update
`ota rollback` on the affected controller's console (B: `link ota rollback` from A also works). A reset within 30 s of the first boot of a new image rolls back on its own.
---
## 7. Git on several machines
Fetch before you start on another machine; the wikis are edited from every machine:
```powershell
git fetch origin
git status -sb # "behind" → git pull --ff-only before touching anything
```
+20 -8
View File
@@ -1,9 +1,9 @@
# Link Protocol Specification (v2)
**Version:** 2 (`PACKET_VERSION 0x02`)
**Last Updated:** 2026-09-21
**Source of truth:** `include/protocol/automotive_data.h` — byte-identical in both repos.
**Direction:** Controller A (ESP32-S3-Touch-LCD-5B) → Controller B (ESP32-S3-LCD-1.3), one way.
**Last Updated:** 2026-09-27
**Source of truth:** `include/protocol/automotive_data.h` (+ `link_secure.h`) — byte-identical in both repos.
**Direction:** gauge data Main CTRL (ESP32-S3-Touch-LCD-5B) → Inst. Cluster (ESP32-S3-LCD-1.3). Since 2026-09-27 B answers with `STATUS` frames over ESP-NOW and A sends B maintenance frames (`PAIR` on the wire, `SECURE` over ESP-NOW) — see *Maintenance frames* below.
---
@@ -28,8 +28,8 @@ The same frames are sent on two paths at once. B accepts either and deduplicates
|---|---|---|
| start | 1 | `0xAA` |
| version | 1 | `0x02` — B rejects any other value (counted as version error) |
| type | 1 | `0x01` DATA, `0x02` CONFIG |
| length | 1 | payload bytes (21 for DATA, 27 for CONFIG) |
| type | 1 | `0x01` DATA, `0x02` CONFIG, `0x03` STATUS, `0x04` PAIR, `0x05` SECURE |
| length | 1 | payload bytes (21 DATA, 27 CONFIG, 78 STATUS, 42 PAIR, 29–160 SECURE); `PACKET_MAX_PAYLOAD` = 160 |
| payload | length | see below, little-endian, packed |
| checksum | 1 | XOR of version, type, length and every payload byte |
| end | 1 | `0x55` |
@@ -101,7 +101,7 @@ Tach: `f = rpm × tach_ppr / 60 × (1 + trim/100)`, clamped, 50 % duty. Output l
---
## Controller A console commands (USB serial)
## Main CTRL console commands (USB serial)
```
cfg show
@@ -120,6 +120,18 @@ The same console also carries the OBD-II diagnostic probe (`diag pids | pid <hex
---
## Maintenance frames (2026-09-27) — for Inst. Cluster's firmware updates
`PACKET_VERSION` did not change: DATA and CONFIG are byte-identical, and a B built before these types counts them as type errors and carries on.
| Type | Direction | Transport | Payload | Purpose |
|---|---|---|---|---|
| `STATUS` 0x03 | B → A | ESP-NOW unicast to A's MAC (learned from A's data frames) | `link_status_t` (78 B): B's version, OTA phase (`LINK_OTA_*`, same numbering as A's `Ota::phase_t`), progress %, flags (paired / have Wi-Fi / joined / pending verify), `key_fp`, uptime, free heap, latest tag, message | every 5 s and on every phase change; A's Updates page "Inst. Cluster" card |
| `PAIR` 0x04 | A → B | **UART wire only** — B drops a PAIR heard by radio | `link_pair_t` (42 B): magic `"PAIR"`, 32-byte random key, A's STA MAC | `link pair` on A's console, sent 3×; both sides keep the key in NVS. The only secret in the system (both repos are public) |
| `SECURE` 0x05 | A → B | ESP-NOW unicast | `nonce[12] \| tag[16] \| AES-256-GCM(key, nonce, inner_type \| inner)` — helpers in `link_secure.h` | inner `LINK_INNER_OTA_CMD` 0x11 (`link_ota_cmd_t`: check / install [force] / rollback + random nonce, B ignores a repeat of the last 4) or `LINK_INNER_WIFI_CREDS` 0x12 (`link_wifi_creds_t`: SET/FORGET, ssid, pass). B also requires the sender MAC to be the paired A |
B reports `key_fp` = first two bytes of SHA-256(key) so A can tell "paired with my key" from "paired with an old one" and re-pair.
## Receiver behaviour (B)
- Link considered lost after 1000 ms without an applied DATA frame on any transport; display shows N/A and both gauge outputs go low.
@@ -131,7 +143,7 @@ The same console also carries the OBD-II diagnostic probe (`diag pids | pid <hex
## Changing the protocol
1. Edit `automotive_data.h` on A, bump `PACKET_VERSION`.
2. Copy the header to B unchanged.
1. Edit `automotive_data.h` on A. Bump `PACKET_VERSION` if DATA or CONFIG change; adding a new frame type does not need a bump (a stale B ignores unknown types).
2. Copy the header (and `link_secure.h`) to B unchanged (`cmp` them).
3. Update this document.
4. Flash both. A stale B logs version errors and applies nothing.
+16 -7
View File
@@ -49,14 +49,19 @@
#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 (48U * 1024U) /*[bytes]*/
/* 512 KB pool in PSRAM (2026-09-27). The old 48 KB pool lived in internal
* RAM and ran out: Settings + its Wi-Fi list is ~15 KB, and screen churn +
* fragmentation reached 87% used / 4.5 KB biggest block, then a label draw
* failed lv_mem_buf_get() -> assert. Moving it out also frees 48 KB of the
* scarce internal RAM. `mem` on the console prints the pool state. */
#define LV_MEM_SIZE (512U * 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
#undef LV_MEM_POOL_INCLUDE
#undef LV_MEM_POOL_ALLOC
#define LV_MEM_POOL_INCLUDE <esp_heap_caps.h>
#define LV_MEM_POOL_ALLOC(size) heap_caps_malloc((size), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)
#endif
#else /*LV_MEM_CUSTOM*/
@@ -271,8 +276,12 @@
#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*/
#define LV_ASSERT_HANDLER_INCLUDE <stdlib.h>
/* Was `while(1);`: a failed assert spun forever inside the calling task while it
* held the LVGL lock - the UI froze, loop() blocked on the lock, and only the
* link task kept running (2026-09-27). abort() panics instead: backtrace on the
* console, core dump to flash (ELF), reboot. A reboot beats a frozen screen. */
#define LV_ASSERT_HANDLER abort();
/*-------------
* Others
@@ -367,9 +376,9 @@
#define LV_FONT_MONTSERRAT_14 1
#define LV_FONT_MONTSERRAT_16 0
#define LV_FONT_MONTSERRAT_18 0
#define LV_FONT_MONTSERRAT_20 0
#define LV_FONT_MONTSERRAT_20 1
#define LV_FONT_MONTSERRAT_22 0
#define LV_FONT_MONTSERRAT_24 0
#define LV_FONT_MONTSERRAT_24 1
#define LV_FONT_MONTSERRAT_26 0
#define LV_FONT_MONTSERRAT_28 0
#define LV_FONT_MONTSERRAT_30 1
+111
View File
@@ -0,0 +1,111 @@
/**
* ota_config.h - where Main CTRL looks for firmware updates, and what it trusts.
*
* Updates are pulled over HTTPS from this repo's Gitea releases (public repo,
* no token). CI (.gitea/workflows/firmware.yml) attaches firmware.bin +
* manifest.txt to every v* tag; manifest carries size, sha256 and an ECDSA
* P-256 signature. See wiki/pages/ota-updates.md.
*
* Nothing in here is secret: the CA roots and the signing PUBLIC key are meant
* to be public. The signing private key lives only in the Gitea repo secret
* BMW_NISSAN_FIRMWARE_SIGNING_KEY (plus the owner's offline backup).
*/
#ifndef OTA_CONFIG_H
#define OTA_CONFIG_H
// Version string baked in by CI (-DFW_VERSION="v1.2.3"); local builds say "dev".
#ifndef FW_VERSION
#define FW_VERSION "dev"
#endif
// Identity inside the signed statement, so a Inst. Cluster image can never be
// accepted by A (and vice versa) even though both are signed by the same key.
#define OTA_TARGET "patrol-a"
#define OTA_SERVER "https://git.infra.msai.al"
#define OTA_REPO "art/ESP32-S3-Touch-LCD-5B"
// Latest non-draft, non-prerelease release (the rolling `main` build is a
// prerelease, so it is never offered to the car).
#define OTA_LATEST_API_URL OTA_SERVER "/api/v1/repos/" OTA_REPO "/releases/latest"
// + "<tag>/<asset>"
#define OTA_DOWNLOAD_BASE OTA_SERVER "/" OTA_REPO "/releases/download/"
// TLS trust: Let's Encrypt roots. The server's chain (2026-09-26) is
// leaf -> YR2 -> Root YR (cross-signed by ISRG Root X1); both roots verify it
// on their own, so either survives LE dropping the cross-sign. Valid to
// 2035 (X1) / 2045 (YR). Leaf certs rotate every ~90 days - never pin them.
static const char OTA_CA_PEM[] =
// ISRG Root X1
"-----BEGIN CERTIFICATE-----\n"
"MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"
"TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
"cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n"
"WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n"
"ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n"
"MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n"
"h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n"
"0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n"
"A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n"
"T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n"
"B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n"
"B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n"
"KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n"
"OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n"
"jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n"
"qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n"
"rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
"HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n"
"hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n"
"ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n"
"3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n"
"NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n"
"ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n"
"TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n"
"jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n"
"oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n"
"4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n"
"mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n"
"emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n"
"-----END CERTIFICATE-----\n"
// ISRG Root YR
"-----BEGIN CERTIFICATE-----\n"
"MIIFKTCCAxGgAwIBAgIRAOxGNJNgz0sP+KmC2Tqpyj0wDQYJKoZIhvcNAQELBQAw\n"
"LjELMAkGA1UEBhMCVVMxDTALBgNVBAoTBElTUkcxEDAOBgNVBAMTB1Jvb3QgWVIw\n"
"HhcNMjUwOTAzMDAwMDAwWhcNNDUwOTAyMjM1OTU5WjAuMQswCQYDVQQGEwJVUzEN\n"
"MAsGA1UEChMESVNSRzEQMA4GA1UEAxMHUm9vdCBZUjCCAiIwDQYJKoZIhvcNAQEB\n"
"BQADggIPADCCAgoCggIBANvGJnN78CTJdWL3+eGfsLN5TrNBJs+VH9hRXqRbwxu9\n"
"sGNiB0BD1fcOxbSUQCJIM1xE13Db+5Cw1w0s0EBYsvuIP/6joF0w8cuImbgR1OGg\n"
"YbSQ4OpzI+DG8SGuTlcE873OCS+kh3srlo6vl43M5OJg4Aeo1sfHp6kTJDoIiFBN\n"
"JAY+OKfX/FUvYKuhjT+no49lmqmupSBI5PkBQiqrEGtWU5uxU/cQWHGu8jSjFBzn\n"
"ZqvbNPLMXMLFxCb3WTfrJBXXjqvWG+v4bjzxjjeAtOlU7qarRDvNOyAuQYLln904\n"
"M+faKx8hnLCpJ15ZqaEgcNlY+9MMWcC5yvL2A2j3l9+2buggZX+dOE91zYmIdawT\n"
"vSZuVvlbRrAlLxIB6pwMBjneXCjYQ8+3BCCjssbSNpZU3hTcBDdhfAlEDlYr6pEa\n"
"tnMdmDT5BqnKC92bd0EhM1fbLHioLccLCuievT8ZkPhZrq7Mii7gNXAcUEAR8+lz\n"
"Yal+9zTg7C5DALyVOeG/CqfRAMn1KSHCR0NSA6P8tn/mGRlnCct5rtVCLnVySVpU\n"
"6H1qGg3DgTOuskf8eahTMiYbI5ezPJmO5ertalskQ1utp74+eDy92PI4ftHKTbq9\n"
"IWhH4YZKh3WnJEIt+oQvlYZbY8tpEroKrFB6PFGzrJIDRyts4HqvuH52RFj2zv/B\n"
"AgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud\n"
"DgQWBBTe51tg0CJtQCh9Pw0B/qS1UrRRlDANBgkqhkiG9w0BAQsFAAOCAgEAWHnf\n"
"713Bdkq7t5yN2dNIgQakUb94X9WuyhMEHHkgx4oDpSUlnG0w4g94MoqaEUE31ZjR\n"
"LU7L5LD1g9ujFHTQu8AD215AHMVQFbm6j8hQxdXHAzDajFNQnOlDJrLjzIx176oy\n"
"AjvUtejZx2NNmdb5fd0WGVGsCdoAJ3N8ozo7ajE8t6vfxStZb4BQ9WYJGHUDrv2N\n"
"i5tJF6CNiPnlzs3BUfECRbE4JSk+jvy8+VoGiFE8qsH/j78x2fjgQhAQFV7P7Zxy\n"
"dBTZ1wEkNpZNW2qnaK1SKBLa+xf6E06YRIq5uaI+HWH8SY1y5VbRgzq40EKg3yxP\n"
"06fz+uYAUIFJoLNfhwRCc3Q6pQVuMX3yAjHAes4gk4moGcLQ5p7HAh39yeylZc1J\n"
"41sx/jKwLIkPE6Rr1Nf4pxdsxf9SA4yOEiAkDgq04DVxn8hgYFdUtBCuiuVC2heA\n"
"EiqVEa+8QZjuw8Gj0EbHXcRd1nInvGqRS1o9Is7YBdQN57X1AYveGBNNqjICSb7c\n"
"awuw1EawTDrs13VUlJVEsbQ0/O/1aaV73mCdOQ8azqL2KTv1Ewu1xbquE2S+kdQU\n"
"To9TUwat3wUA6cwXh1EfpS/3fJ0aGah5hdpRyoCLDlsSn8tkrjMfFFX0viC+GxHc\n"
"sI1ANRYvqSFC2X1VRZfDg+wD6E21BccmifG4yWc=\n"
"-----END CERTIFICATE-----\n";
// Firmware signing public key (ECDSA P-256). The device verifies
// sig over SHA-256("<target>|<version>|<sha256-of-image-hex>").
static const char OTA_SIGNING_PUBKEY_PEM[] =
"-----BEGIN PUBLIC KEY-----\n"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF\n"
"Y9brIfDTgn8IOWBm8J4nmLUef7zU4ydPM5BKXqUrTshJEpLd74GJIIOtkg==\n"
"-----END PUBLIC KEY-----\n";
#endif // OTA_CONFIG_H
+40 -1
View File
@@ -9,6 +9,8 @@
#define ESP_UTILS_LOG_TAG "LvPort"
#include "esp_lib_utils.h"
#include "lvgl_v8_port.h"
#include "modules/perf_monitor.h"
#include "esp_timer.h"
using namespace esp_panel::drivers;
@@ -478,14 +480,35 @@ void flush_callback(lv_disp_drv_t *drv, const lv_area_t *area, lv_color_t *color
const int offsetx2 = area->x2;
const int offsety1 = area->y1;
const int offsety2 = area->y2;
const int w = offsetx2 - offsetx1 + 1;
const int h = offsety2 - offsety1 + 1;
lcd->drawBitmap(offsetx1, offsety1, offsetx2 - offsetx1 + 1, offsety2 - offsety1 + 1, (const uint8_t *)color_map);
// Time the pixel copy into the (PSRAM) framebuffer - this is the PSRAM
// write cost the display experiments (open question #13) change.
const int64_t t0 = esp_timer_get_time();
lcd->drawBitmap(offsetx1, offsety1, w, h, (const uint8_t *)color_map);
PerfMon::onFlush((uint32_t)(esp_timer_get_time() - t0), (uint32_t)(w * h));
// For RGB LCD, directly notify LVGL that the buffer is ready
if (lcd->getBus()->getBasicAttributes().type == ESP_PANEL_BUS_TYPE_RGB) {
lv_disp_flush_ready(drv);
}
}
// LVGL calls this once per rendered frame (render + flush time, pixels drawn).
static void monitor_callback(lv_disp_drv_t *drv, uint32_t time_ms, uint32_t px)
{
(void)drv;
PerfMon::onFrame(time_ms, px);
}
// RGB panel "refresh finished" (vsync) interrupt - counted for the perf monitor.
static IRAM_ATTR bool onPerfVsyncCallback(void *user_data)
{
(void)user_data;
PerfMon::onVsync();
return false; // no context switch needed
}
static void update_callback(lv_disp_drv_t *drv)
{
LCD *lcd = (LCD *)drv->user_data;
@@ -605,6 +628,9 @@ static lv_disp_t *display_init(LCD *lcd)
ESP_UTILS_LOGD("Register display driver to LVGL");
lv_disp_drv_init(&disp_drv);
disp_drv.flush_cb = flush_callback;
#if LVGL_PORT_AVOID_TEARING_MODE == 0
disp_drv.monitor_cb = monitor_callback;
#endif
#if (LVGL_PORT_ROTATION_DEGREE == 90) || (LVGL_PORT_ROTATION_DEGREE == 270)
disp_drv.hor_res = lcd_height;
disp_drv.ver_res = lcd_width;
@@ -802,6 +828,10 @@ bool lvgl_port_init(LCD *lcd, Touch *tp)
#if LVGL_PORT_AVOID_TEAR
lcd->attachRefreshFinishCallback(onLcdVsyncCallback, (void *)lvgl_task_handle);
#else
if (bus_type == ESP_PANEL_BUS_TYPE_RGB) {
lcd->attachRefreshFinishCallback(onPerfVsyncCallback, nullptr);
}
#endif
return true;
@@ -815,6 +845,15 @@ bool lvgl_port_lock(int timeout_ms)
return (xSemaphoreTakeRecursive(lvgl_mux, timeout_ticks) == pdTRUE);
}
bool lvgl_port_lock_available(void)
{
if (!lvgl_port_lock(0)) {
return false;
}
lvgl_port_unlock();
return true;
}
bool lvgl_port_unlock(void)
{
ESP_UTILS_CHECK_NULL_RETURN(lvgl_mux, false, "LVGL mutex is not initialized");
+8
View File
@@ -171,6 +171,14 @@ bool lvgl_port_lock(int timeout_ms);
*/
bool lvgl_port_unlock(void);
/**
* @brief Try the LVGL lock without waiting and release it at once.
* Used by the perf monitor to read lv_timer_get_idle() only when the
* UI task is not mid-render (the value is a plain int, so a stale read
* is harmless; a blocked console is not).
*/
bool lvgl_port_lock_available(void);
#ifdef __cplusplus
}
#endif
+19 -11
View File
@@ -67,9 +67,14 @@ typedef struct {
// DRIVELINE STATE
// ============================================================================
// Where driveline_t.ignition_on came from (see the field's comment).
#define IGN_SRC_NONE 0 // no frame seen yet
#define IGN_SRC_3B4 1 // 0x3B4 byte 2 nibble, seen within the last IGN_3B4_HOLD_MS
#define IGN_SRC_LEVER 2 // 0x1D2 byte 0: lever code valid = on, 0xF0 = off
/**
* Decoded driveline speeds. Deliberately NOT part of automotive_data_t: that
* struct is the wire format for the UART link to Controller B, and widening it
* struct is the wire format for the UART link to Inst. Cluster, and widening it
* would break the receiver. These live here until there's a reason to spend a
* protocol version bump on them.
*
@@ -90,9 +95,12 @@ typedef struct {
uint8_t converter_clutch; // 0x0BA ST_CCLT (CCLT_* constants). When CLOSED,
// turbine_rpm == engine_rpm by design — read this
// before interpreting the two as a slip ratio.
bool ignition_on; // 0x3B4 byte 2 low nibble. This bus's only
// ignition/terminal signal — CAS (0x130) is not
// present in the swap.
bool ignition_on; // Terminal 15. From 0x3B4 byte 2 low nibble when
// that frame is on the bus (Patrol 1); otherwise
// from the 0x1D2 lever byte: a recognised P/R/N/D
// code means key on, 0xF0 means key off (Patrol 2
// has no 0x3B4 at all - captures 2026-10-18).
uint8_t ignition_src; // IGN_SRC_* : which of the two decided ignition_on
uint8_t lever; // 0x1D2 byte 0 as gear_position_t: the selected
// detent (P/R/N/D). GEAR_UNKNOWN before first frame.
uint8_t engaged_gear; // 0x1D2 byte 1: gear the box is actually in, 1..6;
@@ -147,12 +155,13 @@ namespace CANDriver {
/**
* Transmit ONE standard (11-bit) frame, single-shot (no automatic
* retransmission if nobody ACKs). The only write path onto the vehicle
* bus; reserved for DiagProbe's on-demand diagnostic requests. Echoes the
* frame on the console as a "CANTX," line (same shape as CANRAW) so
* captures hold both halves of an exchange.
* bus; reserved for DiagProbe (console requests + the Engine data screen's
* live poll). Echoes the frame on the console as a "CANTX," line (same
* shape as CANRAW) so captures hold both halves of an exchange; the live
* poll passes echo=false unless CANRAW logging is on (10 frames/s).
* @return true if the frame was queued (delivery is reported via stats)
*/
bool transmit(uint32_t id, const uint8_t* data, uint8_t len);
bool transmit(uint32_t id, const uint8_t* data, uint8_t len, bool echo = true);
/**
* Enable/disable raw frame logging (candump-style capture of EVERY frame).
@@ -178,10 +187,9 @@ namespace CANDriver {
void setVerboseDecode(bool enabled);
/**
* UI event handler for CAN toggle switch
* @param e LVGL event
* Settings-screen switch: start/stop the CAN task and remember the choice in NVS.
*/
void onCANToggle(lv_event_t *e);
void setEnabled(bool enabled);
}
#endif // _CAN_DRIVER_H
+114 -20
View File
@@ -1,8 +1,8 @@
/**
* automotive_data.h
*
* Shared wire contract between Controller A (ESP32-S3-Touch-LCD-5B) and
* Controller B (ESP32-S3-LCD-1.3).
* Shared wire contract between Main CTRL (ESP32-S3-Touch-LCD-5B) and
* Inst. Cluster (ESP32-S3-LCD-1.3).
*
* THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS. Copy it across whenever it
* changes and bump PACKET_VERSION; B rejects frames with any other version.
@@ -16,6 +16,13 @@
* - link_config_t: Patrol gauge calibration + alert thresholds, edited on A,
* executed on B (tach + coolant PWM outputs)
* - the same frames go out on UART1 and ESP-NOW; B dedupes by packet_id
*
* v2 additions (2026-09-27, PACKET_VERSION unchanged - DATA/CONFIG are the same
* bytes, an older B counts the new types as FRAME_ERR_TYPE and carries on):
* - STATUS B -> A (ESP-NOW unicast): B's version, OTA phase, uptime
* - PAIR A -> B (UART wire ONLY): the shared secret for SECURE frames
* - SECURE A -> B (ESP-NOW unicast): AES-256-GCM envelope carrying an
* OTA_CMD or WIFI_CREDS payload. See ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md
*/
#ifndef _AUTOMOTIVE_DATA_H
@@ -38,8 +45,8 @@
// (B hops until it hears A, then locks)
// NOTE: UART pin assignments are controller-specific:
// - Controller A (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B)
// - Controller B (1.3): platformio.ini (RX IO1)
// - Main CTRL (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B)
// - Inst. Cluster (1.3): platformio.ini (RX IO1)
// ============================================================================
// FRAME FORMAT (identical on UART and ESP-NOW)
@@ -53,12 +60,19 @@
#define PACKET_END_BYTE 0x55
#define PACKET_VERSION 0x02
#define PACKET_TYPE_DATA 0x01 // payload = automotive_data_t
#define PACKET_TYPE_CONFIG 0x02 // payload = link_config_t
#define PACKET_TYPE_DATA 0x01 // A -> B payload = automotive_data_t
#define PACKET_TYPE_CONFIG 0x02 // A -> B payload = link_config_t
#define PACKET_TYPE_STATUS 0x03 // B -> A payload = link_status_t (ESP-NOW unicast)
#define PACKET_TYPE_PAIR 0x04 // A -> B payload = link_pair_t (UART wire only, never radio)
#define PACKET_TYPE_SECURE 0x05 // A -> B payload = secure envelope, see LINK MAINTENANCE below
// Inner types carried inside a SECURE envelope (never on the wire in the clear):
#define LINK_INNER_OTA_CMD 0x11 // link_ota_cmd_t
#define LINK_INNER_WIFI_CREDS 0x12 // link_wifi_creds_t
#define PACKET_HEADER_SIZE 4 // start, version, type, length
#define PACKET_TRAILER_SIZE 2 // checksum, end
#define PACKET_MAX_PAYLOAD 64
#define PACKET_MAX_PAYLOAD 160 // was 64 until 2026-09-27; SECURE(WIFI_CREDS) needs 127.
// Whole frame 166 B < ESP-NOW's 250 B limit.
#define PACKET_MAX_SIZE (PACKET_HEADER_SIZE + PACKET_MAX_PAYLOAD + PACKET_TRAILER_SIZE)
// ============================================================================
@@ -76,7 +90,7 @@ typedef enum {
LEVER_UNKNOWN = 0xFF
} gear_lever_t;
// Controller A's internal gear enum (CAN decode helpers below use it). Not on
// Main CTRL's internal gear enum (CAN decode helpers below use it). Not on
// the wire any more - B never sees it.
typedef enum {
GEAR_PARK = 0,
@@ -201,6 +215,88 @@ static inline void link_config_defaults(link_config_t* c) {
c->battery_low_x100 = 1100;
}
// ============================================================================
// LINK MAINTENANCE FRAMES (2026-09-27) - Inst. Cluster firmware updates
// ============================================================================
//
// B pulls its own signed release over Wi-Fi; A only hands it the credentials
// and the trigger. Both repos are public, so nothing secret is compiled in:
// the shared key is generated on A at pairing time and travels to B over the
// UART wire only. Everything A later sends B by radio that matters (Wi-Fi
// credentials, OTA commands) goes inside a SECURE envelope under that key.
// STATUS frames carry nothing secret and go in the clear.
#define LINK_KEY_LEN 32 // AES-256
#define LINK_NONCE_LEN 12 // GCM IV, random per frame
#define LINK_TAG_LEN 16 // GCM tag
#define LINK_STATUS_PERIOD_MS 5000 // B -> A STATUS cadence
#define LINK_STATUS_TIMEOUT_MS 15000 // A: B "not heard" after this
// --- PAIR (A -> B, wire only) -----------------------------------------------
#define LINK_PAIR_MAGIC 0x52494150UL // "PAIR"
typedef struct __attribute__((packed)) {
uint32_t magic; // LINK_PAIR_MAGIC - guards against a torn frame
uint8_t key[LINK_KEY_LEN]; // the shared secret; both sides keep it in NVS
uint8_t a_mac[6]; // A's STA MAC: the only sender B accepts SECURE frames from
} link_pair_t; // 42 bytes
// --- STATUS (B -> A, ESP-NOW unicast, every LINK_STATUS_PERIOD_MS) ----------
// ota_phase mirrors Main CTRL's Ota::phase_t so one UI renders both.
#define LINK_OTA_IDLE 0
#define LINK_OTA_CHECKING 1
#define LINK_OTA_UP_TO_DATE 2
#define LINK_OTA_AVAILABLE 3
#define LINK_OTA_INSTALLING 4
#define LINK_OTA_FAILED 5
#define LINK_STATUS_PAIRED (1 << 0) // B holds a pairing key
#define LINK_STATUS_HAVE_WIFI (1 << 1) // B holds Wi-Fi credentials
#define LINK_STATUS_WIFI_JOINED (1 << 2) // B is currently on the network (during a job)
#define LINK_STATUS_PENDING_VERIFY (1 << 3) // B runs a fresh image not yet confirmed
typedef struct __attribute__((packed)) {
char version[16]; // B's firmware version ("dev" for local builds)
uint8_t ota_phase; // LINK_OTA_*
uint8_t ota_progress; // 0..100 while installing
uint8_t flags; // LINK_STATUS_*
uint8_t reserved;
uint16_t key_fp; // first two bytes of SHA-256(pairing key); 0 = unpaired.
// Lets A see "paired with MY key" vs "paired with an old one".
uint32_t uptime_s;
uint32_t free_heap; // internal heap free, bytes
char latest[16]; // latest release tag B knows of ("" = never checked)
char message[32]; // failure reason when ota_phase == LINK_OTA_FAILED
} link_status_t; // 78 bytes
// --- OTA_CMD (inner, A -> B) ------------------------------------------------
#define LINK_OTA_CMD_CHECK 1
#define LINK_OTA_CMD_INSTALL 2
#define LINK_OTA_CMD_ROLLBACK 3
#define LINK_OTA_FORCE (1 << 0) // reinstall even if versions match
typedef struct __attribute__((packed)) {
uint8_t cmd; // LINK_OTA_CMD_*
uint8_t flags; // LINK_OTA_FORCE
uint32_t nonce; // random; B drops a repeat of a recently seen one
} link_ota_cmd_t; // 6 bytes
// --- WIFI_CREDS (inner, A -> B) ---------------------------------------------
#define LINK_WIFI_SET 1
#define LINK_WIFI_FORGET 2
typedef struct __attribute__((packed)) {
uint8_t action; // LINK_WIFI_*
char ssid[33];
char pass[64];
} link_wifi_creds_t; // 98 bytes
// --- SECURE envelope ---------------------------------------------------------
// payload = nonce[12] | tag[16] | ciphertext
// ciphertext = AES-256-GCM(key, nonce, plaintext = inner_type | inner_payload)
// Helpers that do the encryption live in protocol/link_secure.h (mbedtls).
#define LINK_SECURE_OVERHEAD (LINK_NONCE_LEN + LINK_TAG_LEN)
#define LINK_SECURE_MAX_INNER (PACKET_MAX_PAYLOAD - LINK_SECURE_OVERHEAD) // 132: 1 + 98 fits
// ============================================================================
// CAN BUS ID MAPPINGS (BMW-Specific)
// ============================================================================
@@ -413,6 +509,12 @@ static inline frame_status_t frame_parse(const uint8_t* f, size_t n,
if (l != sizeof(automotive_data_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_CONFIG) {
if (l != sizeof(link_config_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_STATUS) {
if (l != sizeof(link_status_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_PAIR) {
if (l != sizeof(link_pair_t)) return FRAME_ERR_TYPE;
} else if (t == PACKET_TYPE_SECURE) {
if (l < LINK_SECURE_OVERHEAD + 1) return FRAME_ERR_TYPE; // at least the inner type byte
} else {
return FRAME_ERR_TYPE;
}
@@ -654,7 +756,7 @@ static inline const char* gear_to_string(gear_position_t gear) {
* @return Pointer to buffer
*/
static inline char* format_temperature(int16_t temp_x10, char* buffer) {
// Plain "C": Controller B's UI font has no degree-sign glyph.
// Plain "C": Inst. Cluster's UI font has no degree-sign glyph.
sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10));
return buffer;
}
@@ -670,16 +772,8 @@ static inline char* format_voltage(uint16_t voltage_x100, char* buffer) {
return buffer;
}
// ============================================================================
// DEFAULT/TEST VALUES
// ============================================================================
// Default values for testing (before CAN data is available)
#define DEFAULT_GEAR_LEVER LEVER_PARK
#define DEFAULT_GEARBOX_TEMP 850 // 85.0°C
#define DEFAULT_ENGINE_OIL_TEMP 920 // 92.0°C
#define DEFAULT_COOLANT_TEMP 890 // 89.0°C
#define DEFAULT_BATTERY_VOLTAGE 1245 // 12.45V
#define DEFAULT_ALERTS 0x0000 // No alerts
// No default / test values: a field is only ever filled from a CAN frame, and
// its VALID_FLAG_* bit says so. Removed 2026-09-28 - the bench defaults
// (89 / 85 degC, 12.45 V) looked like real readings on Inst. Cluster.
#endif // _AUTOMOTIVE_DATA_H
+93
View File
@@ -0,0 +1,93 @@
/**
* link_secure.h - the SECURE envelope of the A <-> B link (see automotive_data.h).
*
* THIS FILE MUST BE BYTE-IDENTICAL IN BOTH REPOS, like automotive_data.h.
*
* payload = nonce[12] | tag[16] | AES-256-GCM(key, nonce, inner_type | inner)
*
* Both cores ship mbedtls (2.28 on Inst. Cluster's IDF 4.4, 3.x on Controller
* A's IDF 5.5); the GCM calls are the same, only SHA-256's name differs.
*/
#ifndef LINK_SECURE_H
#define LINK_SECURE_H
#include "automotive_data.h"
#include <mbedtls/gcm.h>
#include <mbedtls/sha256.h>
#include <mbedtls/version.h>
#if __has_include(<esp_random.h>)
#include <esp_random.h>
#else
#include <esp_system.h> // IDF 4.4: esp_random / esp_fill_random live here
#endif
/** First two bytes of SHA-256(key), never 0 (0 means "unpaired" on the wire). */
static inline uint16_t link_key_fingerprint(const uint8_t key[LINK_KEY_LEN]) {
uint8_t h[32];
#if MBEDTLS_VERSION_MAJOR >= 3
mbedtls_sha256(key, LINK_KEY_LEN, h, 0);
#else
mbedtls_sha256_ret(key, LINK_KEY_LEN, h, 0);
#endif
uint16_t fp = (uint16_t)((h[0] << 8) | h[1]);
return fp ? fp : 1;
}
/**
* Seal inner_type + inner into a SECURE payload.
* @param out buffer of PACKET_MAX_PAYLOAD bytes
* @return payload length, or 0 on error / oversize
*/
static inline size_t link_secure_seal(const uint8_t key[LINK_KEY_LEN], uint8_t inner_type,
const void* inner, size_t inner_len, uint8_t* out) {
if (inner_len + 1 > LINK_SECURE_MAX_INNER) return 0;
uint8_t plain[LINK_SECURE_MAX_INNER];
plain[0] = inner_type;
memcpy(&plain[1], inner, inner_len);
size_t n = inner_len + 1;
uint8_t* nonce = out;
uint8_t* tag = out + LINK_NONCE_LEN;
uint8_t* ct = out + LINK_SECURE_OVERHEAD;
esp_fill_random(nonce, LINK_NONCE_LEN);
mbedtls_gcm_context g;
mbedtls_gcm_init(&g);
int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8);
if (rc == 0) {
rc = mbedtls_gcm_crypt_and_tag(&g, MBEDTLS_GCM_ENCRYPT, n, nonce, LINK_NONCE_LEN,
NULL, 0, plain, ct, LINK_TAG_LEN, tag);
}
mbedtls_gcm_free(&g);
return rc == 0 ? LINK_SECURE_OVERHEAD + n : 0;
}
/**
* Open a SECURE payload. On success *inner_type and inner (LINK_SECURE_MAX_INNER
* bytes) are filled; *inner_len excludes the type byte.
*/
static inline bool link_secure_open(const uint8_t key[LINK_KEY_LEN], const uint8_t* payload, size_t len,
uint8_t* inner_type, uint8_t* inner, size_t* inner_len) {
if (len < LINK_SECURE_OVERHEAD + 1 || len > PACKET_MAX_PAYLOAD) return false;
size_t n = len - LINK_SECURE_OVERHEAD;
uint8_t plain[LINK_SECURE_MAX_INNER];
mbedtls_gcm_context g;
mbedtls_gcm_init(&g);
int rc = mbedtls_gcm_setkey(&g, MBEDTLS_CIPHER_ID_AES, key, LINK_KEY_LEN * 8);
if (rc == 0) {
rc = mbedtls_gcm_auth_decrypt(&g, n, payload, LINK_NONCE_LEN, NULL, 0,
payload + LINK_NONCE_LEN, LINK_TAG_LEN,
payload + LINK_SECURE_OVERHEAD, plain);
}
mbedtls_gcm_free(&g);
if (rc != 0) return false;
*inner_type = plain[0];
*inner_len = n - 1;
memcpy(inner, &plain[1], n - 1);
return true;
}
#endif // LINK_SECURE_H
-8
View File
@@ -1,8 +0,0 @@
SET(SOURCES screens/ui_Settings_Screen.c
ui_theme_manager.c
ui_themes.c
ui.c
components/ui_comp_hook.c
ui_helpers.c)
add_library(ui ${SOURCES})
-5
View File
@@ -1,5 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD
-6
View File
@@ -1,6 +0,0 @@
screens/ui_Settings_Screen.c
ui_theme_manager.c
ui_themes.c
ui.c
components/ui_comp_hook.c
ui_helpers.c
-9
View File
@@ -1,9 +0,0 @@
{
"project_name": "SquareLine_Project.spj",
"datetime": "2025-11-09T17:09:26.2274380+01:00",
"editor_version": "1.5.4",
"project_version": 60,
"user": "Goxhe Altin",
"export_datetime": "2025-11-09T17:09:28.3122290+01:00",
"export_user": "Goxhe Altin"
}
-552
View File
@@ -1,552 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#include "../ui.h"
// Hand-coded Driveline screen (src/modules/driveline_screen.cpp) - replaces Home
void app_show_driveline(void);
lv_obj_t * uic_Settings_Loading_Spinner;
lv_obj_t * uic_Settings_Loading_Container;
lv_obj_t * uic_CPU_Values_LBL;
lv_obj_t * uic_FPS_Values_LBL;
lv_obj_t * uic_Device_State_Values_LBL;
lv_obj_t * uic_CPU_Static_LBL;
lv_obj_t * uic_FPS_Static_LBL;
lv_obj_t * uic_Static_LBLS_Container;
lv_obj_t * uic_Device_State_Container;
lv_obj_t * uic_Keyboard;
lv_obj_t * uic_Wifi_Passkey_TB;
lv_obj_t * uic_Select_SSID_BTN;
lv_obj_t * uic_Wifi_Container;
lv_obj_t * uic_Enable_Debug_LBL;
lv_obj_t * uic_Toggle_Debug_Switch;
lv_obj_t * uic_Debug_CTRL_Panel;
lv_obj_t * uic_Enable_BLE_LBL;
lv_obj_t * uic_Toggle_BLE_Switch;
lv_obj_t * uic_BLE_CTRL_Panel;
lv_obj_t * uic_Enable_Wifi_LBL;
lv_obj_t * uic_Toggle_Wifi_Switch;
lv_obj_t * uic_Wifi_CTRL_Panel;
lv_obj_t * uic_Enable_UART_LBL;
lv_obj_t * uic_Toggle_UART_Switch;
lv_obj_t * uic_UART_CTRL_Panel;
lv_obj_t * uic_Enable_CAN_Bus_LBL;
lv_obj_t * uic_Toggle_CAN_Bus_Switch;
lv_obj_t * uic_CAN_Bus_CTRL_Panel;
lv_obj_t * uic_Settings_CTRL_Container;
lv_obj_t * uic_Main_Container;
lv_obj_t * uic_Settings_Screen_LBL;
lv_obj_t * uic_Settings_Screen;
lv_obj_t * ui_Settings_Screen = NULL;
lv_obj_t * ui_Settings_Screen_LBL = NULL;
lv_obj_t * ui_Main_Container = NULL;
lv_obj_t * ui_Settings_CTRL_Container = NULL;
lv_obj_t * ui_CAN_Bus_CTRL_Panel = NULL;
lv_obj_t * ui_Toggle_CAN_Bus_Switch = NULL;
lv_obj_t * ui_Enable_CAN_Bus_LBL = NULL;
lv_obj_t * ui_UART_CTRL_Panel = NULL;
lv_obj_t * ui_Toggle_UART_Switch = NULL;
lv_obj_t * ui_Enable_UART_LBL = NULL;
lv_obj_t * ui_Wifi_CTRL_Panel = NULL;
lv_obj_t * ui_Toggle_Wifi_Switch = NULL;
lv_obj_t * ui_Enable_Wifi_LBL = NULL;
lv_obj_t * ui_BLE_CTRL_Panel = NULL;
lv_obj_t * ui_Toggle_BLE_Switch = NULL;
lv_obj_t * ui_Enable_BLE_LBL = NULL;
lv_obj_t * ui_Debug_CTRL_Panel = NULL;
lv_obj_t * ui_Toggle_Debug_Switch = NULL;
lv_obj_t * ui_Enable_Debug_LBL = NULL;
lv_obj_t * ui_Wifi_Container = NULL;
lv_obj_t * ui_Select_SSID_BTN = NULL;
lv_obj_t * ui_Wifi_Passkey_TB = NULL;
lv_obj_t * ui_Keyboard = NULL;
lv_obj_t * ui_Device_State_Container = NULL;
lv_obj_t * ui_Static_LBLS_Container = NULL;
lv_obj_t * ui_FPS_Static_LBL = NULL;
lv_obj_t * ui_CPU_Static_LBL = NULL;
lv_obj_t * ui_Device_State_Values_LBL = NULL;
lv_obj_t * ui_FPS_Values_LBL = NULL;
lv_obj_t * ui_CPU_Values_LBL = NULL;
lv_obj_t * ui_Settings_Loading_Container = NULL;
lv_obj_t * ui_Settings_Loading_Spinner = NULL;
// event funtions
void ui_event_Settings_Screen(lv_event_t * e)
{
lv_event_code_t event_code = lv_event_get_code(e);
if(event_code == LV_EVENT_GESTURE && lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act());
app_show_driveline(); // Home screen removed; back goes to the Driveline screen
}
}
void ui_event_Toggle_UART_Switch(lv_event_t * e)
{
lv_event_code_t event_code = lv_event_get_code(e);
if(event_code == LV_EVENT_RELEASED) {
onUARTToggle(e);
}
}
void ui_event_Toggle_Wifi_Switch(lv_event_t * e)
{
lv_event_code_t event_code = lv_event_get_code(e);
if(event_code == LV_EVENT_RELEASED) {
onWifiToggle(e);
}
}
void ui_event_Toggle_CAN_Bus_Switch(lv_event_t * e)
{
lv_event_code_t event_code = lv_event_get_code(e);
if(event_code == LV_EVENT_RELEASED) {
onCANBusToggle(e);
}
}
void ui_event_Toggle_Debug_Switch(lv_event_t * e)
{
lv_event_code_t event_code = lv_event_get_code(e);
if(event_code == LV_EVENT_RELEASED) {
onDebugToggle(e);
}
}
void ui_event_Select_SSID_BTN(lv_event_t * e)
{
lv_event_code_t event_code = lv_event_get_code(e);
if(event_code == LV_EVENT_CLICKED) {
onSelectSSID(e);
}
}
// build funtions
void ui_Settings_Screen_screen_init(void)
{
ui_Settings_Screen = lv_obj_create(NULL);
lv_obj_clear_flag(ui_Settings_Screen, LV_OBJ_FLAG_SCROLLABLE); /// Flags
lv_obj_add_event_cb(ui_Settings_Screen, scr_unloaded_delete_cb, LV_EVENT_SCREEN_UNLOADED,
ui_Settings_Screen_screen_destroy);
ui_Settings_Screen_LBL = lv_label_create(ui_Settings_Screen);
lv_obj_set_width(ui_Settings_Screen_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_Settings_Screen_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_Settings_Screen_LBL, -405);
lv_obj_set_y(ui_Settings_Screen_LBL, -268);
lv_obj_set_align(ui_Settings_Screen_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_Settings_Screen_LBL, "Settings");
lv_obj_set_style_text_font(ui_Settings_Screen_LBL, &lv_font_montserrat_48, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_Main_Container = lv_obj_create(ui_Settings_Screen);
lv_obj_remove_style_all(ui_Main_Container);
lv_obj_set_width(ui_Main_Container, 1024);
lv_obj_set_height(ui_Main_Container, 530);
lv_obj_set_x(ui_Main_Container, 0);
lv_obj_set_y(ui_Main_Container, 34);
lv_obj_set_align(ui_Main_Container, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Main_Container, LV_FLEX_FLOW_ROW_WRAP);
lv_obj_set_flex_align(ui_Main_Container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_Main_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_Settings_CTRL_Container = lv_obj_create(ui_Main_Container);
lv_obj_remove_style_all(ui_Settings_CTRL_Container);
lv_obj_set_width(ui_Settings_CTRL_Container, 410);
lv_obj_set_height(ui_Settings_CTRL_Container, 530);
lv_obj_set_x(ui_Settings_CTRL_Container, -130);
lv_obj_set_y(ui_Settings_CTRL_Container, 8);
lv_obj_set_align(ui_Settings_CTRL_Container, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Settings_CTRL_Container, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(ui_Settings_CTRL_Container, LV_FLEX_ALIGN_SPACE_AROUND, LV_FLEX_ALIGN_CENTER,
LV_FLEX_ALIGN_SPACE_EVENLY);
lv_obj_clear_flag(ui_Settings_CTRL_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_CAN_Bus_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container);
lv_obj_set_width(ui_CAN_Bus_CTRL_Panel, 400);
lv_obj_set_height(ui_CAN_Bus_CTRL_Panel, 100);
lv_obj_set_x(ui_CAN_Bus_CTRL_Panel, 0);
lv_obj_set_y(ui_CAN_Bus_CTRL_Panel, 1);
lv_obj_set_align(ui_CAN_Bus_CTRL_Panel, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_CAN_Bus_CTRL_Panel, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_CAN_Bus_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_CAN_Bus_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags
lv_obj_set_style_bg_color(ui_CAN_Bus_CTRL_Panel, lv_color_hex(0x7F7A9C), LV_PART_MAIN | LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(ui_CAN_Bus_CTRL_Panel, 255, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_Toggle_CAN_Bus_Switch = lv_switch_create(ui_CAN_Bus_CTRL_Panel);
lv_obj_set_width(ui_Toggle_CAN_Bus_Switch, 110);
lv_obj_set_height(ui_Toggle_CAN_Bus_Switch, 60);
lv_obj_set_x(ui_Toggle_CAN_Bus_Switch, -181);
lv_obj_set_y(ui_Toggle_CAN_Bus_Switch, -3);
lv_obj_set_align(ui_Toggle_CAN_Bus_Switch, LV_ALIGN_CENTER);
ui_Enable_CAN_Bus_LBL = lv_label_create(ui_CAN_Bus_CTRL_Panel);
lv_obj_set_width(ui_Enable_CAN_Bus_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_Enable_CAN_Bus_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_Enable_CAN_Bus_LBL, -117);
lv_obj_set_y(ui_Enable_CAN_Bus_LBL, -2);
lv_obj_set_align(ui_Enable_CAN_Bus_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_Enable_CAN_Bus_LBL, "Enable CANBus");
lv_obj_set_style_text_font(ui_Enable_CAN_Bus_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_UART_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container);
lv_obj_set_width(ui_UART_CTRL_Panel, 400);
lv_obj_set_height(ui_UART_CTRL_Panel, 100);
lv_obj_set_x(ui_UART_CTRL_Panel, 0);
lv_obj_set_y(ui_UART_CTRL_Panel, 1);
lv_obj_set_align(ui_UART_CTRL_Panel, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_UART_CTRL_Panel, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_UART_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_UART_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_object_set_themeable_style_property(ui_UART_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR,
_ui_theme_color_panel_backgroung);
ui_object_set_themeable_style_property(ui_UART_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA,
_ui_theme_alpha_panel_backgroung);
ui_Toggle_UART_Switch = lv_switch_create(ui_UART_CTRL_Panel);
lv_obj_set_width(ui_Toggle_UART_Switch, 110);
lv_obj_set_height(ui_Toggle_UART_Switch, 60);
lv_obj_set_x(ui_Toggle_UART_Switch, -181);
lv_obj_set_y(ui_Toggle_UART_Switch, -3);
lv_obj_set_align(ui_Toggle_UART_Switch, LV_ALIGN_CENTER);
ui_Enable_UART_LBL = lv_label_create(ui_UART_CTRL_Panel);
lv_obj_set_width(ui_Enable_UART_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_Enable_UART_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_Enable_UART_LBL, -117);
lv_obj_set_y(ui_Enable_UART_LBL, -2);
lv_obj_set_align(ui_Enable_UART_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_Enable_UART_LBL, "Enable UART");
lv_obj_set_style_text_font(ui_Enable_UART_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_Wifi_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container);
lv_obj_set_width(ui_Wifi_CTRL_Panel, 405);
lv_obj_set_height(ui_Wifi_CTRL_Panel, 100);
lv_obj_set_x(ui_Wifi_CTRL_Panel, 0);
lv_obj_set_y(ui_Wifi_CTRL_Panel, 1);
lv_obj_set_align(ui_Wifi_CTRL_Panel, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Wifi_CTRL_Panel, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_Wifi_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_Wifi_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_object_set_themeable_style_property(ui_Wifi_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR,
_ui_theme_color_panel_backgroung);
ui_object_set_themeable_style_property(ui_Wifi_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA,
_ui_theme_alpha_panel_backgroung);
ui_Toggle_Wifi_Switch = lv_switch_create(ui_Wifi_CTRL_Panel);
lv_obj_set_width(ui_Toggle_Wifi_Switch, 110);
lv_obj_set_height(ui_Toggle_Wifi_Switch, 60);
lv_obj_set_x(ui_Toggle_Wifi_Switch, -181);
lv_obj_set_y(ui_Toggle_Wifi_Switch, -3);
lv_obj_set_align(ui_Toggle_Wifi_Switch, LV_ALIGN_CENTER);
lv_obj_add_state(ui_Toggle_Wifi_Switch, LV_STATE_DISABLED); /// States
ui_Enable_Wifi_LBL = lv_label_create(ui_Wifi_CTRL_Panel);
lv_obj_set_width(ui_Enable_Wifi_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_Enable_Wifi_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_Enable_Wifi_LBL, -117);
lv_obj_set_y(ui_Enable_Wifi_LBL, -2);
lv_obj_set_align(ui_Enable_Wifi_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_Enable_Wifi_LBL, "Enable Wifi");
lv_obj_set_style_text_font(ui_Enable_Wifi_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_BLE_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container);
lv_obj_set_width(ui_BLE_CTRL_Panel, 400);
lv_obj_set_height(ui_BLE_CTRL_Panel, 100);
lv_obj_set_x(ui_BLE_CTRL_Panel, 0);
lv_obj_set_y(ui_BLE_CTRL_Panel, 1);
lv_obj_set_align(ui_BLE_CTRL_Panel, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_BLE_CTRL_Panel, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_BLE_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_BLE_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_object_set_themeable_style_property(ui_BLE_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR,
_ui_theme_color_panel_backgroung);
ui_object_set_themeable_style_property(ui_BLE_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA,
_ui_theme_alpha_panel_backgroung);
ui_Toggle_BLE_Switch = lv_switch_create(ui_BLE_CTRL_Panel);
lv_obj_set_width(ui_Toggle_BLE_Switch, 110);
lv_obj_set_height(ui_Toggle_BLE_Switch, 60);
lv_obj_set_x(ui_Toggle_BLE_Switch, -181);
lv_obj_set_y(ui_Toggle_BLE_Switch, -3);
lv_obj_set_align(ui_Toggle_BLE_Switch, LV_ALIGN_CENTER);
lv_obj_add_state(ui_Toggle_BLE_Switch, LV_STATE_DISABLED); /// States
ui_Enable_BLE_LBL = lv_label_create(ui_BLE_CTRL_Panel);
lv_obj_set_width(ui_Enable_BLE_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_Enable_BLE_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_Enable_BLE_LBL, -117);
lv_obj_set_y(ui_Enable_BLE_LBL, -2);
lv_obj_set_align(ui_Enable_BLE_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_Enable_BLE_LBL, "Enable BLE");
lv_obj_set_style_text_font(ui_Enable_BLE_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_Debug_CTRL_Panel = lv_obj_create(ui_Settings_CTRL_Container);
lv_obj_set_width(ui_Debug_CTRL_Panel, 400);
lv_obj_set_height(ui_Debug_CTRL_Panel, 100);
lv_obj_set_x(ui_Debug_CTRL_Panel, 0);
lv_obj_set_y(ui_Debug_CTRL_Panel, 1);
lv_obj_set_align(ui_Debug_CTRL_Panel, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Debug_CTRL_Panel, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_Debug_CTRL_Panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_Debug_CTRL_Panel, LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_object_set_themeable_style_property(ui_Debug_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_COLOR,
_ui_theme_color_panel_backgroung);
ui_object_set_themeable_style_property(ui_Debug_CTRL_Panel, LV_PART_MAIN | LV_STATE_DEFAULT, LV_STYLE_BG_OPA,
_ui_theme_alpha_panel_backgroung);
ui_Toggle_Debug_Switch = lv_switch_create(ui_Debug_CTRL_Panel);
lv_obj_set_width(ui_Toggle_Debug_Switch, 110);
lv_obj_set_height(ui_Toggle_Debug_Switch, 60);
lv_obj_set_x(ui_Toggle_Debug_Switch, -181);
lv_obj_set_y(ui_Toggle_Debug_Switch, -3);
lv_obj_set_align(ui_Toggle_Debug_Switch, LV_ALIGN_CENTER);
ui_Enable_Debug_LBL = lv_label_create(ui_Debug_CTRL_Panel);
lv_obj_set_width(ui_Enable_Debug_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_Enable_Debug_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_Enable_Debug_LBL, -117);
lv_obj_set_y(ui_Enable_Debug_LBL, -2);
lv_obj_set_align(ui_Enable_Debug_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_Enable_Debug_LBL, "Enable Debug");
lv_obj_set_style_text_font(ui_Enable_Debug_LBL, &lv_font_montserrat_30, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_Wifi_Container = lv_obj_create(ui_Main_Container);
lv_obj_remove_style_all(ui_Wifi_Container);
lv_obj_set_width(ui_Wifi_Container, 610);
lv_obj_set_height(ui_Wifi_Container, 530);
lv_obj_set_x(ui_Wifi_Container, -100);
lv_obj_set_y(ui_Wifi_Container, 8);
lv_obj_set_align(ui_Wifi_Container, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Wifi_Container, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(ui_Wifi_Container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_clear_flag(ui_Wifi_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_Select_SSID_BTN = lv_btn_create(ui_Wifi_Container);
lv_obj_set_width(ui_Select_SSID_BTN, 668);
lv_obj_set_height(ui_Select_SSID_BTN, 50);
lv_obj_set_x(ui_Select_SSID_BTN, 7);
lv_obj_set_y(ui_Select_SSID_BTN, -4);
lv_obj_set_align(ui_Select_SSID_BTN, LV_ALIGN_CENTER);
lv_obj_add_flag(ui_Select_SSID_BTN, LV_OBJ_FLAG_HIDDEN); /// Flags
lv_obj_set_style_bg_color(ui_Select_SSID_BTN, lv_color_hex(0x7F7A9C), LV_PART_MAIN | LV_STATE_DEFAULT);
lv_obj_set_style_bg_opa(ui_Select_SSID_BTN, 255, LV_PART_MAIN | LV_STATE_DEFAULT);
ui_Wifi_Passkey_TB = lv_textarea_create(ui_Wifi_Container);
lv_obj_set_width(ui_Wifi_Passkey_TB, 200);
lv_obj_set_height(ui_Wifi_Passkey_TB, LV_SIZE_CONTENT); /// 70
lv_obj_set_x(ui_Wifi_Passkey_TB, 129);
lv_obj_set_y(ui_Wifi_Passkey_TB, -173);
lv_obj_set_align(ui_Wifi_Passkey_TB, LV_ALIGN_CENTER);
lv_textarea_set_placeholder_text(ui_Wifi_Passkey_TB, "Placeholder...");
lv_textarea_set_one_line(ui_Wifi_Passkey_TB, true);
lv_obj_add_flag(ui_Wifi_Passkey_TB, LV_OBJ_FLAG_HIDDEN); /// Flags
ui_Keyboard = lv_keyboard_create(ui_Settings_Screen);
lv_obj_set_width(ui_Keyboard, 1012);
lv_obj_set_height(ui_Keyboard, 268);
lv_obj_set_x(ui_Keyboard, 3);
lv_obj_set_y(ui_Keyboard, 161);
lv_obj_set_align(ui_Keyboard, LV_ALIGN_CENTER);
lv_obj_add_flag(ui_Keyboard, LV_OBJ_FLAG_HIDDEN); /// Flags
ui_Device_State_Container = lv_obj_create(ui_Settings_Screen);
lv_obj_remove_style_all(ui_Device_State_Container);
lv_obj_set_width(ui_Device_State_Container, 75);
lv_obj_set_height(ui_Device_State_Container, 30);
lv_obj_set_x(ui_Device_State_Container, 470);
lv_obj_set_y(ui_Device_State_Container, -282);
lv_obj_set_align(ui_Device_State_Container, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Device_State_Container, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_Device_State_Container, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_add_flag(ui_Device_State_Container, LV_OBJ_FLAG_HIDDEN); /// Flags
lv_obj_clear_flag(ui_Device_State_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_Static_LBLS_Container = lv_obj_create(ui_Device_State_Container);
lv_obj_remove_style_all(ui_Static_LBLS_Container);
lv_obj_set_width(ui_Static_LBLS_Container, 35);
lv_obj_set_height(ui_Static_LBLS_Container, 30);
lv_obj_set_align(ui_Static_LBLS_Container, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Static_LBLS_Container, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(ui_Static_LBLS_Container, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_START);
lv_obj_clear_flag(ui_Static_LBLS_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_FPS_Static_LBL = lv_label_create(ui_Static_LBLS_Container);
lv_obj_set_width(ui_FPS_Static_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_FPS_Static_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_FPS_Static_LBL, -176);
lv_obj_set_y(ui_FPS_Static_LBL, 34);
lv_obj_set_align(ui_FPS_Static_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_FPS_Static_LBL, "FPS:");
ui_CPU_Static_LBL = lv_label_create(ui_Static_LBLS_Container);
lv_obj_set_width(ui_CPU_Static_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_CPU_Static_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_CPU_Static_LBL, -1);
lv_obj_set_y(ui_CPU_Static_LBL, -1);
lv_obj_set_align(ui_CPU_Static_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_CPU_Static_LBL, "CPU:");
ui_Device_State_Values_LBL = lv_obj_create(ui_Device_State_Container);
lv_obj_remove_style_all(ui_Device_State_Values_LBL);
lv_obj_set_width(ui_Device_State_Values_LBL, 35);
lv_obj_set_height(ui_Device_State_Values_LBL, 30);
lv_obj_set_align(ui_Device_State_Values_LBL, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Device_State_Values_LBL, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(ui_Device_State_Values_LBL, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_clear_flag(ui_Device_State_Values_LBL, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_FPS_Values_LBL = lv_label_create(ui_Device_State_Values_LBL);
lv_obj_set_width(ui_FPS_Values_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_FPS_Values_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_FPS_Values_LBL, -176);
lv_obj_set_y(ui_FPS_Values_LBL, 34);
lv_obj_set_align(ui_FPS_Values_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_FPS_Values_LBL, "0");
ui_CPU_Values_LBL = lv_label_create(ui_Device_State_Values_LBL);
lv_obj_set_width(ui_CPU_Values_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_height(ui_CPU_Values_LBL, LV_SIZE_CONTENT); /// 1
lv_obj_set_x(ui_CPU_Values_LBL, -1);
lv_obj_set_y(ui_CPU_Values_LBL, -1);
lv_obj_set_align(ui_CPU_Values_LBL, LV_ALIGN_CENTER);
lv_label_set_text(ui_CPU_Values_LBL, "0%");
ui_Settings_Loading_Container = lv_obj_create(ui_Settings_Screen);
lv_obj_remove_style_all(ui_Settings_Loading_Container);
lv_obj_set_width(ui_Settings_Loading_Container, 1024);
lv_obj_set_height(ui_Settings_Loading_Container, 600);
lv_obj_set_align(ui_Settings_Loading_Container, LV_ALIGN_CENTER);
lv_obj_set_flex_flow(ui_Settings_Loading_Container, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(ui_Settings_Loading_Container, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(ui_Settings_Loading_Container, LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_SCROLLABLE); /// Flags
ui_Settings_Loading_Spinner = lv_spinner_create(ui_Settings_Loading_Container, 1000, 90);
lv_obj_set_width(ui_Settings_Loading_Spinner, 80);
lv_obj_set_height(ui_Settings_Loading_Spinner, 80);
lv_obj_set_x(ui_Settings_Loading_Spinner, -22);
lv_obj_set_y(ui_Settings_Loading_Spinner, -22);
lv_obj_set_align(ui_Settings_Loading_Spinner, LV_ALIGN_CENTER);
lv_obj_add_flag(ui_Settings_Loading_Spinner, LV_OBJ_FLAG_HIDDEN); /// Flags
lv_obj_clear_flag(ui_Settings_Loading_Spinner, LV_OBJ_FLAG_CLICKABLE); /// Flags
lv_obj_add_event_cb(ui_Toggle_UART_Switch, ui_event_Toggle_UART_Switch, LV_EVENT_ALL, NULL);
lv_obj_add_event_cb(ui_Toggle_Wifi_Switch, ui_event_Toggle_Wifi_Switch, LV_EVENT_ALL, NULL);
lv_obj_add_event_cb(ui_Toggle_CAN_Bus_Switch, ui_event_Toggle_CAN_Bus_Switch, LV_EVENT_ALL, NULL);
lv_obj_add_event_cb(ui_Toggle_Debug_Switch, ui_event_Toggle_Debug_Switch, LV_EVENT_ALL, NULL);
lv_obj_add_event_cb(ui_Select_SSID_BTN, ui_event_Select_SSID_BTN, LV_EVENT_ALL, NULL);
lv_obj_add_event_cb(ui_Settings_Screen, ui_event_Settings_Screen, LV_EVENT_ALL, NULL);
uic_Settings_Screen = ui_Settings_Screen;
uic_Settings_Screen_LBL = ui_Settings_Screen_LBL;
uic_Main_Container = ui_Main_Container;
uic_Settings_CTRL_Container = ui_Settings_CTRL_Container;
uic_CAN_Bus_CTRL_Panel = ui_CAN_Bus_CTRL_Panel;
uic_Toggle_CAN_Bus_Switch = ui_Toggle_CAN_Bus_Switch;
uic_Enable_CAN_Bus_LBL = ui_Enable_CAN_Bus_LBL;
uic_UART_CTRL_Panel = ui_UART_CTRL_Panel;
uic_Toggle_UART_Switch = ui_Toggle_UART_Switch;
uic_Enable_UART_LBL = ui_Enable_UART_LBL;
uic_Wifi_CTRL_Panel = ui_Wifi_CTRL_Panel;
uic_Toggle_Wifi_Switch = ui_Toggle_Wifi_Switch;
uic_Enable_Wifi_LBL = ui_Enable_Wifi_LBL;
uic_BLE_CTRL_Panel = ui_BLE_CTRL_Panel;
uic_Toggle_BLE_Switch = ui_Toggle_BLE_Switch;
uic_Enable_BLE_LBL = ui_Enable_BLE_LBL;
uic_Debug_CTRL_Panel = ui_Debug_CTRL_Panel;
uic_Toggle_Debug_Switch = ui_Toggle_Debug_Switch;
uic_Enable_Debug_LBL = ui_Enable_Debug_LBL;
uic_Wifi_Container = ui_Wifi_Container;
uic_Select_SSID_BTN = ui_Select_SSID_BTN;
uic_Wifi_Passkey_TB = ui_Wifi_Passkey_TB;
uic_Keyboard = ui_Keyboard;
uic_Device_State_Container = ui_Device_State_Container;
uic_Static_LBLS_Container = ui_Static_LBLS_Container;
uic_FPS_Static_LBL = ui_FPS_Static_LBL;
uic_CPU_Static_LBL = ui_CPU_Static_LBL;
uic_Device_State_Values_LBL = ui_Device_State_Values_LBL;
uic_FPS_Values_LBL = ui_FPS_Values_LBL;
uic_CPU_Values_LBL = ui_CPU_Values_LBL;
uic_Settings_Loading_Container = ui_Settings_Loading_Container;
uic_Settings_Loading_Spinner = ui_Settings_Loading_Spinner;
}
void ui_Settings_Screen_screen_destroy(void)
{
if(ui_Settings_Screen) lv_obj_del(ui_Settings_Screen);
// NULL screen variables
uic_Settings_Screen = NULL;
ui_Settings_Screen = NULL;
uic_Settings_Screen_LBL = NULL;
ui_Settings_Screen_LBL = NULL;
uic_Main_Container = NULL;
ui_Main_Container = NULL;
uic_Settings_CTRL_Container = NULL;
ui_Settings_CTRL_Container = NULL;
uic_CAN_Bus_CTRL_Panel = NULL;
ui_CAN_Bus_CTRL_Panel = NULL;
uic_Toggle_CAN_Bus_Switch = NULL;
ui_Toggle_CAN_Bus_Switch = NULL;
uic_Enable_CAN_Bus_LBL = NULL;
ui_Enable_CAN_Bus_LBL = NULL;
uic_UART_CTRL_Panel = NULL;
ui_UART_CTRL_Panel = NULL;
uic_Toggle_UART_Switch = NULL;
ui_Toggle_UART_Switch = NULL;
uic_Enable_UART_LBL = NULL;
ui_Enable_UART_LBL = NULL;
uic_Wifi_CTRL_Panel = NULL;
ui_Wifi_CTRL_Panel = NULL;
uic_Toggle_Wifi_Switch = NULL;
ui_Toggle_Wifi_Switch = NULL;
uic_Enable_Wifi_LBL = NULL;
ui_Enable_Wifi_LBL = NULL;
uic_BLE_CTRL_Panel = NULL;
ui_BLE_CTRL_Panel = NULL;
uic_Toggle_BLE_Switch = NULL;
ui_Toggle_BLE_Switch = NULL;
uic_Enable_BLE_LBL = NULL;
ui_Enable_BLE_LBL = NULL;
uic_Debug_CTRL_Panel = NULL;
ui_Debug_CTRL_Panel = NULL;
uic_Toggle_Debug_Switch = NULL;
ui_Toggle_Debug_Switch = NULL;
uic_Enable_Debug_LBL = NULL;
ui_Enable_Debug_LBL = NULL;
uic_Wifi_Container = NULL;
ui_Wifi_Container = NULL;
uic_Select_SSID_BTN = NULL;
ui_Select_SSID_BTN = NULL;
uic_Wifi_Passkey_TB = NULL;
ui_Wifi_Passkey_TB = NULL;
uic_Keyboard = NULL;
ui_Keyboard = NULL;
uic_Device_State_Container = NULL;
ui_Device_State_Container = NULL;
uic_Static_LBLS_Container = NULL;
ui_Static_LBLS_Container = NULL;
uic_FPS_Static_LBL = NULL;
ui_FPS_Static_LBL = NULL;
uic_CPU_Static_LBL = NULL;
ui_CPU_Static_LBL = NULL;
uic_Device_State_Values_LBL = NULL;
ui_Device_State_Values_LBL = NULL;
uic_FPS_Values_LBL = NULL;
ui_FPS_Values_LBL = NULL;
uic_CPU_Values_LBL = NULL;
ui_CPU_Values_LBL = NULL;
uic_Settings_Loading_Container = NULL;
ui_Settings_Loading_Container = NULL;
uic_Settings_Loading_Spinner = NULL;
ui_Settings_Loading_Spinner = NULL;
}
-92
View File
@@ -1,92 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#ifndef UI_SETTINGS_SCREEN_H
#define UI_SETTINGS_SCREEN_H
#ifdef __cplusplus
extern "C" {
#endif
// SCREEN: ui_Settings_Screen
extern void ui_Settings_Screen_screen_init(void);
extern void ui_Settings_Screen_screen_destroy(void);
extern void ui_event_Settings_Screen(lv_event_t * e);
extern lv_obj_t * ui_Settings_Screen;
extern lv_obj_t * ui_Settings_Screen_LBL;
extern lv_obj_t * ui_Main_Container;
extern lv_obj_t * ui_Settings_CTRL_Container;
extern lv_obj_t * ui_CAN_Bus_CTRL_Panel;
extern lv_obj_t * ui_Toggle_CAN_Bus_Switch;
extern lv_obj_t * ui_Enable_CAN_Bus_LBL;
extern lv_obj_t * ui_UART_CTRL_Panel;
extern void ui_event_Toggle_UART_Switch(lv_event_t * e);
extern lv_obj_t * ui_Toggle_UART_Switch;
extern lv_obj_t * ui_Enable_UART_LBL;
extern lv_obj_t * ui_Wifi_CTRL_Panel;
extern void ui_event_Toggle_Wifi_Switch(lv_event_t * e);
extern lv_obj_t * ui_Toggle_Wifi_Switch;
extern lv_obj_t * ui_Enable_Wifi_LBL;
extern lv_obj_t * ui_BLE_CTRL_Panel;
extern lv_obj_t * ui_Toggle_BLE_Switch;
extern lv_obj_t * ui_Enable_BLE_LBL;
extern lv_obj_t * ui_Debug_CTRL_Panel;
extern void ui_event_Toggle_Debug_Switch(lv_event_t * e);
extern lv_obj_t * ui_Toggle_Debug_Switch;
extern lv_obj_t * ui_Enable_Debug_LBL;
extern lv_obj_t * ui_Wifi_Container;
extern void ui_event_Select_SSID_BTN(lv_event_t * e);
extern lv_obj_t * ui_Select_SSID_BTN;
extern lv_obj_t * ui_Wifi_Passkey_TB;
extern lv_obj_t * ui_Keyboard;
extern lv_obj_t * ui_Device_State_Container;
extern lv_obj_t * ui_Static_LBLS_Container;
extern lv_obj_t * ui_FPS_Static_LBL;
extern lv_obj_t * ui_CPU_Static_LBL;
extern lv_obj_t * ui_Device_State_Values_LBL;
extern lv_obj_t * ui_FPS_Values_LBL;
extern lv_obj_t * ui_CPU_Values_LBL;
extern lv_obj_t * ui_Settings_Loading_Container;
extern lv_obj_t * ui_Settings_Loading_Spinner;
// CUSTOM VARIABLES
extern lv_obj_t * uic_Settings_Screen;
extern lv_obj_t * uic_Settings_Screen_LBL;
extern lv_obj_t * uic_Main_Container;
extern lv_obj_t * uic_Settings_CTRL_Container;
extern lv_obj_t * uic_CAN_Bus_CTRL_Panel;
extern lv_obj_t * uic_Toggle_CAN_Bus_Switch;
extern lv_obj_t * uic_Enable_CAN_Bus_LBL;
extern lv_obj_t * uic_UART_CTRL_Panel;
extern lv_obj_t * uic_Toggle_UART_Switch;
extern lv_obj_t * uic_Enable_UART_LBL;
extern lv_obj_t * uic_Wifi_CTRL_Panel;
extern lv_obj_t * uic_Toggle_Wifi_Switch;
extern lv_obj_t * uic_Enable_Wifi_LBL;
extern lv_obj_t * uic_BLE_CTRL_Panel;
extern lv_obj_t * uic_Toggle_BLE_Switch;
extern lv_obj_t * uic_Enable_BLE_LBL;
extern lv_obj_t * uic_Debug_CTRL_Panel;
extern lv_obj_t * uic_Toggle_Debug_Switch;
extern lv_obj_t * uic_Enable_Debug_LBL;
extern lv_obj_t * uic_Wifi_Container;
extern lv_obj_t * uic_Select_SSID_BTN;
extern lv_obj_t * uic_Wifi_Passkey_TB;
extern lv_obj_t * uic_Keyboard;
extern lv_obj_t * uic_Device_State_Container;
extern lv_obj_t * uic_Static_LBLS_Container;
extern lv_obj_t * uic_FPS_Static_LBL;
extern lv_obj_t * uic_CPU_Static_LBL;
extern lv_obj_t * uic_Device_State_Values_LBL;
extern lv_obj_t * uic_FPS_Values_LBL;
extern lv_obj_t * uic_CPU_Values_LBL;
extern lv_obj_t * uic_Settings_Loading_Container;
extern lv_obj_t * uic_Settings_Loading_Spinner;
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
-46
View File
@@ -1,46 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#include "ui.h"
#include "ui_helpers.h"
///////////////////// VARIABLES ////////////////////
// EVENTS
lv_obj_t * ui____initial_actions0;
// IMAGES AND IMAGE SETS
///////////////////// TEST LVGL SETTINGS ////////////////////
#if LV_COLOR_DEPTH != 16
#error "LV_COLOR_DEPTH should be 16bit to match SquareLine Studio's settings"
#endif
#if LV_COLOR_16_SWAP !=0
#error "LV_COLOR_16_SWAP should be 0 to match SquareLine Studio's settings"
#endif
///////////////////// ANIMATIONS ////////////////////
///////////////////// FUNCTIONS ////////////////////
///////////////////// SCREENS ////////////////////
void ui_init(void)
{
lv_disp_t * dispp = lv_disp_get_default();
lv_theme_t * theme = lv_theme_default_init(dispp, lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_RED),
true, LV_FONT_DEFAULT);
lv_disp_set_theme(dispp, theme);
// Home screen removed (2026-09-21): the firmware boots into the hand-coded
// Driveline screen (DrivelineScreen::show() in display_init.cpp). Settings is
// created lazily by _ui_screen_change() when swiped to.
ui____initial_actions0 = lv_obj_create(NULL);
lv_disp_load_scr(ui____initial_actions0);
}
void ui_destroy(void)
{
ui_Settings_Screen_screen_destroy();
}
-48
View File
@@ -1,48 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#ifndef _ESP32_S3_TOUCH_LCD_5B_UI_H
#define _ESP32_S3_TOUCH_LCD_5B_UI_H
#ifdef __cplusplus
extern "C" {
#endif
#if defined __has_include
#if __has_include("lvgl.h")
#include "lvgl.h"
#elif __has_include("lvgl/lvgl.h")
#include "lvgl/lvgl.h"
#else
#include "lvgl.h"
#endif
#else
#include "lvgl.h"
#endif
#include "ui_helpers.h"
#include "ui_events.h"
#include "ui_theme_manager.h"
#include "ui_themes.h"
///////////////////// SCREENS ////////////////////
#include "screens/ui_Settings_Screen.h"
///////////////////// VARIABLES ////////////////////
// EVENTS
extern lv_obj_t * ui____initial_actions0;
// IMAGES AND IMAGE SETS
// UI INIT
void ui_init(void);
void ui_destroy(void);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
-23
View File
@@ -1,23 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#ifndef _UI_EVENTS_H
#define _UI_EVENTS_H
#ifdef __cplusplus
extern "C" {
#endif
void onUARTToggle(lv_event_t * e);
void onWifiToggle(lv_event_t * e);
void onCANBusToggle(lv_event_t * e);
void onDebugToggle(lv_event_t * e);
void onSelectSSID(lv_event_t * e);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
-262
View File
@@ -1,262 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#include "ui_helpers.h"
void _ui_bar_set_property(lv_obj_t * target, int id, int val)
{
if(id == _UI_BAR_PROPERTY_VALUE_WITH_ANIM) lv_bar_set_value(target, val, LV_ANIM_ON);
if(id == _UI_BAR_PROPERTY_VALUE) lv_bar_set_value(target, val, LV_ANIM_OFF);
}
void _ui_basic_set_property(lv_obj_t * target, int id, int val)
{
if(id == _UI_BASIC_PROPERTY_POSITION_X) lv_obj_set_x(target, val);
if(id == _UI_BASIC_PROPERTY_POSITION_Y) lv_obj_set_y(target, val);
if(id == _UI_BASIC_PROPERTY_WIDTH) lv_obj_set_width(target, val);
if(id == _UI_BASIC_PROPERTY_HEIGHT) lv_obj_set_height(target, val);
}
void _ui_dropdown_set_property(lv_obj_t * target, int id, int val)
{
if(id == _UI_DROPDOWN_PROPERTY_SELECTED) lv_dropdown_set_selected(target, val);
}
void _ui_image_set_property(lv_obj_t * target, int id, uint8_t * val)
{
if(id == _UI_IMAGE_PROPERTY_IMAGE) lv_img_set_src(target, val);
}
void _ui_label_set_property(lv_obj_t * target, int id, const char * val)
{
if(id == _UI_LABEL_PROPERTY_TEXT) lv_label_set_text(target, val);
}
void _ui_roller_set_property(lv_obj_t * target, int id, int val)
{
if(id == _UI_ROLLER_PROPERTY_SELECTED_WITH_ANIM) lv_roller_set_selected(target, val, LV_ANIM_ON);
if(id == _UI_ROLLER_PROPERTY_SELECTED) lv_roller_set_selected(target, val, LV_ANIM_OFF);
}
void _ui_slider_set_property(lv_obj_t * target, int id, int val)
{
if(id == _UI_SLIDER_PROPERTY_VALUE_WITH_ANIM) lv_slider_set_value(target, val, LV_ANIM_ON);
if(id == _UI_SLIDER_PROPERTY_VALUE) lv_slider_set_value(target, val, LV_ANIM_OFF);
}
void _ui_screen_change(lv_obj_t ** target, lv_scr_load_anim_t fademode, int spd, int delay, void (*target_init)(void))
{
if(*target == NULL)
target_init();
lv_scr_load_anim(*target, fademode, spd, delay, false);
}
void _ui_arc_increment(lv_obj_t * target, int val)
{
int old = lv_arc_get_value(target);
lv_arc_set_value(target, old + val);
lv_event_send(target, LV_EVENT_VALUE_CHANGED, 0);
}
void _ui_bar_increment(lv_obj_t * target, int val, int anm)
{
int old = lv_bar_get_value(target);
lv_bar_set_value(target, old + val, anm);
}
void _ui_slider_increment(lv_obj_t * target, int val, int anm)
{
int old = lv_slider_get_value(target);
lv_slider_set_value(target, old + val, anm);
lv_event_send(target, LV_EVENT_VALUE_CHANGED, 0);
}
void _ui_keyboard_set_target(lv_obj_t * keyboard, lv_obj_t * textarea)
{
lv_keyboard_set_textarea(keyboard, textarea);
}
void _ui_flag_modify(lv_obj_t * target, int32_t flag, int value)
{
if(value == _UI_MODIFY_FLAG_TOGGLE) {
if(lv_obj_has_flag(target, flag)) lv_obj_clear_flag(target, flag);
else lv_obj_add_flag(target, flag);
}
else if(value == _UI_MODIFY_FLAG_ADD) lv_obj_add_flag(target, flag);
else lv_obj_clear_flag(target, flag);
}
void _ui_state_modify(lv_obj_t * target, int32_t state, int value)
{
if(value == _UI_MODIFY_STATE_TOGGLE) {
if(lv_obj_has_state(target, state)) lv_obj_clear_state(target, state);
else lv_obj_add_state(target, state);
}
else if(value == _UI_MODIFY_STATE_ADD) lv_obj_add_state(target, state);
else lv_obj_clear_state(target, state);
}
void _ui_textarea_move_cursor(lv_obj_t * target, int val)
{
if(val == UI_MOVE_CURSOR_UP) lv_textarea_cursor_up(target);
if(val == UI_MOVE_CURSOR_RIGHT) lv_textarea_cursor_right(target);
if(val == UI_MOVE_CURSOR_DOWN) lv_textarea_cursor_down(target);
if(val == UI_MOVE_CURSOR_LEFT) lv_textarea_cursor_left(target);
lv_obj_add_state(target, LV_STATE_FOCUSED);
}
typedef void (*screen_destroy_cb_t)(void);
void scr_unloaded_delete_cb(lv_event_t * e)
{
// Get the destroy callback from user_data
screen_destroy_cb_t destroy_cb = lv_event_get_user_data(e);
if(destroy_cb) {
destroy_cb(); // call the specific screen destroy function
}
}
void _ui_opacity_set(lv_obj_t * target, int val)
{
lv_obj_set_style_opa(target, val, 0);
}
void _ui_anim_callback_free_user_data(lv_anim_t * a)
{
lv_mem_free(a->user_data);
a->user_data = NULL;
}
void _ui_anim_callback_set_x(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_obj_set_x(usr->target, v);
}
void _ui_anim_callback_set_y(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_obj_set_y(usr->target, v);
}
void _ui_anim_callback_set_width(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_obj_set_width(usr->target, v);
}
void _ui_anim_callback_set_height(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_obj_set_height(usr->target, v);
}
void _ui_anim_callback_set_opacity(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_obj_set_style_opa(usr->target, v, 0);
}
void _ui_anim_callback_set_image_zoom(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_img_set_zoom(usr->target, v);
}
void _ui_anim_callback_set_image_angle(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
lv_img_set_angle(usr->target, v);
}
void _ui_anim_callback_set_image_frame(lv_anim_t * a, int32_t v)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
usr->val = v;
if(v < 0) v = 0;
if(v >= usr->imgset_size) v = usr->imgset_size - 1;
lv_img_set_src(usr->target, usr->imgset[v]);
}
int32_t _ui_anim_callback_get_x(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_obj_get_x_aligned(usr->target);
}
int32_t _ui_anim_callback_get_y(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_obj_get_y_aligned(usr->target);
}
int32_t _ui_anim_callback_get_width(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_obj_get_width(usr->target);
}
int32_t _ui_anim_callback_get_height(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_obj_get_height(usr->target);
}
int32_t _ui_anim_callback_get_opacity(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_obj_get_style_opa(usr->target, 0);
}
int32_t _ui_anim_callback_get_image_zoom(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_img_get_zoom(usr->target);
}
int32_t _ui_anim_callback_get_image_angle(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return lv_img_get_angle(usr->target);
}
int32_t _ui_anim_callback_get_image_frame(lv_anim_t * a)
{
ui_anim_user_data_t * usr = (ui_anim_user_data_t *)a->user_data;
return usr->val;
}
void _ui_arc_set_text_value(lv_obj_t * trg, lv_obj_t * src, const char * prefix, const char * postfix)
{
char buf[_UI_TEMPORARY_STRING_BUFFER_SIZE];
lv_snprintf(buf, sizeof(buf), "%s%d%s", prefix, (int)lv_arc_get_value(src), postfix);
lv_label_set_text(trg, buf);
}
void _ui_slider_set_text_value(lv_obj_t * trg, lv_obj_t * src, const char * prefix, const char * postfix)
{
char buf[_UI_TEMPORARY_STRING_BUFFER_SIZE];
lv_snprintf(buf, sizeof(buf), "%s%d%s", prefix, (int)lv_slider_get_value(src), postfix);
lv_label_set_text(trg, buf);
}
void _ui_checked_set_text_value(lv_obj_t * trg, lv_obj_t * src, const char * txt_on, const char * txt_off)
{
if(lv_obj_has_state(src, LV_STATE_CHECKED)) lv_label_set_text(trg, txt_on);
else lv_label_set_text(trg, txt_off);
}
void _ui_spinbox_step(lv_obj_t * target, int val)
{
if(val > 0) lv_spinbox_increment(target);
else lv_spinbox_decrement(target);
lv_event_send(target, LV_EVENT_VALUE_CHANGED, 0);
}
void _ui_switch_theme(int val)
{
#ifdef UI_THEME_ACTIVE
ui_theme_set(val);
#endif
}
-131
View File
@@ -1,131 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#ifndef _ESP32_S3_TOUCH_LCD_5B_UI_HELPERS_H
#define _ESP32_S3_TOUCH_LCD_5B_UI_HELPERS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "ui.h"
#define _UI_TEMPORARY_STRING_BUFFER_SIZE 32
#define _UI_BAR_PROPERTY_VALUE 0
#define _UI_BAR_PROPERTY_VALUE_WITH_ANIM 1
void _ui_bar_set_property(lv_obj_t * target, int id, int val);
#define _UI_BASIC_PROPERTY_POSITION_X 0
#define _UI_BASIC_PROPERTY_POSITION_Y 1
#define _UI_BASIC_PROPERTY_WIDTH 2
#define _UI_BASIC_PROPERTY_HEIGHT 3
void _ui_basic_set_property(lv_obj_t * target, int id, int val);
#define _UI_DROPDOWN_PROPERTY_SELECTED 0
void _ui_dropdown_set_property(lv_obj_t * target, int id, int val);
#define _UI_IMAGE_PROPERTY_IMAGE 0
void _ui_image_set_property(lv_obj_t * target, int id, uint8_t * val);
#define _UI_LABEL_PROPERTY_TEXT 0
void _ui_label_set_property(lv_obj_t * target, int id, const char * val);
#define _UI_ROLLER_PROPERTY_SELECTED 0
#define _UI_ROLLER_PROPERTY_SELECTED_WITH_ANIM 1
void _ui_roller_set_property(lv_obj_t * target, int id, int val);
#define _UI_SLIDER_PROPERTY_VALUE 0
#define _UI_SLIDER_PROPERTY_VALUE_WITH_ANIM 1
void _ui_slider_set_property(lv_obj_t * target, int id, int val);
void _ui_screen_change(lv_obj_t ** target, lv_scr_load_anim_t fademode, int spd, int delay, void (*target_init)(void));
void _ui_arc_increment(lv_obj_t * target, int val);
void _ui_bar_increment(lv_obj_t * target, int val, int anm);
void _ui_slider_increment(lv_obj_t * target, int val, int anm);
void _ui_keyboard_set_target(lv_obj_t * keyboard, lv_obj_t * textarea);
#define _UI_MODIFY_FLAG_ADD 0
#define _UI_MODIFY_FLAG_REMOVE 1
#define _UI_MODIFY_FLAG_TOGGLE 2
void _ui_flag_modify(lv_obj_t * target, int32_t flag, int value);
#define _UI_MODIFY_STATE_ADD 0
#define _UI_MODIFY_STATE_REMOVE 1
#define _UI_MODIFY_STATE_TOGGLE 2
void _ui_state_modify(lv_obj_t * target, int32_t state, int value);
#define UI_MOVE_CURSOR_UP 0
#define UI_MOVE_CURSOR_RIGHT 1
#define UI_MOVE_CURSOR_DOWN 2
#define UI_MOVE_CURSOR_LEFT 3
void _ui_textarea_move_cursor(lv_obj_t * target, int val)
;
void scr_unloaded_delete_cb(lv_event_t * e);
void _ui_opacity_set(lv_obj_t * target, int val);
/** Describes an animation*/
typedef struct _ui_anim_user_data_t {
lv_obj_t * target;
lv_img_dsc_t ** imgset;
int32_t imgset_size;
int32_t val;
} ui_anim_user_data_t;
void _ui_anim_callback_free_user_data(lv_anim_t * a);
void _ui_anim_callback_set_x(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_y(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_width(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_height(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_opacity(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_image_zoom(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_image_angle(lv_anim_t * a, int32_t v);
void _ui_anim_callback_set_image_frame(lv_anim_t * a, int32_t v);
int32_t _ui_anim_callback_get_x(lv_anim_t * a);
int32_t _ui_anim_callback_get_y(lv_anim_t * a);
int32_t _ui_anim_callback_get_width(lv_anim_t * a);
int32_t _ui_anim_callback_get_height(lv_anim_t * a);
int32_t _ui_anim_callback_get_opacity(lv_anim_t * a);
int32_t _ui_anim_callback_get_image_zoom(lv_anim_t * a);
int32_t _ui_anim_callback_get_image_angle(lv_anim_t * a);
int32_t _ui_anim_callback_get_image_frame(lv_anim_t * a);
void _ui_arc_set_text_value(lv_obj_t * trg, lv_obj_t * src, const char * prefix, const char * postfix);
void _ui_slider_set_text_value(lv_obj_t * trg, lv_obj_t * src, const char * prefix, const char * postfix);
void _ui_checked_set_text_value(lv_obj_t * trg, lv_obj_t * src, const char * txt_on, const char * txt_off);
void _ui_spinbox_step(lv_obj_t * target, int val)
;
void _ui_switch_theme(int val)
;
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
-209
View File
@@ -1,209 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.4.3+
// LVGL version: 8.3.11
// Project name: design
#include "ui.h"
_ui_local_style_t* _ui_local_styles;
uint32_t _ui_local_style_count = 0;
inline void ui_object_set_local_style_property
(lv_obj_t* object_p, lv_style_selector_t selector, lv_style_prop_t property, ui_style_variable_t value ) {
if ( object_p!=NULL /*&& lv_obj_is_valid(object_p)*/ ) {
lv_obj_set_local_style_prop( object_p, property, _ui_style_value_convert( property, value ), selector );
}
}
//Atomic function to set (and register) an LVGL local style-property for a given part+state (selector) of an object (widget) - can be used in many ways due to being atomic
void ui_object_set_themeable_style_property
(lv_obj_t* object_p, lv_style_selector_t selector, lv_style_prop_t property, const ui_theme_variable_t* theme_variable_p) {
static _ui_local_style_t* local_style_p;
static _ui_local_style_property_setting_t* property_setting_p;
if (object_p==NULL /*|| !lv_obj_is_valid(object_p)*/ || theme_variable_p==NULL) return;
local_style_p = _ui_local_style_create( theme_variable_p, true );
if (local_style_p == NULL) return;
property_setting_p = _ui_local_style_property_setting_create( local_style_p, object_p, selector, property );
if (property_setting_p == NULL) return;
lv_obj_set_local_style_prop( object_p, property, _ui_style_value_convert( property, ui_get_theme_value(theme_variable_p) ), selector ); //ui_object_set_local_style_property( object_p, selector, property, ui_get_theme_value(theme_variable_p) );
}
//This function goes through all registered style-property settings and if theme is changed, sets all of them to the theme. (If called periodically, it can follow change of values automatically.)
void _ui_theme_set_variable_styles (uint8_t mode) {
static uint8_t ui_theme_idx_previous = -1;
static uint32_t i, j;
static _ui_local_style_property_setting_t* property_setting_p;
static ui_style_variable_t style_value;
static ui_style_variable_t* style_variable_p;
uint8_t ui_Theme_Changed = (ui_theme_idx != ui_theme_idx_previous); ui_theme_idx_previous = ui_theme_idx;
for (i = 0; i < _ui_local_style_count; ++i) {
style_variable_p = _ui_local_styles[i].style_variable_p;
if (_ui_local_styles[i].is_themeable) style_value = ui_get_theme_value( style_variable_p );
else style_value = *style_variable_p;
if (style_variable_p != _ui_local_styles[i].previous_pointer || style_value != _ui_local_styles[i].previous_value
|| mode == UI_VARIABLE_STYLES_MODE_INIT || ui_Theme_Changed) {
_ui_local_styles[i].previous_pointer = style_variable_p; _ui_local_styles[i].previous_value = style_value;
property_setting_p = _ui_local_styles[i].style_property_settings; //first item of linked list
for (j = 0; j < _ui_local_styles[i].style_property_setting_count; ++j) {
if (property_setting_p->object_p != NULL) {
ui_object_set_local_style_property (
property_setting_p->object_p, property_setting_p->selector, property_setting_p->property, style_value
);
}
if (property_setting_p->next_p != NULL) property_setting_p = (_ui_local_style_property_setting_t*) property_setting_p->next_p; //get next item in linked-list for next round
else break; //this shouldn't happen, but if it does, it's assumed end of the list
}
}
}
}
ui_style_variable_t ui_get_theme_value(const ui_theme_variable_t* var) {
return var[ui_theme_idx];
}
lv_style_value_t _ui_style_value_convert (lv_style_prop_t property, ui_style_variable_t value) {
static lv_style_value_t Style_Value; //LVGL would produce artefacts if both .num and .color were set for the local style to add:
//static lv_style_const_prop_t ValueConvert_Table [_LV_STYLE_NUM_BUILT_IN_PROPS] = { [LV_STYLE_BG_COLOR] = LV_STYLE_CONST_BG_COLOR(1), [LV_STYLE_BG_OPA] = LV_STYLE_CONST_BG_OPA(1) };
if (property==LV_STYLE_BG_COLOR || property==LV_STYLE_BG_GRAD_COLOR || property==LV_STYLE_BG_IMG_RECOLOR || property==LV_STYLE_BORDER_COLOR
|| property==LV_STYLE_OUTLINE_COLOR || property==LV_STYLE_SHADOW_COLOR || property==LV_STYLE_IMG_RECOLOR || property==LV_STYLE_LINE_COLOR
|| property==LV_STYLE_ARC_COLOR || property==LV_STYLE_TEXT_COLOR) {
Style_Value.color = lv_color_hex(value);
}
else if (property==LV_STYLE_BG_GRAD || property==LV_STYLE_BG_IMG_SRC || property==LV_STYLE_ARC_IMG_SRC || property==LV_STYLE_TEXT_FONT
|| property==LV_STYLE_COLOR_FILTER_DSC || property==LV_STYLE_ANIM || property==LV_STYLE_TRANSITION) {
Style_Value.ptr = (void*)(uintptr_t) value;
}
else Style_Value.num = value;
return Style_Value;
}
//auto-update dynamic local style array with existing/new style-variable (1st dimension)
_ui_local_style_t* _ui_local_style_create (const ui_style_variable_t* style_variable_p, bool is_themeable) {
static uint32_t i;
static _ui_local_style_t* local_style_p;
for (i = 0; i < _ui_local_style_count; ++i) { //Find existing local style
if (_ui_local_styles[i].style_variable_p == style_variable_p) return &_ui_local_styles[i];
}
//If not found, create new local style
_ui_local_styles = (_ui_local_style_t*) lv_mem_realloc( _ui_local_styles, (_ui_local_style_count + 1) * sizeof(_ui_local_style_t) );
LV_ASSERT_MALLOC( _ui_local_styles );
if (_ui_local_styles == NULL) return NULL;
//Reset new local style
local_style_p = &_ui_local_styles[ _ui_local_style_count ];
local_style_p->style_variable_p = (ui_style_variable_t*) style_variable_p;
local_style_p->is_themeable = is_themeable;
local_style_p->previous_pointer = NULL;
local_style_p->previous_value = -1;
local_style_p->style_property_setting_count = 0;
local_style_p->style_property_settings = NULL;
/*#ifdef LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD
local_style_p->garbage_collector_couter = 0;
#endif*/
++_ui_local_style_count;
return local_style_p;
}
void _ui_local_style_property_setting_delete (lv_event_t* event) { * (lv_obj_t**) lv_event_get_user_data( event ) = NULL; }
//auto-update dynamic local style-array's 2nd dimension (object part+state style-property settings for a given style-variable)
_ui_local_style_property_setting_t* _ui_local_style_property_setting_create
(_ui_local_style_t* local_style_p, lv_obj_t* object_p, lv_style_selector_t selector, lv_style_prop_t property) {
static uint32_t i; //auto-update
static _ui_local_style_property_setting_t *style_property_setting_p, *empty_style_property_setting_p;
/*#ifdef LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD
style_property_setting_p = local_style_p->style_property_settings; //first item of linked list
if (style_property_setting_p != NULL) { //checking might be unnecessary if count is properly initialized to 0
if (local_style_p->garbage_collector_couter > 0) --local_style_p->garbage_collector_couter; //avoid calling garbage collector every time
else if (LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD > 0) {
local_style_p->garbage_collector_couter = LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD - 1;
for (i = 0; i < local_style_p->style_property_setting_count; ++i) {
if (style_property_setting_p->object_p != NULL) { //check only valid object entry (skip already emptied positions{
#if ( defined(LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE) && LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE ) //Not recommended inside explicit garbage collector.
if ( style_property_setting_p->validcheck_counter > 0 ) --style_property_setting_p->validcheck_counter; //avoids calling complex lv_obj_is_valid() many times
else { //check objects with expired positive vaidity check
if ( lv_obj_is_valid( style_property_setting_p->object_p ) ) style_property_setting_p->validcheck_counter = LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE;
else style_property_setting_p->object_p = NULL; //free up an entry of a deleted widget
}
#else //this is the recommended variant inside explicit garbage collector:
if ( !lv_obj_is_valid( style_property_setting_p->object_p ) ) style_property_setting_p->object_p = NULL; //free up an entry of a deleted widget
#endif
}
if (style_property_setting_p->next_p != NULL) style_property_setting_p = (_ui_local_style_property_setting_t*) style_property_setting_p->next_p; //get next item in linked-list for next round
else break; //this shouldn't happen
}
}
}
#endif*/
style_property_setting_p = local_style_p->style_property_settings; //first item of linked list
empty_style_property_setting_p = NULL;
if (style_property_setting_p != NULL) { //checking might be unnecessary if count is properly initialized to 0
for (i = 0; i < local_style_p->style_property_setting_count; ++i) {
if (empty_style_property_setting_p == NULL) { //search and register one empty position that might be needed for a newly created entry
if (style_property_setting_p->object_p == NULL) empty_style_property_setting_p = style_property_setting_p; //if found empty position, register it
/*#ifdef LV_SQUARELINE_THEME__IMPLICIT_GARBAGE_COLLECTOR
else { //if not, check for possible empty positions of deleted objects (garbage-collection)
#if ( defined(LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE) && LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE ) //for slow hardware, adding this and setting to 5..10 in lv_conf.h might make it faster
if ( style_property_setting_p->validcheck_counter > 0 ) --style_property_setting_p->validcheck_counter; //avoids calling complex lv_obj_is_valid() many times
else { //check objects with expired positive vaidity check
if ( lv_obj_is_valid( style_property_setting_p->object_p ) ) style_property_setting_p->validcheck_counter = LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE;
else { //free up an entry of a deleted widget
style_property_setting_p->object_p = NULL;
empty_style_property_setting_p = style_property_setting_p;
}
}
#else
if ( !lv_obj_is_valid( style_property_setting_p->object_p ) ) { //free up an entry of a deleted widget
style_property_setting_p->object_p = NULL;
empty_style_property_setting_p = style_property_setting_p;
}
#endif
}
#endif*/
}
if (style_property_setting_p->object_p == object_p && style_property_setting_p->selector == selector
&& style_property_setting_p->property == property) { //setting found in the list (created already), so returning it
return style_property_setting_p;
}
if (style_property_setting_p->next_p != NULL) style_property_setting_p = (_ui_local_style_property_setting_t*) style_property_setting_p->next_p; //get next item in linked-list for next round
else break; //this shouldn't happen, but if it does, create a new element
}
}
//If not found, create new local style-property (can be inside the array at freed-up places of deleted objects too)
if (empty_style_property_setting_p == NULL) { //allocate new
empty_style_property_setting_p = (_ui_local_style_property_setting_t*) lv_mem_alloc( sizeof(_ui_local_style_property_setting_t) );
LV_ASSERT_MALLOC( empty_style_property_setting_p );
if (empty_style_property_setting_p == NULL) return NULL;
if (style_property_setting_p != NULL) style_property_setting_p->next_p = (void*) empty_style_property_setting_p; //create link from last item to the new
else local_style_p->style_property_settings = empty_style_property_setting_p; //(except if creating first item)
style_property_setting_p = empty_style_property_setting_p; //take the new item pointer for initialization
style_property_setting_p->next_p = NULL; //signify the end of the linked list, just in case
++local_style_p->style_property_setting_count;
}
else { //reuse empty
style_property_setting_p = empty_style_property_setting_p;
}
style_property_setting_p->object_p = object_p; lv_obj_add_event_cb( object_p, _ui_local_style_property_setting_delete, LV_EVENT_DELETE, &style_property_setting_p->object_p );
style_property_setting_p->selector = selector;
style_property_setting_p->property = property;
/*#ifdef LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE
style_property_setting_p->validcheck_counter = LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE; //0
#endif*/
return style_property_setting_p;
}
-75
View File
@@ -1,75 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.4.3+
#ifndef _UI_THEME_MANAGER_H
#define _UI_THEME_MANAGER_H
#ifdef __cplusplus
extern "C" {
#endif
#define UI_THEME_ACTIVE 1
/*#ifndef LV_SQUARELINE_THEME__IMPLICIT_GARBAGE_COLLECTOR
#ifndef LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD //for slow hardware, tells how frequently the style-properties inside this style should be garbage-collected (recommended value: 10..100, 0:never)
#define LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD 100 //a sensible default value that already gives good results on slow hardware, can be overridden from outside
#endif
#endif*/
enum { UI_VARIABLE_STYLES_MODE_INIT = 1, UI_VARIABLE_STYLES_MODE_FOLLOW = 0 };
typedef int64_t ui_style_variable_t;
typedef ui_style_variable_t ui_theme_variable_t; //A 'theme' variable array is an array of 'style' variables for corresponding themes.
typedef struct {
lv_obj_t * object_p;
lv_style_selector_t selector;
lv_style_prop_t property;
/*#ifdef LV_SQUARELINE_THEME__OBJECT_VALIDITY_CACHE //for slow hardware, adding this and setting to 5..10 in lv_conf.h might make it faster (less lv_obj_is_valid calls)
uint16_t validcheck_counter; //used for garbage collection (finding empty slots) not to call lv_obj_is_valid() every time
#endif*/
void * next_p;
} _ui_local_style_property_setting_t;
typedef struct {
bool is_themeable; //scalar or vector?
ui_style_variable_t * style_variable_p;
ui_style_variable_t * previous_pointer;
ui_style_variable_t previous_value;
uint32_t style_property_setting_count;
_ui_local_style_property_setting_t * style_property_settings;
/*#ifdef LV_SQUARELINE_THEME__EXPLICIT_GARBAGE_COLLECTOR_PERIOD
uint16_t garbage_collector_couter;
#endif*/
} _ui_local_style_t;
extern _ui_local_style_t * _ui_local_styles;
extern uint32_t _ui_local_style_count;
void ui_object_set_local_style_property
(lv_obj_t* object_p, lv_style_selector_t selector, lv_style_prop_t property, ui_style_variable_t value );
void ui_object_set_themeable_style_property
(lv_obj_t* object_p, lv_style_selector_t selector, lv_style_prop_t property, const ui_theme_variable_t* theme_variable_p);
void _ui_theme_set_variable_styles (uint8_t mode);
lv_style_value_t _ui_style_value_convert (lv_style_prop_t property, ui_style_variable_t value);
ui_style_variable_t ui_get_theme_value (const ui_theme_variable_t *var);
_ui_local_style_t * _ui_local_style_create (const ui_style_variable_t * style_variable_p, bool is_themeable);
_ui_local_style_property_setting_t * _ui_local_style_property_setting_create
(_ui_local_style_t * local_style, lv_obj_t * object_p, lv_style_selector_t selector, lv_style_prop_t property);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
-17
View File
@@ -1,17 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#include "ui.h"
const ui_theme_variable_t _ui_theme_color_panel_backgroung[1] = {0x7F7A9C};
const ui_theme_variable_t _ui_theme_alpha_panel_backgroung[1] = {255};
uint8_t ui_theme_idx = UI_THEME_DEFAULT;
void ui_theme_set(uint8_t theme_idx)
{
ui_theme_idx = theme_idx;
_ui_theme_set_variable_styles(UI_VARIABLE_STYLES_MODE_FOLLOW);
}
-30
View File
@@ -1,30 +0,0 @@
// This file was generated by SquareLine Studio
// SquareLine Studio version: SquareLine Studio 1.5.4
// LVGL version: 8.3.6
// Project name: ESP32-S3-Touch-LCD-5B
#ifndef _UI_THEMES_H
#define _UI_THEMES_H
#ifdef __cplusplus
extern "C" {
#endif
#define UI_THEME_COLOR_PANEL_BACKGROUNG 0
#define UI_THEME_DEFAULT 0
extern const ui_theme_variable_t _ui_theme_color_panel_backgroung[1];
extern const ui_theme_variable_t _ui_theme_alpha_panel_backgroung[1];
extern const uint32_t * ui_theme_colors[1];
extern const uint8_t * ui_theme_alphas[1];
extern uint8_t ui_theme_idx;
void ui_theme_set(uint8_t theme_idx);
#ifdef __cplusplus
} /*extern "C"*/
#endif
#endif
+9 -3
View File
@@ -1,7 +1,13 @@
# ESP32-S3-WROOM-1-N16R8 Partition Table (16MB Flash)
# ESP32-S3-WROOM-1-N16R8 Partition Table (16MB Flash) - dual-slot OTA
# Name, Type, SubType, Offset, Size, Flags
#
# nvs + otadata keep their original offsets so saved settings/tunables survive
# the change. Two equal app slots for OTA (src/modules/ota_update.cpp): the
# running image writes the new one into the idle slot and flips otadata.
# SPIFFS was dropped (nothing used it) to give each slot ~7.9 MB; firmware is
# ~1.5 MB. Changing this table needs one USB flash; OTA works after that.
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0xC80000,
spiffs, data, spiffs, 0xC90000, 0x360000,
app0, app, ota_0, 0x10000, 0x7F0000,
app1, app, ota_1, 0x800000, 0x7F0000,
coredump, data, coredump,0xFF0000, 0x10000,
1 # ESP32-S3-WROOM-1-N16R8 Partition Table (16MB Flash) # ESP32-S3-WROOM-1-N16R8 Partition Table (16MB Flash) - dual-slot OTA
2 # Name, Type, SubType, Offset, Size, Flags # Name, Type, SubType, Offset, Size, Flags
3 #
4 # nvs + otadata keep their original offsets so saved settings/tunables survive
5 # the change. Two equal app slots for OTA (src/modules/ota_update.cpp): the
6 # running image writes the new one into the idle slot and flips otadata.
7 # SPIFFS was dropped (nothing used it) to give each slot ~7.9 MB; firmware is
8 # ~1.5 MB. Changing this table needs one USB flash; OTA works after that.
9 nvs, data, nvs, 0x9000, 0x5000, nvs, data, nvs, 0x9000, 0x5000,
10 otadata, data, ota, 0xe000, 0x2000, otadata, data, ota, 0xe000, 0x2000,
11 app0, app, ota_0, 0x10000, 0xC80000, app0, app, ota_0, 0x10000, 0x7F0000,
12 spiffs, data, spiffs, 0xC90000, 0x360000, app1, app, ota_1, 0x800000, 0x7F0000,
13 coredump, data, coredump,0xFF0000, 0x10000, coredump, data, coredump,0xFF0000, 0x10000,
+42 -6
View File
@@ -49,8 +49,43 @@ lib_deps =
; ----------------------------------------------------------------------------
; Build Flags & Source Directories
; ----------------------------------------------------------------------------
; Include UI, display, and modules directories as source directories
build_src_filter = +<*> +<modules/*> +<../include/ui/*> +<../include/display/*>
; Also compile the LVGL port that lives under include/display
build_src_filter = +<*> +<modules/*> +<../include/display/*>
; ---- Display experiment (branch display-xip, wiki open-questions #13 step 3) ----
; Rebuilds the Arduino core with these sdkconfig changes (pioarduino custom_sdkconfig):
; - XIP_FROM_PSRAM: code + rodata execute from PSRAM, so flash writes (NVS, OTA)
; no longer stall everything that touches PSRAM (the LCD framebuffer refill).
; - LCD_RGB_ISR_IRAM_SAFE: the bounce-buffer refill interrupt keeps running while
; the flash cache is disabled.
; Components not used by this firmware, dropped from the core rebuild. RainMaker /
; Insights also try to embed a https_server.crt that only exists in their own
; projects, which broke the first custom_sdkconfig build (2026-09-27).
custom_component_remove =
espressif/esp_rainmaker
espressif/rmaker_common
espressif/esp_insights
espressif/esp_diag_data_store
espressif/esp_diagnostics
espressif/cbor
espressif/qrcode
espressif/network_provisioning
espressif/esp-zboss-lib
espressif/esp-zigbee-lib
espressif/esp_hosted
espressif/esp_wifi_remote
espressif/esp-sr
espressif/esp-dsp
espressif/esp-modbus
espressif/libsodium
chmorgan/esp-libhelix-mp3
espressif/esp32-camera
custom_sdkconfig =
CONFIG_SPIRAM_XIP_FROM_PSRAM=y
CONFIG_SPIRAM_FETCH_INSTRUCTIONS=y
CONFIG_SPIRAM_RODATA=y
CONFIG_LCD_RGB_ISR_IRAM_SAFE=y
build_flags =
; C++ standard (required for ESP32_Display_Panel)
@@ -79,9 +114,11 @@ build_flags =
; RGB LCD Framebuffer Configuration for large displays
; Force RGB LCD to use PSRAM for framebuffers (1024x600 requires ~2.4MB)
-DESP_PANEL_LCD_RGB_BUFFER_NUMS=2
-DESP_PANEL_LCD_RGB_BOUNCE_BUF_SIZE=0
-DESP_PANEL_LCD_RGB_REFRESH_MODE=0
; NOTE: the RGB panel settings (21 MHz pixel clock, 10-line bounce buffers,
; porches, pins) come from ESP32_Display_Panel's board header
; BOARD_WAVESHARE_ESP32_S3_TOUCH_LCD_5_B.h (ESP_PANEL_BOARD_LCD_RGB_*).
; The old -DESP_PANEL_LCD_RGB_{BUFFER_NUMS,BOUNCE_BUF_SIZE,REFRESH_MODE}
; flags here were never read by the v1.x library and were removed 2026-09-27.
; FreeRTOS configuration
-DARDUINO_RUNNING_CORE=1 ; LVGL runs on Core 1
@@ -91,7 +128,6 @@ build_flags =
-I include/config
-I include/display
-I include/protocol
-I include/ui
-I src
; ----------------------------------------------------------------------------
+22076
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+56 -13
View File
@@ -11,6 +11,7 @@
#include "modules/serial_lock.h"
#include "modules/tunables.h"
#include "modules/diag_probe.h"
#include "modules/bench_sim.h"
#include "esp_log.h"
// Import shared data from UARTManager namespace
@@ -32,6 +33,11 @@ namespace CANDriver {
// Without this window the flag would strobe on every gear change.
#define GEAR_MISMATCH_DEBOUNCE_MS 500
// 0x3B4 is a 5 s frame. While one has been seen this recently its ignition
// nibble rules; otherwise ignition follows the 0x1D2 lever byte (Patrol 2's bus
// has no 0x3B4 at all; captures 2026-10-18, wiki can-capture-2026-10-18-patrol-2).
#define IGN_3B4_HOLD_MS 10000
// ============================================================================
// MODULE STATE
// ============================================================================
@@ -42,6 +48,7 @@ static QueueHandle_t g_can_event_queue = NULL;
static can_stats_t g_can_stats = {0};
static bool g_uart_auto_stopped = false; // Track if UART was auto-stopped due to CAN timeout
// Raw frame logging: capture EVERY frame (candump-style) for offline CAN ID
// discovery. Default ON since discovery is the current priority.
static bool g_raw_logging = true;
@@ -53,6 +60,22 @@ static bool g_verbose_decode = false;
// Guarded by g_data_mutex along with g_automotive_data.
static driveline_t g_driveline = {0};
/**
* Forget every CAN-derived value: nothing may be shown or sent that the bus
* did not say recently. Called when CAN stops and when the bus goes silent.
*/
static void clearSharedData() {
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
uint8_t dbg = UARTManager::g_automotive_data.debug_enabled;
memset(&UARTManager::g_automotive_data, 0, sizeof(UARTManager::g_automotive_data));
UARTManager::g_automotive_data.gear_lever = LEVER_UNKNOWN;
UARTManager::g_automotive_data.debug_enabled = dbg;
xSemaphoreGive(UARTManager::g_data_mutex);
}
memset(&g_driveline, 0, sizeof(g_driveline));
g_driveline.lever = GEAR_UNKNOWN;
}
// Last gear LEVER code seen on 0x1D2, for the lever-vs-gearbox cross-check.
static gear_position_t g_last_lever = GEAR_UNKNOWN;
// When the current disagreement started (0 = currently in agreement).
@@ -60,11 +83,28 @@ static uint32_t g_mismatch_since = 0;
// Gearbox target gear number from 0x0BA (1..6 forward, 0 = P/R/N/none), for the
// wire's target nibble. Lives here because 0x0BA and 0x1D2 arrive separately.
static uint8_t g_target_gear_num = 0;
// millis() of the last 0x3B4 frame (0 = none since CAN started) - see IGN_3B4_HOLD_MS.
static uint32_t g_last_3b4_ms = 0;
// ============================================================================
// PRIVATE FUNCTIONS
// ============================================================================
/**
* @brief Set the ignition flag and remember which frame decided it; one console
* line per change so a capture shows when and why the screens blanked.
* Caller must hold g_data_mutex.
*/
static void setIgnition(bool on, uint8_t src) {
if (g_driveline.ignition_on == on && g_driveline.ignition_src == src) return;
g_driveline.ignition_on = on;
g_driveline.ignition_src = src;
SerialLock::lock();
ESP_LOGI("CANDrv", "ignition %s (from %s)", on ? "ON" : "OFF",
src == IGN_SRC_3B4 ? "0x3B4" : "0x1D2 lever - no 0x3B4 on this bus");
SerialLock::unlock();
}
/**
* @brief Cross-check the driver's lever selection against the gearbox's own
* target gear and raise a fault if they disagree for long enough.
@@ -226,6 +266,12 @@ static bool parseCANMessage(const twai_message_t& message) {
if (dlc > CAN_BYTE_GEAR_LEVER) {
g_last_lever = can_to_gear_lever(data[CAN_BYTE_GEAR_LEVER]);
g_driveline.lever = (uint8_t)g_last_lever;
// Ignition fallback: the EGS reports a lever position only with
// terminal 15 on; with the key off the byte reads 0xF0 within one
// frame while the bus stays awake for another 5-10 s (verified on
// Patrol 2's captures). 0x3B4, when present, keeps precedence.
bool have_3b4 = (g_last_3b4_ms != 0) && (millis() - g_last_3b4_ms < IGN_3B4_HOLD_MS);
if (!have_3b4) setIgnition(g_last_lever != GEAR_UNKNOWN, IGN_SRC_LEVER);
}
if (dlc > CAN_BYTE_GEAR_ENGAGED) {
g_driveline.engaged_gear = can_to_engaged_gear(data[CAN_BYTE_GEAR_ENGAGED]);
@@ -304,9 +350,9 @@ static bool parseCANMessage(const twai_message_t& message) {
}
if (dlc > CAN_BYTE_IGNITION) {
// Byte 2's low nibble tracks ignition (inverted), NOT engine run
// — verified on this bus against both published claims.
g_driveline.ignition_on =
((data[CAN_BYTE_IGNITION] & 0x0F) == IGNITION_ON);
// — verified on Patrol 1's bus against both published claims.
g_last_3b4_ms = millis();
setIgnition((data[CAN_BYTE_IGNITION] & 0x0F) == IGNITION_ON, IGN_SRC_3B4);
parsed = true;
}
break;
@@ -507,6 +553,7 @@ static void canTask(void* parameter) {
g_last_lever = GEAR_UNKNOWN;
g_target_gear_num = 0;
g_mismatch_since = 0;
g_last_3b4_ms = 0;
ESP_LOGI("CANTask", "CAN reception active");
// Auto-start UART transmission (CAN drives UART)
@@ -523,6 +570,7 @@ static void canTask(void* parameter) {
deinitTWAI();
g_can_active = false;
g_uart_auto_stopped = false; // Reset auto-stop flag
clearSharedData();
// Auto-stop UART transmission (CAN drives UART)
UARTManager::linkToCANState(false);
@@ -595,6 +643,7 @@ static void canTask(void* parameter) {
// CAN data is stale - auto-stop UART to prevent transmitting stale data
ESP_LOGW("CANTask", "⚠ CAN timeout (%dms since last message), auto-stopping UART", time_since_last_rx);
UARTManager::linkToCANState(false);
clearSharedData(); // stale values must not come back as "valid" later
g_uart_auto_stopped = true;
}
}
@@ -673,6 +722,7 @@ driveline_t getDriveline() {
memset(&snapshot, 0, sizeof(snapshot));
snapshot.lever = (uint8_t)GEAR_UNKNOWN; // 0 would mean GEAR_PARK
}
BenchSim::apply(snapshot); // `sim` console: bench torque / rpm / shaft, off unless asked
return snapshot;
}
@@ -680,7 +730,7 @@ bool isActive() {
return g_can_active;
}
bool transmit(uint32_t id, const uint8_t* data, uint8_t len) {
bool transmit(uint32_t id, const uint8_t* data, uint8_t len, bool echo) {
if (!g_can_active || data == NULL || len > 8 || id > 0x7FF) {
g_can_stats.tx_failures++;
return false;
@@ -700,7 +750,7 @@ bool transmit(uint32_t id, const uint8_t* data, uint8_t len) {
return false;
}
g_can_stats.messages_transmitted++;
emitFrameLine("CANTX", m);
if (echo) emitFrameLine("CANTX", m);
return true;
}
@@ -718,14 +768,7 @@ void setVerboseDecode(bool enabled) {
ESP_LOGI("CANDrv", "Verbose decode logging %s", enabled ? "ENABLED" : "disabled");
}
void onCANToggle(lv_event_t *e) {
lv_obj_t *target = lv_event_get_target(e);
if (target == NULL) {
ESP_LOGE("CANDrv", "ERROR: CAN toggle target is NULL!");
return;
}
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
void setEnabled(bool state) {
ESP_LOGI("CANDrv", "===== CAN Toggle Event =====");
ESP_LOGI("CANDrv", "CAN Toggle State: %s", state ? "ON" : "OFF");
+69 -96
View File
@@ -1,5 +1,6 @@
#include <Arduino.h>
#include <lvgl.h>
#include <esp_heap_caps.h>
#include "display/lvgl_v8_port.h" // LVGL port layer (for lvgl_port_lock/unlock)
#include "modules/display_init.h" // Display initialization module
#include "modules/wifi_manager.h" // WiFi manager module
@@ -9,109 +10,69 @@
#include "modules/ui_state_manager.h" // UI state manager module
#include "modules/driveline_screen.h" // Hand-coded driveline screen (boot screen)
#include "modules/tuning_screen.h" // Hand-coded gauge tuning screen (swipe right from Driveline)
#include "modules/settings_screen.h" // Hand-coded settings screen (swipe left from Driveline)
#include "modules/engine_screen.h" // Live DDE values (Engine data button on Driveline)
#include "modules/sport_screen.h" // Torque + power gauges (Sport button on Driveline)
#include "modules/vehicle.h" // Final drive ratio + tyre circumference -> road speed; power maths (`vehicle` console)
#include "modules/bench_sim.h" // `sim` console: bench torque / rpm / shaft for the screens, never saved
#include "modules/ecu_ident.h" // which DDE this board is on: read once, stored, UNKNOWN ECU until then (`ecu` console)
#include "modules/serial_lock.h" // Global serial write mutex
#include "modules/tunables.h" // Gauge calibration + alert thresholds (NVS, serial console)
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Controller B
#include "modules/perf_monitor.h" // `perf` console: render fps, flush cost, CPU idle, heap
#include "modules/espnow_link.h" // ESP-NOW transmit leg of the link to Inst. Cluster
#include "modules/diag_probe.h" // On-demand OBD-II requests (`diag` console) - the only CAN transmitter
#include "modules/ota_update.h" // Manual firmware updates from Gitea releases (`ota` console)
#include "modules/link_peer.h" // Inst. Cluster status, pairing, credential handoff, B updates (`link` console)
#include "modules/status_overlay.h" // Every screen: Wi-Fi chip top-right, blinking alert banner top-centre
#include "modules/diff_locks.h" // Diff-lock inputs DI0 rear / DI1 front via the CH422G (`difflock` console)
#include "modules/reverse_light.h" // Reverse-light relay on DO0, follows the lever in R (`reverse` console)
// ============================================================================
// MINIMAL LVGL + UI SETTINGS + WIFI + UART
// ============================================================================
// This is a minimal setup with:
// - LVGL display and touch initialization
// - Hand-coded Driveline (boot) + Gauge Tuning screens, SquareLine Settings screen
// - WiFi module with async scanning (managed by WiFiManager)
// - Hand-coded Driveline (boot), Settings and Gauge Tuning screens
// - WiFi: one remembered network, scans on request (WiFiManager)
// - UART data transmission at 5Hz (managed by UARTManager)
// - UI state synchronization (managed by UIStateManager)
// - Persistent settings storage (managed by SettingsManager)
// ============================================================================
// External UI element references (from ui_Settings_Screen.c)
extern "C" {
extern lv_obj_t *uic_Main_Container;
extern lv_obj_t *uic_Toggle_Wifi_Switch;
extern lv_obj_t *uic_Toggle_UART_Switch;
extern lv_obj_t *uic_Toggle_CAN_Bus_Switch;
}
// ============================================================================
// EVENT HANDLERS (C linkage for SquareLine Studio UI callbacks)
// ============================================================================
extern "C" {
// WiFi-related event handlers (delegated to WiFiManager)
void onSelectSSID(lv_event_t *e) {
WiFiManager::onSelectSSID(e);
}
// WiFi toggle event handler - delegates to WiFiManager module
void onWifiToggle(lv_event_t *e)
{
// Get the actual widget from the event (safer than global variable)
lv_obj_t *target = lv_event_get_target(e);
// Verify the widget is valid
if (target == NULL) {
Serial.println("ERROR: WiFi toggle target is NULL!");
Serial.flush();
return;
// `mem`: internal heap, PSRAM, and LVGL's own pool (LV_MEM_SIZE, where every
// widget lives). Takes the LVGL lock with a timeout so a hung UI is reported
// rather than hanging the console too.
static bool memCommand(const char* line) {
if (strcmp(line, "mem") != 0) return false;
SerialLock::lock();
Serial.printf("[mem] internal free %u (largest block %u), PSRAM free %u\n",
(unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
(unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
(unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
SerialLock::unlock();
if (!lvgl_port_lock(500)) {
Serial.println("[mem] LVGL lock busy > 500 ms - UI task stuck?");
return true;
}
// Check the toggle state
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
Serial.printf("WiFi Toggle RELEASED - State: %s\n", state ? "ON" : "OFF");
Serial.flush();
// Save state to NVS for persistence across power cycles
SettingsManager::saveWiFiState(state);
// Delegate to WiFiManager module
WiFiManager::onWifiToggle(e);
lv_mem_monitor_t m;
lv_mem_monitor(&m);
lvgl_port_unlock();
SerialLock::lock();
Serial.printf("[mem] LVGL pool: used %u of %u B (%u%%), frag %u%%, biggest free %u\n",
(unsigned)(m.total_size - m.free_size), (unsigned)m.total_size,
(unsigned)m.used_pct, (unsigned)m.frag_pct, (unsigned)m.free_biggest_size);
SerialLock::unlock();
return true;
}
// UART toggle event handler - delegates to UARTManager module
void onUARTToggle(lv_event_t *e)
{
// Get the actual widget from the event (safer than global variable)
lv_obj_t *target = lv_event_get_target(e);
// Verify the widget is valid
if (target == NULL) {
Serial.println("ERROR: UART toggle target is NULL!");
Serial.flush();
return;
}
// Check the toggle state
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
Serial.printf("UART Toggle RELEASED - State: %s\n", state ? "ON" : "OFF");
Serial.flush();
// Save state to NVS for persistence across power cycles
SettingsManager::saveUARTState(state);
// Delegate to UARTManager module
UARTManager::onUARTToggle(e);
// Console lines `cfg` doesn't recognise: diagnostic probe, OTA, Wi-Fi, mem, link, difflock.
static bool consoleExtraCommand(const char* line) {
return DiagProbe::handleCommand(line) || Ota::handleCommand(line) ||
WiFiManager::handleCommand(line) || memCommand(line) ||
PerfMon::handleCommand(line) || LinkPeer::handleCommand(line) ||
DiffLocks::handleCommand(line) || ReverseLight::handleCommand(line) || Vehicle::handleCommand(line) ||
BenchSim::handleCommand(line) || EcuIdent::handleCommand(line);
}
// CAN Bus toggle event handler - delegates to CANDriver module
void onCANBusToggle(lv_event_t *e)
{
CANDriver::onCANToggle(e);
}
// Debug toggle event handler - delegates to UIStateManager module
void onDebugToggle(lv_event_t *e)
{
UIStateManager::onDebugToggle(e);
}
} // extern "C"
// ============================================================================
// SETUP - Initialize hardware and UI
// ============================================================================
@@ -131,20 +92,25 @@ void setup()
// Use ESP_LOG instead of Serial.println to match library output
ESP_LOGI("MAIN", "=== ESP32-S3-LCD-5B Minimal Setup ===");
ESP_LOGI("MAIN", "Firmware compiled: %s %s", __DATE__, __TIME__);
Ota::init(); // version + slot; flags an unconfirmed freshly-installed image
// Initialize display hardware and UI
ESP_LOGI("MAIN", "Initializing display and UI...");
DisplayInit::init();
ESP_LOGI("MAIN", "Display init COMPLETED!");
StatusOverlay::init(); // Wi-Fi chip + alert banner on lv_layer_top(), above every screen
// Initialize Settings Manager
ESP_LOGI("MAIN", "Initializing Settings Manager...");
SettingsManager::init();
Vehicle::init(); // final drive ratio + tyre circumference (road speed)
// Tunables (gauge calibration, alert thresholds) - before CAN/UART start
Tunables::init();
DiagProbe::init();
Tunables::setExtraCommandHandler(DiagProbe::handleCommand);
EcuIdent::init(); // stored DDE identification; hooks DiagProbe for the one-shot read
Tunables::setExtraCommandHandler(consoleExtraCommand);
PerfMon::init();
// Load saved switch states from NVS
ESP_LOGI("MAIN", "Loading saved switch states from NVS...");
@@ -152,6 +118,8 @@ void setup()
bool saved_uart_state = SettingsManager::loadUARTState();
bool saved_can_state = SettingsManager::loadCANState();
bool saved_debug_state = SettingsManager::loadDebugState();
DiffLocks::init(SettingsManager::loadDiffLockState(), SettingsManager::loadDiffLockInvert()); // CH422G bus is up since DisplayInit
ReverseLight::init(SettingsManager::loadReverseLightState(), DisplayInit::expander()); // DO0 off until the lever says R
ESP_LOGI("MAIN", "Saved states loaded (UI will be updated when Settings screen opens)");
// Initialize UI State Manager
@@ -165,6 +133,7 @@ void setup()
// ESP-NOW transmit leg (needs the radio in STA mode, which WiFiManager keeps)
ESP_LOGI("MAIN", "Initializing ESP-NOW link...");
EspNowLink::init();
LinkPeer::init(); // B's STATUS frames, pairing key, credential handoff
// Initialize UART subsystem using UARTManager module
ESP_LOGI("MAIN", "Initializing UART subsystem...");
@@ -186,8 +155,7 @@ void setup()
ESP_LOGI("MAIN", "- Link: UART1 TX GPIO44 (RS485 A/B) + ESP-NOW broadcast, protocol v%u", PACKET_VERSION);
ESP_LOGI("MAIN", "- Console: type 'cfg help' to tune the Patrol gauge outputs");
ESP_LOGI("MAIN", "- Screens: Driveline (boot) <- left: Settings | right: Gauge tuning ->");
ESP_LOGI("MAIN", "- Settings screen has WiFi and UART toggles");
ESP_LOGI("MAIN", "- WiFi scan updates every 10 seconds when enabled");
ESP_LOGI("MAIN", "- Settings: Wi-Fi (remembered network), Updates, System, Vehicle");
ESP_LOGI("MAIN", "- UART transmits at 5Hz (200ms) when enabled");
}
@@ -203,19 +171,24 @@ void loop()
last_print = millis();
}
// LVGL task runs automatically in separate task
// Keep loop() minimal and empty to avoid interfering with LVGL rendering
// Continuously sync UI switches with actual service states
// (Settings screen gets destroyed/recreated when swiping)
UIStateManager::applySavedStatesToUI();
// Serial console: gauge tunables (cfg ...) and the diagnostic probe (diag ...)
// LVGL renders in its own task; the screen ticks below only refresh values.
// Serial console: gauge tunables (cfg ...), diagnostic probe (diag ...), updates (ota ...)
Tunables::pollSerial();
PerfMon::tick();
DiagProbe::tick();
Ota::tick(); // confirms a freshly installed image after healthy uptime
LinkPeer::tick(); // Inst. Cluster heard/lost, credential sync
DiffLocks::tick(); // DI0/DI1 at 4 Hz, only when the Settings switch is on
ReverseLight::tick(); // DO0 follows the lever in R (10 Hz decision, 200 ms confirm)
Vehicle::tick(); // deferred NVS write of the Vehicle settings
EcuIdent::tick(); // one-shot DDE identification read while nothing is stored
DrivelineScreen::tick();
TuningScreen::tick();
SettingsScreen::tick();
StatusOverlay::tick();
EngineScreen::tick();
SportScreen::tick();
delay(100); // Check frequently to catch screen changes quickly
}
+96
View File
@@ -0,0 +1,96 @@
/*
* Bench Simulation Module Implementation - see bench_sim.h
*/
#include "bench_sim.h"
#include "serial_lock.h"
#include "vehicle.h"
namespace BenchSim {
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
static volatile bool g_active = false;
static volatile int16_t g_torque_x10 = 0;
static volatile uint16_t g_rpm = 0;
static volatile uint16_t g_shaft_raw = 0;
static void print(const char* fmt, ...) {
char buf[200];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static void status() {
if (!g_active) { print("[sim] off - screens show the CAN bus"); return; }
uint16_t shaft_rpm = can_output_shaft_rpm(g_shaft_raw);
uint16_t hp = Vehicle::powerHpX10(g_torque_x10, g_rpm);
uint16_t kmh = Vehicle::speedKmhX10(g_shaft_raw);
print("[sim] ON: torque %d.%d Nm, engine %u rpm -> %u.%u hp; output shaft %u rpm (raw %u) -> %u.%u km/h (not saved)",
g_torque_x10 / 10, abs(g_torque_x10 % 10), g_rpm, hp / 10, hp % 10,
shaft_rpm, g_shaft_raw, kmh / 10, kmh % 10);
}
static void help() {
print("sim torque <Nm> [rpm <n>] [shaft <rpm>] bench values for the Sport / Driveline screens");
print("sim rpm <n> engine speed (power = torque x rpm)");
print("sim shaft <rpm> output shaft speed (road speed on screen)");
print("sim status");
print("sim off back to the CAN bus (also at every boot)");
}
// ============================================================================
// PUBLIC API
// ============================================================================
bool isActive() { return g_active; }
void apply(driveline_t& dl) {
if (!g_active) return;
dl.engine_torque_x10 = g_torque_x10;
dl.engine_rpm = g_rpm;
dl.output_shaft_raw = g_shaft_raw;
dl.ignition_on = true;
dl.engine_run_state = ENGINE_RUN_RUNNING;
}
bool handleCommand(const char* line) {
if (strncmp(line, "sim", 3) != 0 || (line[3] != 0 && line[3] != ' ')) return false;
char buf[96];
snprintf(buf, sizeof(buf), "%s", line);
char* argv[8];
int argc = 0;
for (char* t = strtok(buf, " \t"); t && argc < 8; t = strtok(NULL, " \t")) argv[argc++] = t;
if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; }
if (!strcmp(argv[1], "status")) { status(); return true; }
if (!strcmp(argv[1], "off")) {
g_active = false;
g_torque_x10 = 0; g_rpm = 0; g_shaft_raw = 0;
print("[sim] off");
return true;
}
// any number of "<name> <value>" pairs
bool ok = argc >= 3 && (argc % 2) == 1;
for (int i = 1; ok && i + 1 < argc; i += 2) {
long v = strtol(argv[i + 1], NULL, 0);
if (!strcmp(argv[i], "torque")) g_torque_x10 = (int16_t)constrain(v, -3000, 3000) * 10;
else if (!strcmp(argv[i], "rpm")) g_rpm = (uint16_t)constrain(v, 0, 10000);
else if (!strcmp(argv[i], "shaft")) g_shaft_raw = (uint16_t)constrain((v * OUTPUT_SHAFT_RPM_DEN) / OUTPUT_SHAFT_RPM_NUM, 0, 65535);
else ok = false;
}
if (!ok) { help(); return true; }
g_active = true;
status();
return true;
}
} // namespace BenchSim
+31
View File
@@ -0,0 +1,31 @@
/*
* Bench Simulation Module (`sim` console)
*
* Feeds made-up torque / engine rpm / output shaft values into the driveline
* snapshot so the Sport screen, the Driveline and the Vehicle page can be
* looked at on the bench without a CAN bus. While active, the snapshot also
* reads ignition on + engine running, so the screens treat it as live.
*
* Bench tool only: never saved, off at every boot, nothing is transmitted,
* and the Inst. Cluster is not affected (that side has `cfg override`).
* The screens say "SIM" while it is on so a simulated number is never
* mistaken for the car's.
*/
#pragma once
#include <Arduino.h>
#include "drivers/can_driver.h"
namespace BenchSim {
/** True while a simulation is active (`sim ...` until `sim off`). */
bool isActive();
/** Overlay the simulated fields onto a driveline snapshot. No-op when off. */
void apply(driveline_t& dl);
/** `sim torque <Nm> | rpm <n> | shaft <rpm> | status | off` (several pairs per line). */
bool handleCommand(const char* line);
} // namespace BenchSim
+447 -37
View File
@@ -25,13 +25,15 @@ static const uint32_t OBD_RESP_LAST = 0x7EF; // physical request = response
static const uint32_t OBD_REQ_FIRST = 0x7E0;
static const uint32_t OBD_REQ_LAST = 0x7E7;
static const uint32_t BMW_TESTER_ID = 0x6F1; // BMW KWP/UDS tester (Launch, INPA)
static const uint32_t BMW_RX_BASE = 0x600; // an ECU replies on 0x600 + its address
static const uint8_t BMW_ADDR_DDE = 0x12; // engine ECU address (reply on 0x612)
static const uint32_t REPLY_TIMEOUT_MS = 500; // P2 is 50 ms; be generous
static const uint32_t LINGER_MS = 150; // after the first reply, wait for other ECUs
static const uint32_t PENDING_EXTRA_MS = 2000; // NRC 0x78 "response pending"
static const uint32_t TESTER_GUARD_MS = 3000; // refuse to send this soon after a foreign tester
static const uint8_t PAD_BYTE = 0x00;
static const size_t MAX_PAYLOAD = 64;
static const size_t MAX_PAYLOAD = 384; // KWP ident replies can be long
static const int MAX_RESPONDERS = 4;
static const int SCAN_BLOCKS = 8; // 0x00, 0x20, ... 0xE0
@@ -50,7 +52,10 @@ struct responder_t {
static SemaphoreHandle_t g_mutex = NULL;
static state_t g_state = ST_IDLE;
static uint8_t g_req_mode = 0, g_req_pid = 0;
static uint8_t g_req_mode = 0;
static int g_req_pid = 0; // -1 = request had no PID/sub byte (e.g. mode 03)
static bool g_bmw = false; // current request is BMW-addressed on 0x6F1
static uint8_t g_bmw_target = 0; // its target ECU address (reply on 0x600+addr)
static uint32_t g_deadline_ms = 0;
static uint8_t g_replies_this_req = 0;
@@ -75,6 +80,36 @@ static uint32_t g_requests = 0, g_replies = 0, g_timeouts = 0, g_negatives = 0;
static uint32_t g_tx_fail_at_send = 0; // CANDriver tx_failures when the request went out
static bool g_last_req_unacked = false;
// live engine data (Engine data screen) - liveStop() is public, declared in the header
// Which `2C 10 <id>` identifiers to ask is PER DDE SOFTWARE (Patrol 1's set
// returned junk on Patrol 2, 2026-10-18): the Engine data screen picks a set
// from its per-ECU profile table and installs it with liveConfigure(). Until
// then nothing is asked. 0 = no identifier for that slot (never requested).
static live_set_t g_live_set = {0, {0, 0, 0, 0}};
static const uint32_t LIVE_GAP_MS = 80; // between requests (plus the loop's 100 ms tick)
static const uint32_t LIVE_KEEPALIVE_MS = 1500; // stop this long after the screen stops asking
static const uint8_t LIVE_NO_ANSWER_AFTER = 4; // consecutive timeouts
static bool g_live = false;
static bool g_live_defined = false;
static uint8_t g_live_next = 0;
static uint32_t g_live_keep_ms = 0, g_live_last_tx = 0;
static live_state_t g_live_state = LIVE_OFF;
static uint8_t g_live_misses = 0;
static bool g_live_req = false; // the request in flight is a live one (quiet)
static int8_t g_live_req_index = -1; // -1 = the define request
static struct { bool valid; uint16_t raw; uint32_t at_ms; uint8_t nrc; } g_live_vals[LIVE_COUNT];
// ECU identification: handler + a passive reassembler for OTHER testers' `1A xx`
// replies on 0x612 (we see the DDE's frames whoever asked; the asker sends the
// flow control). CAN-task only, so no lock.
static const size_t IDENT_MAX = 96; // `1A 80` is 31-37 bytes, `1A 86` 65
static ident_cb_t g_ident_cb = NULL;
static uint8_t g_pid_buf[IDENT_MAX];
static size_t g_pid_len = 0, g_pid_exp = 0;
static uint8_t g_pid_seq = 0;
static bool g_pid_active = false;
// ============================================================================
// HELPERS
// ============================================================================
@@ -190,8 +225,8 @@ static responder_t* findResponder(uint32_t id, bool create) {
// Transmit
// ----------------------------------------------------------------------------
/** Build and send one single-frame request. Caller holds no lock. */
static bool sendRequest(uint8_t mode, uint8_t pid) {
/** Common preconditions for any transmit; prints the refusal reason. */
static bool clearToSend() {
if (!CANDriver::isActive()) {
print("[diag] refused: CAN is not running");
return false;
@@ -212,23 +247,41 @@ static bool sendRequest(uint8_t mode, uint8_t pid) {
(unsigned long)tester_id, (unsigned long)since_tester);
return false;
}
return true;
}
uint8_t f[8];
memset(f, PAD_BYTE, sizeof(f));
f[0] = 0x02; // ISO-TP single frame, 2 bytes
f[1] = mode;
f[2] = pid;
/** Arm the waiting state. Caller sends the frame right after. */
static void armRequest(uint8_t mode, int pid, bool bmw, uint8_t target) {
lock();
g_state = ST_WAITING;
g_bmw = bmw;
g_bmw_target = target;
g_req_mode = mode;
g_req_pid = pid;
g_deadline_ms = now + REPLY_TIMEOUT_MS;
g_deadline_ms = millis() + REPLY_TIMEOUT_MS;
g_replies_this_req = 0;
g_rx_active = false;
g_requests++;
g_tx_fail_at_send = CANDriver::getStats().tx_failures;
unlock();
}
/** Build and send one single-frame OBD request on 0x7DF. pid < 0 = mode only. */
static bool sendRequest(uint8_t mode, int pid) {
if (!clearToSend()) return false;
uint8_t f[8];
memset(f, PAD_BYTE, sizeof(f));
if (pid < 0) {
f[0] = 0x01; // ISO-TP single frame, 1 byte (e.g. mode 03)
f[1] = mode;
} else {
f[0] = 0x02; // ISO-TP single frame, 2 bytes
f[1] = mode;
f[2] = (uint8_t)pid;
}
armRequest(mode, pid, false, 0);
if (!CANDriver::transmit(OBD_FUNCTIONAL_ID, f, sizeof(f))) {
lock();
@@ -237,7 +290,52 @@ static bool sendRequest(uint8_t mode, uint8_t pid) {
print("[diag] transmit failed (TWAI queue)");
return false;
}
print("[diag] -> 0x7DF %02X %02X", mode, pid);
if (pid < 0) print("[diag] -> 0x7DF %02X", mode);
else print("[diag] -> 0x7DF %02X %02X", mode, pid);
return true;
}
/**
* One single-frame BMW-addressed request on 0x6F1 (ISO 15765 extended
* addressing: byte 0 = target ECU address, then normal ISO-TP). Read-only
* services only - enforced here, not just at the console.
*/
static bool sendBmwRequest(uint8_t target, const uint8_t* req, size_t n) {
static const uint8_t OK_SERVICES[] = {0x1A, 0x18, 0x21, 0x22};
if (n < 1 || n > 6) {
print("[diag] BMW request must be 1..6 bytes (single frame)");
return false;
}
bool allowed = false;
for (size_t i = 0; i < sizeof(OK_SERVICES); i++) {
if (req[0] == OK_SERVICES[i]) allowed = true;
}
if (!allowed) {
print("[diag] service 0x%02X refused - read-only services only (1A ident, 18 DTCs, 21/22 read data)",
req[0]);
return false;
}
if (!clearToSend()) return false;
uint8_t f[8];
memset(f, PAD_BYTE, sizeof(f));
f[0] = target;
f[1] = (uint8_t)n;
memcpy(f + 2, req, n);
armRequest(req[0], (n >= 2) ? (int)req[1] : -1, true, target);
if (!CANDriver::transmit(BMW_TESTER_ID, f, sizeof(f))) {
lock();
g_state = ST_IDLE;
unlock();
print("[diag] transmit failed (TWAI queue)");
return false;
}
char hex[3 * 6 + 1];
hexdump(hex, sizeof(hex), req, n);
print("[diag] -> 0x6F1 [%02X] %s (reply expected on 0x%03lX)", target, hex,
(unsigned long)(BMW_RX_BASE + target));
return true;
}
@@ -245,9 +343,17 @@ static bool sendRequest(uint8_t mode, uint8_t pid) {
static void sendFlowControl(uint32_t responder_id) {
uint8_t f[8];
memset(f, PAD_BYTE, sizeof(f));
f[0] = 0x30; // FC, ContinueToSend
f[1] = 0x00; // block size: all
f[2] = 0x00; // STmin: 0 ms
if (g_bmw) {
f[0] = g_bmw_target; // extended addressing: target first, then the FC
f[1] = 0x30; // FC, ContinueToSend
f[2] = 0x00; // block size: all
f[3] = 0x00; // STmin: 0 ms
CANDriver::transmit(BMW_TESTER_ID, f, sizeof(f));
return;
}
f[0] = 0x30;
f[1] = 0x00;
f[2] = 0x00;
CANDriver::transmit(responder_id - 8, f, sizeof(f));
}
@@ -259,8 +365,30 @@ static void finishScanBlockIfPrimary(uint32_t id, const uint8_t* p, size_t n);
/** A complete ISO-TP payload from `id`. Caller holds g_mutex. */
static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
char hex[3 * 24 + 1];
hexdump(hex, sizeof(hex), p, n > 24 ? 24 : n);
if (g_live_req) {
// quiet: store and finish at once (no linger - only the DDE answers 0x612)
if (n >= 3 && p[0] == 0x7F && p[2] == 0x78) { g_deadline_ms = millis() + PENDING_EXTRA_MS; return; }
g_replies++;
g_replies_this_req++;
g_live_misses = 0;
if (g_live_req_index >= 0) {
auto& v = g_live_vals[g_live_req_index];
if (n >= 4 && p[0] == 0x6C && p[1] == 0x10) {
v.raw = (uint16_t)((p[2] << 8) | p[3]);
v.valid = true;
v.at_ms = millis();
v.nrc = 0;
} else if (n >= 3 && p[0] == 0x7F) {
v.nrc = p[2];
g_negatives++;
}
}
g_state = ST_IDLE;
g_live_req = false;
return;
}
char hex[3 * 48 + 1];
hexdump(hex, sizeof(hex), p, n > 48 ? 48 : n);
g_replies++;
if (n >= 3 && p[0] == 0x7F) {
@@ -284,10 +412,44 @@ static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
g_replies_this_req++;
if (g_deadline_ms > millis() + LINGER_MS) g_deadline_ms = millis() + LINGER_MS;
print("[diag] <- 0x%03lX %s%s", (unsigned long)id, hex, n > 24 ? " ..." : "");
print("[diag] <- 0x%03lX %s%s", (unsigned long)id, hex, n > 48 ? " ..." : "");
if (n < 2 || p[0] != (uint8_t)(g_req_mode + 0x40) || p[1] != g_req_pid) {
print("[diag] (unexpected payload for request %02X %02X)", g_req_mode, g_req_pid);
if (n < 1 || p[0] != (uint8_t)(g_req_mode + 0x40) ||
(!g_bmw && g_req_pid >= 0 && (n < 2 || p[1] != (uint8_t)g_req_pid))) {
print("[diag] (unexpected payload for request %02X)", g_req_mode);
return;
}
if (g_bmw) {
// KWP ident replies are long and the header line clips at 48 bytes:
// dump the whole payload, 16 bytes per line, hex + ascii.
for (size_t i = 1; i < n; i += 16) {
size_t k = (n - i < 16) ? (n - i) : 16;
char hx[3 * 16 + 1];
hexdump(hx, sizeof(hx), p + i, k);
char as[17];
for (size_t j = 0; j < k; j++) {
as[j] = (p[i + j] >= 0x20 && p[i + j] < 0x7F) ? (char)p[i + j] : '.';
}
as[k] = 0;
print("[diag] +%03u %-48s |%s|", (unsigned)(i - 1), hx, as);
}
// our own identification read: hand the block to EcuIdent
if (g_req_mode == 0x1A && g_bmw_target == BMW_ADDR_DDE && n >= 2 && g_ident_cb) {
g_ident_cb(p[1], p, n, true);
}
return;
}
if (g_req_mode == 0x03) {
// 43 <count> <2 bytes per DTC>
uint8_t cnt = (n >= 2) ? p[1] : 0;
print("[diag] %u stored DTC(s):", cnt);
for (size_t i = 2; i + 1 < n; i += 2) {
uint8_t a = p[i], b = p[i + 1];
if (a == 0 && b == 0) continue;
print("[diag] %c%u%X%02X", "PCBU"[a >> 6], (a >> 4) & 3, a & 0x0F, b);
}
return;
}
@@ -326,10 +488,46 @@ static void handleReply(uint32_t id, const uint8_t* p, size_t n) {
}
}
/**
* Reassemble a `5A xx` identification reply the DDE sends to ANOTHER tester
* (our own request's reply goes through handleReply). Extended addressing:
* byte 0 = 0xF1 (the tester), then the ISO-TP PCI.
*/
static void passiveIdent(const twai_message_t& m) {
const uint8_t* d = m.data;
uint8_t dlc = m.data_length_code;
if (dlc < 3 || d[0] != 0xF1) return;
if (g_state == ST_WAITING && g_bmw && g_bmw_target == BMW_ADDR_DDE) return; // ours: handled elsewhere
uint8_t pci = d[1] >> 4;
if (pci == 0x1) { // first frame: F1 1L LL 5A xx ...
if (dlc < 5 || d[3] != 0x5A) { g_pid_active = false; return; }
g_pid_exp = ((size_t)(d[1] & 0x0F) << 8) | d[2];
if (g_pid_exp > IDENT_MAX) g_pid_exp = IDENT_MAX;
g_pid_len = 0;
for (uint8_t i = 3; i < dlc && g_pid_len < g_pid_exp; i++) g_pid_buf[g_pid_len++] = d[i];
g_pid_seq = 1;
g_pid_active = true;
} else if (pci == 0x2) { // consecutive frame: F1 2N ...
if (!g_pid_active || (d[1] & 0x0F) != (g_pid_seq & 0x0F)) return;
for (uint8_t i = 2; i < dlc && g_pid_len < g_pid_exp; i++) g_pid_buf[g_pid_len++] = d[i];
g_pid_seq++;
if (g_pid_len >= g_pid_exp) {
g_pid_active = false;
if (g_pid_len >= 2) g_ident_cb(g_pid_buf[1], g_pid_buf, g_pid_len, false);
}
} else if (pci == 0x0) { // single frame (not seen from a DDE, but cheap)
size_t len = d[1] & 0x0F;
if (len >= 2 && 2 + len <= dlc && d[2] == 0x5A) g_ident_cb(d[3], d + 2, len, false);
}
}
void onFrame(const twai_message_t& m) {
if (m.extd) return;
uint32_t id = m.identifier;
if (id == BMW_RX_BASE + BMW_ADDR_DDE && g_ident_cb) passiveIdent(m);
// Foreign tester activity: our own frames are not looped back in NORMAL mode,
// so anything on these IDs is somebody else's request.
if (id == OBD_FUNCTIONAL_ID || (id >= OBD_REQ_FIRST && id <= OBD_REQ_LAST) || id == BMW_TESTER_ID) {
@@ -340,27 +538,40 @@ void onFrame(const twai_message_t& m) {
return;
}
if (id < OBD_RESP_FIRST || id > OBD_RESP_LAST) return;
if (m.data_length_code == 0) return;
bool maybe_obd = (id >= OBD_RESP_FIRST && id <= OBD_RESP_LAST);
bool maybe_bmw = (id >= BMW_RX_BASE && id < BMW_RX_BASE + 0x100);
if (!maybe_obd && !maybe_bmw) return;
lock();
if (g_state != ST_WAITING) { unlock(); return; }
uint8_t pci = m.data[0] >> 4;
const uint8_t* d = m.data;
uint8_t dlc = m.data_length_code;
uint8_t off = 0; // index of the ISO-TP PCI byte
if (g_bmw) {
// extended addressing: reply on 0x600+target, byte 0 = tester addr 0xF1
if (id != BMW_RX_BASE + g_bmw_target || dlc < 2 || d[0] != 0xF1) { unlock(); return; }
off = 1;
} else if (!maybe_obd) {
unlock();
return;
}
uint8_t pci = d[off] >> 4;
if (pci == 0x0) {
// single frame
size_t len = d[0] & 0x0F;
if (len > 0 && len + 1 <= dlc) handleReply(id, d + 1, len);
size_t len = d[off] & 0x0F;
if (len > 0 && off + 1 + len <= dlc) handleReply(id, d + off + 1, len);
} else if (pci == 0x1) {
// first frame: 1L LL data[6]
if (!g_rx_active && dlc >= 2) {
g_rx_expected = ((size_t)(d[0] & 0x0F) << 8) | d[1];
// first frame: 1L LL data[...]
if (!g_rx_active && dlc >= (uint8_t)(off + 2)) {
g_rx_expected = ((size_t)(d[off] & 0x0F) << 8) | d[off + 1];
if (g_rx_expected > MAX_PAYLOAD) g_rx_expected = MAX_PAYLOAD;
g_rx_len = 0;
for (uint8_t i = 2; i < dlc && g_rx_len < g_rx_expected; i++) g_rx_buf[g_rx_len++] = d[i];
for (uint8_t i = off + 2; i < dlc && g_rx_len < g_rx_expected; i++) g_rx_buf[g_rx_len++] = d[i];
g_rx_id = id;
g_rx_seq = 1;
g_rx_active = true;
@@ -370,9 +581,9 @@ void onFrame(const twai_message_t& m) {
return;
}
} else if (pci == 0x2) {
// consecutive frame: 2N data[7]
if (g_rx_active && id == g_rx_id && (d[0] & 0x0F) == (g_rx_seq & 0x0F)) {
for (uint8_t i = 1; i < dlc && g_rx_len < g_rx_expected; i++) g_rx_buf[g_rx_len++] = d[i];
// consecutive frame: 2N data[...]
if (g_rx_active && id == g_rx_id && (d[off] & 0x0F) == (g_rx_seq & 0x0F)) {
for (uint8_t i = off + 1; i < dlc && g_rx_len < g_rx_expected; i++) g_rx_buf[g_rx_len++] = d[i];
g_rx_seq++;
g_deadline_ms = millis() + REPLY_TIMEOUT_MS;
if (g_rx_len >= g_rx_expected) {
@@ -421,13 +632,84 @@ static void printScanSummary() {
print("[diag] next: `diag pid 0C` (rpm) to prove a data read, `diag vin` for the donor");
}
/** One fixed `2C 10 <id>` request to the DDE for the live poll. Caller checked the guards. */
static void sendLive(int8_t index) {
uint16_t vid = index < 0 ? g_live_set.define_id : g_live_set.ids[index];
uint8_t f[8];
memset(f, PAD_BYTE, sizeof(f));
f[0] = BMW_ADDR_DDE;
f[1] = 0x04;
f[2] = 0x2C;
f[3] = 0x10;
f[4] = (uint8_t)(vid >> 8);
f[5] = (uint8_t)vid;
armRequest(0x2C, 0x10, true, BMW_ADDR_DDE);
lock();
g_live_req = true;
g_live_req_index = index;
unlock();
if (!CANDriver::transmit(BMW_TESTER_ID, f, sizeof(f), CANDriver::isRawLogging())) {
lock();
g_state = ST_IDLE;
g_live_req = false;
unlock();
}
}
static void liveTick() {
if (!g_live) return;
uint32_t now = millis();
if (now - g_live_keep_ms > LIVE_KEEPALIVE_MS) {
liveStop();
return;
}
if (!CANDriver::isActive()) { g_live_state = LIVE_CAN_OFF; return; }
lock();
bool busy = (g_state != ST_IDLE);
bool tester = (g_last_tester_ms != 0) && (now - g_last_tester_ms < TESTER_GUARD_MS);
unlock();
if (tester) {
g_live_state = LIVE_PAUSED_TESTER;
g_live_defined = false; // redo the define once the other tester is gone
return;
}
if (busy || now - g_live_last_tx < LIVE_GAP_MS) return;
g_live_state = (g_live_misses >= LIVE_NO_ANSWER_AFTER) ? LIVE_NO_ANSWER : LIVE_RUNNING;
g_live_last_tx = now;
if (!g_live_defined) {
g_live_defined = true;
if (g_live_set.define_id) { sendLive(-1); return; }
}
// next slot that has an identifier on this DDE (at most one full turn)
for (int i = 0; i < LIVE_COUNT; i++) {
uint8_t slot = (uint8_t)((g_live_next + i) % LIVE_COUNT);
if (g_live_set.ids[slot] == 0) continue;
g_live_next = (uint8_t)((slot + 1) % LIVE_COUNT);
sendLive((int8_t)slot);
return;
}
// no identifiers at all: nothing to ask (the screen says so)
}
void tick() {
if (g_state == ST_IDLE) return;
if (g_state == ST_IDLE) { liveTick(); return; }
uint32_t now = millis();
lock();
if ((int32_t)(now - g_deadline_ms) < 0) { unlock(); return; }
if (g_live_req) { // a live request timed out: count it quietly, carry on
g_state = ST_IDLE;
g_live_req = false;
g_timeouts++;
if (g_live_misses < 255) g_live_misses++;
unlock();
liveTick();
return;
}
// request over
bool got_reply = g_replies_this_req > 0;
bool scan = g_scan_active;
@@ -455,8 +737,13 @@ void tick() {
unlock();
if (!got_reply) {
print("[diag] no reply within %lu ms (request %02X %02X)%s", (unsigned long)REPLY_TIMEOUT_MS,
g_req_mode, g_req_pid, unacked ? " - frame was not ACKed by any node" : " - frame was ACKed, ECU stayed silent");
if (g_req_pid < 0) {
print("[diag] no reply within %lu ms (request %02X)%s", (unsigned long)REPLY_TIMEOUT_MS,
g_req_mode, unacked ? " - frame was not ACKed by any node" : " - frame was ACKed, ECU stayed silent");
} else {
print("[diag] no reply within %lu ms (request %02X %02X)%s", (unsigned long)REPLY_TIMEOUT_MS,
g_req_mode, g_req_pid, unacked ? " - frame was not ACKed by any node" : " - frame was ACKed, ECU stayed silent");
}
}
if (scan) {
if (send_next) {
@@ -474,10 +761,14 @@ void tick() {
static void help() {
print("diag pids scan mode-01 supported-PID bitmaps (the Route A probe)");
print("diag pid <hex> one mode-01 request, e.g. `diag pid 0C` (rpm), `diag pid 70` (boost)");
print("diag dtc mode 03 - read stored generic DTCs");
print("diag vin mode 09 PID 02 - VIN");
print("diag ecu mode 09 PID 0A - ECU name");
print("diag ident [addr] BMW KWP `1A 80` ECU identification (default addr 12 = DDE, reply 0x612)");
print("diag bmw <addr> <hex...> raw BMW request on 0x6F1, read-only services only (1A/18/21/22)");
print("diag raw on|off CANRAW frame logging (off = clean console during scans)");
print("diag status counters, responders, tester guard");
print("Sends on 0x7DF only, one request at a time; refused while a scan tool is polling.");
print("Sends on 0x7DF / 0x6F1 only, one request at a time; refused while a scan tool is polling.");
}
static void status() {
@@ -507,9 +798,9 @@ bool handleCommand(const char* line) {
strncpy(buf, line, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
char* argv[4] = {0};
char* argv[10] = {0};
int argc = 0;
for (char* tok = strtok(buf, " \t"); tok && argc < 4; tok = strtok(NULL, " \t")) {
for (char* tok = strtok(buf, " \t"); tok && argc < 10; tok = strtok(NULL, " \t")) {
argv[argc++] = tok;
}
if (argc == 0 || strcmp(argv[0], "diag") != 0) return false;
@@ -544,6 +835,46 @@ bool handleCommand(const char* line) {
if (!strcmp(argv[1], "vin")) { sendRequest(0x09, 0x02); return true; }
if (!strcmp(argv[1], "ecu")) { sendRequest(0x09, 0x0A); return true; }
if (!strcmp(argv[1], "dtc")) { sendRequest(0x03, -1); return true; }
if (!strcmp(argv[1], "raw") && argc == 3) {
bool on = !strcmp(argv[2], "on");
CANDriver::setRawLogging(on);
print("[diag] CANRAW logging %s", on ? "on" : "off");
return true;
}
if (!strcmp(argv[1], "ident")) {
uint8_t target = BMW_ADDR_DDE;
if (argc >= 3) target = (uint8_t)strtol(argv[2], NULL, 16);
uint8_t req[2] = {0x1A, 0x80};
sendBmwRequest(target, req, sizeof(req));
return true;
}
if (!strcmp(argv[1], "bmw") && argc >= 4) {
uint8_t target = (uint8_t)strtol(argv[2], NULL, 16);
char hexs[13] = {0}; // up to 6 bytes = 12 hex chars
size_t hl = 0;
for (int i = 3; i < argc; i++) {
for (const char* c = argv[i]; *c; c++) {
if (hl >= sizeof(hexs) - 1) { print("[diag] too many bytes (max 6)"); return true; }
hexs[hl++] = *c;
}
}
if (hl == 0 || (hl % 2) != 0) {
print("[diag] give whole hex bytes, e.g. `diag bmw 12 1A 80`");
return true;
}
uint8_t req[6];
size_t n = 0;
for (size_t i = 0; i < hl; i += 2) {
char b[3] = {hexs[i], hexs[i + 1], 0};
req[n++] = (uint8_t)strtol(b, NULL, 16);
}
sendBmwRequest(target, req, n);
return true;
}
help();
return true;
@@ -553,4 +884,83 @@ void init() {
if (!g_mutex) g_mutex = xSemaphoreCreateMutex();
}
// ----------------------------------------------------------------------------
// Live engine data
// ----------------------------------------------------------------------------
static void liveRestart() {
lock();
memset(g_live_vals, 0, sizeof(g_live_vals));
unlock();
g_live_defined = false;
g_live_next = 0;
g_live_misses = 0;
g_live_last_tx = 0;
g_live_state = LIVE_RUNNING;
}
void liveConfigure(const live_set_t* set) {
live_set_t s = set ? *set : live_set_t{0, {0, 0, 0, 0}};
if (memcmp(&s, &g_live_set, sizeof(s)) == 0) return;
g_live_set = s;
if (g_live) liveRestart(); // old values belong to the old identifiers
print("[diag] live engine data identifiers: define %04X, rail %04X, boost %04X, air temp %04X, battery %04X (0 = not asked)",
s.define_id, s.ids[LIVE_RAIL], s.ids[LIVE_BOOST], s.ids[LIVE_AIR_TEMP], s.ids[LIVE_BATTERY]);
}
void liveKeepAlive() {
g_live_keep_ms = millis();
if (g_live) return;
g_live = true;
liveRestart();
print("[diag] live engine data ON: polling the DDE (2C 10 %04X/%04X/%04X/%04X, 0 = not asked)",
g_live_set.ids[LIVE_RAIL], g_live_set.ids[LIVE_BOOST], g_live_set.ids[LIVE_AIR_TEMP], g_live_set.ids[LIVE_BATTERY]);
}
void liveStop() {
if (!g_live) return;
g_live = false;
g_live_state = LIVE_OFF;
print("[diag] live engine data OFF");
}
live_state_t liveState() {
return g_live ? g_live_state : LIVE_OFF;
}
live_value_t liveValue(live_id_t id) {
live_value_t out = {false, 0, 0, 0};
if (id >= LIVE_COUNT) return out;
lock();
out.valid = g_live_vals[id].valid;
out.raw = g_live_vals[id].raw;
out.nrc = g_live_vals[id].nrc;
out.age_ms = out.valid ? millis() - g_live_vals[id].at_ms : 0;
unlock();
return out;
}
// ----------------------------------------------------------------------------
// ECU identification
// ----------------------------------------------------------------------------
bool canSendNow() {
if (!CANDriver::isActive()) return false;
uint32_t now = millis();
lock();
bool busy = (g_state != ST_IDLE);
bool tester = (g_last_tester_ms != 0) && (now - g_last_tester_ms < TESTER_GUARD_MS);
unlock();
return !busy && !tester;
}
bool requestIdent(uint8_t sub) {
uint8_t req[2] = {0x1A, sub};
return sendBmwRequest(BMW_ADDR_DDE, req, sizeof(req));
}
void setIdentHandler(ident_cb_t cb) {
g_ident_cb = cb;
}
} // namespace DiagProbe
+86
View File
@@ -15,11 +15,30 @@
* Console (USB serial, same line reader as `cfg`):
* diag pids scan the mode-01 supported-PID bitmaps (00, 20, 40, ...)
* diag pid <hex> one mode-01 request, e.g. `diag pid 0C` (rpm)
* diag dtc mode 03 — stored generic DTCs
* diag vin mode 09 PID 02 — VIN (identifies the donor)
* diag ecu mode 09 PID 0A — ECU name string
* diag ident [addr] BMW KWP `1A 80` ECU identification on 0x6F1 (default 12 = DDE)
* diag bmw <addr> <hex...> raw BMW-addressed request; read-only services only
* diag status counters, responders seen, tester-guard timer
* diag help
*
* BMW requests use ISO 15765 extended addressing: TX on 0x6F1 with byte 0 =
* target ECU address, reply on 0x600+address with byte 0 = 0xF1. Allowed
* services are whitelisted in sendBmwRequest(): 1A (ident), 18 (DTCs),
* 21/22 (read data) — never session control, resets, or writes.
*
* Live engine data (Engine data screen, 2026-10-07): while the screen keeps
* calling liveKeepAlive(), the probe polls up to four DDE values with the
* same KWP `2C 10 <id>` requests the Launch uses (an optional one-time
* define, then the slot identifiers in turn, one request in flight, ~100 ms
* apart). The identifiers are installed by the screen per identified DDE
* (liveConfigure(); Patrol 1: define 15E0, rail 00DF, boost 0091, charge-air
* temp 16A8, battery 0093; Patrol 2: rail 00C2, boost 003A, battery 002F).
* Quiet on the console,
* pauses while another tester is on the bus, stops 1.5 s after the last
* keep-alive. `2C` is NOT allowed from the console - only these frames.
*
* Every frame we send is echoed on the console as
* CANTX,<ts_ms>,<id_hex>,0,<dlc>,<data_hex>
* — the same shape as CANRAW — so a capture holds both halves of every exchange.
@@ -50,4 +69,71 @@ void tick();
*/
void onFrame(const twai_message_t& m);
// ---- Live engine data ------------------------------------------------------
typedef enum { LIVE_RAIL, LIVE_BOOST, LIVE_AIR_TEMP, LIVE_BATTERY, LIVE_COUNT } live_id_t;
typedef enum {
LIVE_OFF, // not polling
LIVE_RUNNING,
LIVE_PAUSED_TESTER, // another tester (e.g. the Launch) is polling - we stay quiet
LIVE_CAN_OFF, // CAN task stopped
LIVE_NO_ANSWER // requests go out but the DDE does not answer
} live_state_t;
typedef struct {
bool valid; // at least one reply since polling started
uint16_t raw; // last 2-byte value from `6C 10 HH LL`
uint32_t age_ms; // since that reply
uint8_t nrc; // last negative-response code (0 = none)
} live_value_t;
/**
* The `2C 10 <id>` identifiers to poll, one per live_id_t slot, 0 = none known
* for this DDE (that slot is never requested, liveValue() stays invalid), plus
* the one-time define id sent first (0 = none). THE IDENTIFIERS DIFFER PER DDE
* SOFTWARE: Patrol 1's set read junk on Patrol 2 (2026-10-18), so the Engine
* data screen installs the set that matches the identified ECU (`EcuIdent`).
* Nothing is asked until a set with at least one identifier is installed.
*/
typedef struct {
uint16_t define_id;
uint16_t ids[LIVE_COUNT];
} live_set_t;
/** Install the identifier set (NULL = none). Restarts the values if polling. */
void liveConfigure(const live_set_t* set);
/** Keep the live poll running; starts it if needed. Call from loop() while the screen is shown. */
void liveKeepAlive();
/** Stop at once (leaving the screen). */
void liveStop();
live_state_t liveState();
live_value_t liveValue(live_id_t id);
// ---- ECU identification (EcuIdent module) ----------------------------------
/**
* True when a request could go out right now: CAN running, nothing in flight,
* no foreign tester for TESTER_GUARD_MS. Prints nothing (unlike a refused send).
*/
bool canSendNow();
/**
* One KWP `1A <sub>` identification request to the DDE on 0x6F1 (sub 0x86 or
* 0x80), console-echoed like `diag ident`. Returns false if refused.
*/
bool requestIdent(uint8_t sub);
/**
* Handler for every complete `5A <sub> ...` identification payload the DDE puts
* on 0x612: the reply to our own request (ours = true), or to another tester's
* (ours = false - the Launch re-reads `1A 80` every cycle, so a connected scan
* tool identifies the ECU for free). Runs in the CAN task: copy and return.
*/
typedef void (*ident_cb_t)(uint8_t sub, const uint8_t* payload, size_t n, bool ours);
void setIdentHandler(ident_cb_t cb);
} // namespace DiagProbe
+163
View File
@@ -0,0 +1,163 @@
/*
* Differential lock inputs - see diff_locks.h
*
* Schematic (V1.2, sheet 1): DINx -> PC814 LED -> 3.6 kOhm -> DI_COM. The
* optocoupler's transistor pulls DIx (4.7 kOhm to 3V3) LOW while current flows,
* so a LOCKED diff reads 0 on its EXIO bit. The PC814 LED is bidirectional:
* +12 V on DINx with DI_COM on ground is the "PNP / high-level" wiring.
*/
#include "diff_locks.h"
#include "settings_manager.h"
#include "serial_lock.h"
#include "display/lvgl_v8_port.h"
#include <driver/i2c.h>
#include <stdarg.h>
namespace DiffLocks {
// CH422G on the panel library's I2C host 0. Its "registers" are I2C addresses.
static const i2c_port_t CH422G_PORT = I2C_NUM_0;
static const uint8_t ADDR_WR_SET = 0x24; // system parameter byte
static const uint8_t ADDR_RD_IO = 0x26; // IO0-7 pin levels
// WR_SET as the board config leaves it (ESP_PANEL_BOARD_EXPANDER_POST_BEGIN_FUNCTION:
// enableAllIO_Output -> IO_OE only; OC push-pull, no sleep). Input = IO_OE cleared.
static const uint8_t WR_SET_OUTPUT = 0x01;
static const uint8_t WR_SET_INPUT = 0x00;
static const uint8_t BIT_REAR = 1 << 0; // DI0 = EXIO0
static const uint8_t BIT_FRONT = 1 << 5; // DI1 = EXIO5
static const uint32_t POLL_MS = 250;
static const uint8_t FAULT_AFTER = 3; // failed reads in a row
static bool g_enabled = false;
static bool g_inverted = false;
static bool g_rear = false, g_front = false; // debounced
static bool g_have_state = false;
static uint8_t g_last_raw = 0xFF;
static bool g_have_raw = false;
static uint8_t g_fail_run = 0;
static uint32_t g_reads = 0, g_fails = 0;
static uint32_t g_last_poll = 0;
static void print(const char* fmt, ...) {
char buf[160];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static esp_err_t writeSet(uint8_t v) {
return i2c_master_write_to_device(CH422G_PORT, ADDR_WR_SET, &v, 1, pdMS_TO_TICKS(10));
}
/**
* One raw read of IO0-7. The bank is an input only between the two WR_SET
* writes (three short I2C transactions); the output is restored even when the
* read fails, and retried, because touch reset, backlight and LCD reset live on
* the same bank. The caller holds the LVGL lock, so no touch read (same bus)
* can land in the middle.
*/
static bool readBank(uint8_t* out) {
if (writeSet(WR_SET_INPUT) != ESP_OK) {
writeSet(WR_SET_OUTPUT); // a half-done write: make sure we are back
return false;
}
esp_err_t r = i2c_master_read_from_device(CH422G_PORT, ADDR_RD_IO, out, 1, pdMS_TO_TICKS(10));
for (int i = 0; i < 3 && writeSet(WR_SET_OUTPUT) != ESP_OK; i++) {}
return r == ESP_OK;
}
void init(bool enabled, bool inverted) {
g_enabled = enabled;
g_inverted = inverted;
print("[difflock] %s (DI0 = rear, DI1 = front, %s)", enabled ? "ON" : "OFF - Settings > System to enable",
inverted ? "INVERTED: no current = locked" : "current = locked");
}
void setEnabled(bool enabled) {
if (enabled == g_enabled) return;
g_enabled = enabled;
g_have_state = g_have_raw = false;
g_rear = g_front = false;
g_fail_run = 0;
SettingsManager::saveDiffLockState(enabled);
}
void setInverted(bool inverted) {
if (inverted == g_inverted) return;
g_inverted = inverted;
g_have_state = g_have_raw = false; // re-evaluate from the next two reads
SettingsManager::saveDiffLockInvert(inverted);
}
bool isInverted() { return g_inverted; }
bool isEnabled() { return g_enabled; }
bool isValid() { return g_enabled && g_have_state && g_fail_run < FAULT_AFTER; }
bool rearLocked() { return isValid() && g_rear; }
bool frontLocked() { return isValid() && g_front; }
void tick() {
if (!g_enabled || millis() - g_last_poll < POLL_MS) return;
g_last_poll = millis();
if (!lvgl_port_lock(100)) return; // UI busy: try again next poll
uint8_t raw = 0xFF;
bool ok = readBank(&raw);
lvgl_port_unlock();
g_reads++;
if (!ok) {
g_fails++;
if (g_fail_run < 255) g_fail_run++;
if (g_fail_run == FAULT_AFTER) print("[difflock] CH422G read failing - lock states unknown");
return;
}
g_fail_run = 0;
// Accept a state only when two reads in a row agree (<= 0.5 s latency).
uint8_t bits = raw & (BIT_REAR | BIT_FRONT);
if (g_have_raw && bits == (g_last_raw & (BIT_REAR | BIT_FRONT))) {
// opto conducting = pin low; that is "locked" unless the polarity is inverted
bool rear = !(bits & BIT_REAR) != g_inverted;
bool front = !(bits & BIT_FRONT) != g_inverted;
if (!g_have_state || rear != g_rear || front != g_front) {
g_rear = rear;
g_front = front;
g_have_state = true;
print("[difflock] rear %s, front %s%s", rear ? "LOCKED" : "open", front ? "LOCKED" : "open",
(front && !rear) ? " (front without rear - check the DI0 wiring)" : "");
}
}
g_last_raw = raw;
g_have_raw = true;
}
bool handleCommand(const char* line) {
if (strncmp(line, "difflock", 8) != 0 || (line[8] != 0 && line[8] != ' ')) return false;
const char* a = line + 8;
while (*a == ' ') a++;
if (!strcmp(a, "on")) { setEnabled(true); print("[difflock] ON (saved)"); return true; }
if (!strcmp(a, "off")) { setEnabled(false); print("[difflock] OFF (saved)"); return true; }
if (!strcmp(a, "invert on")) { setInverted(true); print("[difflock] INVERTED: no current = locked (saved)"); return true; }
if (!strcmp(a, "invert off")) { setInverted(false); print("[difflock] normal: current (+12 V) = locked (saved)"); return true; }
if (!*a || !strcmp(a, "status")) {
if (!g_enabled) { print("[difflock] OFF - inputs not read ('difflock on' or Settings > System)"); return true; }
print("[difflock] rear %s, front %s | %s | raw IO0-7 0x%02X | %lu reads, %lu failed%s",
!isValid() ? "?" : g_rear ? "LOCKED" : "open",
!isValid() ? "?" : g_front ? "LOCKED" : "open",
g_inverted ? "inverted" : "normal", g_last_raw, (unsigned long)g_reads, (unsigned long)g_fails,
g_fail_run >= FAULT_AFTER ? " | READ FAULT" : "");
return true;
}
print("[difflock] usage: difflock status | on | off | invert on|off (DI0 = rear, DI1 = front)");
return true;
}
} // namespace DiffLocks
+47
View File
@@ -0,0 +1,47 @@
/*
* Differential lock inputs - DI0 = rear, DI1 = front
*
* The Patrol's lock switches put +12 V on a wire while a diff is locked. Those
* wires go to the board's isolated inputs (PC814 optocouplers, 5-36 V, DI_COM to
* vehicle ground). The inputs reach the ESP32 only through the CH422G expander
* (DI0 = EXIO0, DI1 = EXIO5), whose IO0-7 are all-in or all-out as ONE bank - and
* the same bank drives touch reset, backlight enable and LCD reset. So each read
* switches the bank to input for ~0.1 ms and straight back (output latches are
* kept by the chip). That is why the whole feature sits behind a Settings switch,
* default OFF: a board without diff-lock wiring never touches the bank.
*/
#pragma once
#include <Arduino.h>
namespace DiffLocks {
/** Call once after DisplayInit (the CH422G's I2C bus is installed by the panel library). */
void init(bool enabled, bool inverted);
/** Settings switch / `difflock on|off`. Saved to NVS (SettingsManager). */
void setEnabled(bool enabled);
bool isEnabled();
/**
* Polarity. Normal: current through the input (+12 V on DINx) = locked.
* Inverted: NO current = locked - the Patrol's ground-switched lock lamps give
* 12 V through the lamp while unlocked and 0 V once the diff switch closes
* (seen in the car, 2026-09-29). Saved to NVS.
*/
void setInverted(bool inverted);
bool isInverted();
/** Poll the inputs (4 Hz, debounced over two reads). Call from loop(). */
void tick();
/** Enabled AND the last reads succeeded - otherwise the lock states mean nothing. */
bool isValid();
bool rearLocked();
bool frontLocked();
/** `difflock status | on | off | invert on|off`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace DiffLocks
+39 -9
View File
@@ -4,11 +4,36 @@
#include "display_init.h"
#include "display/lvgl_v8_port.h"
#include "ui/ui.h"
#include "driveline_screen.h"
#include "config/ota_config.h" // FW_VERSION
namespace DisplayInit {
static Backlight* g_backlight = nullptr;
static esp_expander::Base* g_expander = nullptr;
/**
* Firmware version, bottom-right on every screen. Lives on lv_layer_top(), which
* sits above all screens and survives screen switches. Labels aren't
* clickable, so it never steals touches or swipes from the screen below.
* Call with the LVGL lock held.
*/
static void createVersionLabel() {
lv_obj_t* lbl = lv_label_create(lv_layer_top());
lv_label_set_text(lbl, "A " FW_VERSION);
lv_obj_set_style_text_font(lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(lbl, lv_color_hex(0x808080), 0);
lv_obj_align(lbl, LV_ALIGN_BOTTOM_RIGHT, -8, -4);
}
esp_expander::Base* expander() { return g_expander; }
void setBacklight(bool on) {
if (g_backlight == nullptr) return;
if (on) g_backlight->on();
else g_backlight->off();
}
// ============================================================================
// PUBLIC API IMPLEMENTATION
// ============================================================================
@@ -67,17 +92,20 @@ DisplayObjects init() {
Serial.println("[DisplayInit] Step 11: LVGL initialized successfully!");
Serial.flush();
// Step 12-13: Load SquareLine Studio UI
Serial.println("[DisplayInit] Step 12: Loading SquareLine Studio UI...");
// Step 12-13: Theme + boot screen
Serial.println("[DisplayInit] Step 12: Loading UI...");
lvgl_port_lock(-1);
ui_init(); // Initialize the SquareLine Studio generated UI
// Note: onSelectSSID event handler is registered in ui_Settings_Screen.c
// Boot screen: the hand-coded Driveline screen. ui_init() only loads an
// empty placeholder now (the SquareLine Home screen was removed 2026-09-21);
// swap while the backlight is still off so there's no flash.
// Dark default theme, blue primary. The hand-coded screens override most
// styles, but the keyboard, dialogs, text areas, switches and sliders take
// their base look from it.
lv_disp_t* disp = lv_disp_get_default();
lv_disp_set_theme(disp, lv_theme_default_init(disp, lv_palette_main(LV_PALETTE_BLUE),
lv_palette_main(LV_PALETTE_RED), true, LV_FONT_DEFAULT));
// Boot screen, loaded while the backlight is still off so there's no flash.
DrivelineScreen::show();
createVersionLabel();
lvgl_port_unlock();
Serial.println("[DisplayInit] Step 13: SquareLine UI loaded successfully!");
Serial.println("[DisplayInit] Step 13: UI loaded");
// Small delay to ensure UI is rendered
delay(100);
@@ -91,6 +119,8 @@ DisplayObjects init() {
Serial.println("[DisplayInit] Display initialization complete!");
// Return board and backlight objects for later use
g_backlight = backlight;
g_expander = board->getIO_Expander() ? board->getIO_Expander()->getBase() : nullptr;
return {board, backlight};
}
+14 -2
View File
@@ -4,7 +4,7 @@
* Handles hardware-specific initialization for the Waveshare ESP32-S3-Touch-LCD-5B:
* - Board initialization (LCD panel, touch controller)
* - LVGL initialization and configuration
* - SquareLine Studio UI loading
* - LVGL theme and the boot (Driveline) screen
* - Backlight control to prevent white flash during startup
*/
@@ -35,7 +35,7 @@ struct DisplayObjects {
* 3. Initialize backlight (off initially to prevent white flash)
* 4. Start the board
* 5. Initialize LVGL porting layer
* 6. Load SquareLine Studio UI
* 6. Set the LVGL theme and show the Driveline screen
* 7. Turn on backlight after UI is ready
*
* @return DisplayObjects containing board and backlight pointers
@@ -43,4 +43,16 @@ struct DisplayObjects {
*/
DisplayObjects init();
/** Backlight on/off after init() (e.g. dark during OTA flash writes, which flicker the panel). */
void setBacklight(bool on);
/**
* The board's CH422G IO expander (panel library object), after init(). Modules
* that drive its OC pins (ReverseLight: OC0 = DO0) must go through this object,
* never raw I2C, so the library's cached output register stays right - the
* backlight writes that cache back to the chip on every on/off. NULL if the
* board has no expander.
*/
esp_expander::Base* expander();
} // namespace DisplayInit
+313 -58
View File
@@ -4,15 +4,20 @@
#include "driveline_screen.h"
#include "uart_manager.h"
#include <string.h>
#include <math.h>
#include "display/lvgl_v8_port.h"
#include "drivers/can_driver.h"
#include "tuning_screen.h"
#include "settings_screen.h"
#include "diff_locks.h"
#include "engine_screen.h"
#include "sport_screen.h"
#include "vehicle.h"
#include "bench_sim.h"
#include "ui_kit.h"
#include "esp_log.h"
extern "C" {
#include "ui.h"
}
namespace DrivelineScreen {
// ============================================================================
@@ -26,6 +31,8 @@ namespace DrivelineScreen {
#define COL_ACCENT lv_color_hex(0x3DA9FC)
#define COL_OK lv_color_hex(0x3DD68C)
#define COL_WARN lv_color_hex(0xE5484D)
#define COL_ALERT lv_color_hex(0xFF3B30) // threshold crossed: value + title
#define COL_AMBER lv_color_hex(0xF5A524)
#define RPM_MAX 5000 // M57N redline is ~4500; a little headroom
@@ -38,16 +45,19 @@ static lv_obj_t* g_gear_lbl = NULL;
static lv_obj_t* g_gear_ring = NULL;
static lv_obj_t* g_coolant_lbl = NULL;
static lv_obj_t* g_gearbox_lbl = NULL;
static lv_obj_t* g_coolant_title = NULL;
static lv_obj_t* g_gearbox_title = NULL;
static lv_obj_t* g_rpm_bar = NULL;
static lv_obj_t* g_rpm_lbl = NULL;
static lv_obj_t* g_torque_lbl = NULL;
static lv_obj_t* g_pedal_lbl = NULL;
static lv_obj_t* g_shaft_lbl = NULL;
static lv_obj_t* g_speed_lbl = NULL;
static lv_obj_t* g_ign_chip = NULL;
static lv_obj_t* g_eng_chip = NULL;
static lv_obj_t* g_clutch_chip = NULL;
static lv_obj_t* g_cool_chip = NULL;
static lv_obj_t* g_mismatch_lbl = NULL;
static lv_obj_t* g_diff_box = NULL; // top-right: chassis top view, locked axles lit
// ============================================================================
// PRIVATE HELPERS
@@ -70,12 +80,180 @@ static lv_obj_t* makeChip(lv_obj_t* parent, const char* text) {
}
/**
* @brief Set a chip's text and colour in one go.
* @brief lv_label_set_text() only if the text differs. lv_label_set_text()
* re-lays-out and invalidates the label even when the string is the
* same, and this screen refreshes at 10 Hz - with constant data that was
* ~40 kpx redrawn 10x a second for nothing, a third of core 1 and 50 ms/s
* of PSRAM writes (perf baseline 2026-09-27).
*/
static void setText(lv_obj_t* lbl, const char* text) {
if (lbl == NULL) return;
const char* cur = lv_label_get_text(lbl);
if (cur != NULL && strcmp(cur, text) == 0) return;
lv_label_set_text(lbl, text);
}
/** Text colour, written only on change (a style write invalidates regardless). */
static void setColour(lv_obj_t* o, lv_color_t colour) {
if (o == NULL) return;
if (lv_color_to32(lv_obj_get_style_text_color(o, 0)) != lv_color_to32(colour)) {
lv_obj_set_style_text_color(o, colour, 0);
}
}
/** Ring border colour, written only on change. */
static void setRing(lv_color_t colour) {
if (lv_color_to32(lv_obj_get_style_border_color(g_gear_ring, 0)) != lv_color_to32(colour)) {
lv_obj_set_style_border_color(g_gear_ring, colour, 0);
}
}
/**
* @brief Set a chip's text and colour, touching the object only on a change
* (a style write invalidates the object even for an identical value).
*/
static void setChip(lv_obj_t* chip, const char* text, lv_color_t colour) {
if (chip == NULL) return;
lv_label_set_text(chip, text);
lv_obj_set_style_text_color(chip, colour, 0);
setText(chip, text);
if (lv_color_to32(lv_obj_get_style_text_color(chip, 0)) != lv_color_to32(colour)) {
lv_obj_set_style_text_color(chip, colour, 0);
}
}
// ---- diff-lock drawing ------------------------------------------------------
// A top view of the chassis, after the user's sketch (front up): steered front
// tyres on the front axle, prop shaft, rear axle on straight tyres. All four
// tyres are the same square-cornered 24 x 76 rectangle. A locked axle lights up:
// axle, tyres filled, and an X on its diff. Geometry is in sketch pixels, scaled
// by DL_S. Wheelbase 151 = the sketch's 189 shortened by 20 % (user, 2026-09-29).
static const float DL_S = 0.46f; // sketch -> screen
static const lv_coord_t DL_BOX_W = 110; // hugs the drawing (dl(DL_W) = 98)
static const float DL_W = 212; // sketch width the drawing is centred in
static const float DL_SHAFT_X = 106;
static const float DL_FRONT_Y = 45;
static const float DL_REAR_Y = DL_FRONT_Y + 151;
static const float DL_TRACK_L = 45, DL_TRACK_R = 167; // tyre centres, symmetric about the shaft
static const float DL_TYRE_W = 24, DL_TYRE_L = 76;
static const float DL_STEER = 25; // front tyres, degrees, top leaning right
static lv_coord_t dl(float v) { return (lv_coord_t)lroundf(v * DL_S); }
/** Sketch point -> box point (drawing centred horizontally in the box). */
static lv_point_t dlPoint(float x, float y) {
lv_point_t pt;
pt.x = (DL_BOX_W - dl(DL_W)) / 2 + dl(x);
pt.y = dl(y) + 2;
return pt;
}
struct TyreView {
lv_obj_t* outline;
lv_obj_t* fill; // shown only while the axle is locked
};
struct AxleView {
lv_obj_t* axle;
TyreView tyre[2];
lv_obj_t* cross[2]; // the X on the diff, shown only while locked
};
static AxleView g_front_axle, g_rear_axle;
// lv_line keeps a pointer to its points: they must outlive the objects.
static lv_point_t g_pts_shaft[2];
static lv_point_t g_pts_axle[2][2]; // [front, rear][end]
static lv_point_t g_pts_tyre[2][2][5]; // [front, rear][left, right] closed outline
static lv_point_t g_pts_fill[2][2][2]; // [front, rear][left, right] centre line of the fill
static lv_point_t g_pts_cross[2][2][2]; // [front, rear][stroke][end]
static lv_obj_t* makeLine(lv_obj_t* parent, lv_point_t* pts, uint16_t n, lv_coord_t width, bool rounded) {
lv_obj_t* l = lv_line_create(parent);
lv_line_set_points(l, pts, n);
lv_obj_set_style_line_width(l, width, 0);
lv_obj_set_style_line_rounded(l, rounded, 0);
lv_obj_set_style_line_color(l, COL_MUTED, 0);
lv_obj_clear_flag(l, LV_OBJ_FLAG_CLICKABLE);
return l;
}
/**
* A tyre centred on (cx, cy), `steer` degrees from straight (top leaning right).
* The fill is ONE line as wide as the tyre with square ends, which is exactly
* the filled rectangle, rotated or not (LVGL 8 cannot rotate a plain box).
*/
static TyreView makeTyre(lv_obj_t* parent, lv_point_t* outline, lv_point_t* fill,
float cx, float cy, float steer) {
const float a = DL_TYRE_W / 2, b = DL_TYRE_L / 2, t = steer * (float)M_PI / 180.0f;
const float ux = sinf(t), uy = -cosf(t); // long axis, towards the top
const float vx = cosf(t), vy = sinf(t); // short axis
const float k[4][2] = {{b, a}, {b, -a}, {-b, -a}, {-b, a}};
for (int i = 0; i < 4; i++) {
outline[i] = dlPoint(cx + k[i][0] * ux + k[i][1] * vx, cy + k[i][0] * uy + k[i][1] * vy);
}
outline[4] = outline[0];
fill[0] = dlPoint(cx + b * ux, cy + b * uy);
fill[1] = dlPoint(cx - b * ux, cy - b * uy);
TyreView v;
v.fill = makeLine(parent, fill, 2, dl(DL_TYRE_W), false);
lv_obj_add_flag(v.fill, LV_OBJ_FLAG_HIDDEN);
v.outline = makeLine(parent, outline, 5, 2, true); // 2 px rounded joins read as square corners
return v;
}
/** The X on a diff at (cx, cy); idx 0 = front, 1 = rear. */
static void diffCross(lv_obj_t* parent, AxleView& a, int idx, float cx, float cy) {
const float r = 16;
g_pts_cross[idx][0][0] = dlPoint(cx - r, cy - r); g_pts_cross[idx][0][1] = dlPoint(cx + r, cy + r);
g_pts_cross[idx][1][0] = dlPoint(cx + r, cy - r); g_pts_cross[idx][1][1] = dlPoint(cx - r, cy + r);
for (int k = 0; k < 2; k++) {
a.cross[k] = makeLine(parent, g_pts_cross[idx][k], 2, 4, true);
lv_obj_add_flag(a.cross[k], LV_OBJ_FLAG_HIDDEN);
}
}
/** Line colour, written only on change. */
static void setPartColour(lv_obj_t* o, lv_color_t c) {
if (lv_color_to32(lv_obj_get_style_line_color(o, 0)) != lv_color_to32(c)) {
lv_obj_set_style_line_color(o, c, 0);
}
}
static void setHidden(lv_obj_t* o, bool hidden) {
if (lv_obj_has_flag(o, LV_OBJ_FLAG_HIDDEN) == hidden) return;
if (hidden) lv_obj_add_flag(o, LV_OBJ_FLAG_HIDDEN);
else lv_obj_clear_flag(o, LV_OBJ_FLAG_HIDDEN);
}
static void setAxle(AxleView& a, bool locked, lv_color_t colour) {
lv_color_t c = locked ? colour : COL_MUTED;
setPartColour(a.axle, c);
for (int i = 0; i < 2; i++) {
setPartColour(a.tyre[i].outline, c);
setPartColour(a.tyre[i].fill, c);
setHidden(a.tyre[i].fill, !locked);
setPartColour(a.cross[i], c);
setHidden(a.cross[i], !locked);
}
}
/**
* @brief Diff locks, from the isolated inputs (not CAN - shown with CAN off too).
* Locked axle = amber. The front can only lock after the rear, so FRONT
* without REAR is a wiring/switch fault and shows red.
*/
static void refreshDiffLocks() {
bool on = DiffLocks::isEnabled();
setHidden(g_diff_box, !on);
if (!on) return;
if (!DiffLocks::isValid()) {
setAxle(g_front_axle, false, COL_MUTED);
setAxle(g_rear_axle, false, COL_MUTED);
return;
}
bool rear = DiffLocks::rearLocked(), front = DiffLocks::frontLocked();
setAxle(g_rear_axle, rear, COL_AMBER);
setAxle(g_front_axle, front, rear ? COL_AMBER : COL_ALERT); // no caption: the drawing says it all (user)
}
/**
@@ -137,22 +315,31 @@ static lv_obj_t* makeStat(lv_obj_t* parent, const char* title,
}
/**
* @brief Gesture handler on OUR screen: swipe LEFT opens Settings (SquareLine),
* swipe RIGHT continues to the Gauge Tuning screen.
* @brief Gesture handler: swipe LEFT opens Settings, swipe RIGHT the Gauge
* Tuning screen (both hand-coded, instant switches).
*/
static void onScreenGesture(lv_event_t* e) {
if (lv_event_get_code(e) != LV_EVENT_GESTURE) return;
lv_dir_t dir = lv_indev_get_gesture_dir(lv_indev_get_act());
if (dir == LV_DIR_LEFT) {
lv_indev_wait_release(lv_indev_get_act());
_ui_screen_change(&ui_Settings_Screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0,
&ui_Settings_Screen_screen_init);
SettingsScreen::show();
} else if (dir == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act());
TuningScreen::show();
}
}
static void onEngineData(lv_event_t* e) {
(void)e;
EngineScreen::show();
}
static void onSport(lv_event_t* e) {
(void)e;
SportScreen::show();
}
/**
* @brief Build the screen. Idempotent — returns immediately if already built.
*/
@@ -170,20 +357,59 @@ static void build() {
lv_obj_set_size(bar, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(bar, LV_FLEX_FLOW_ROW);
lv_obj_set_style_pad_column(bar, 8, 0);
lv_obj_align(bar, LV_ALIGN_TOP_LEFT, 24, 18);
// y 60: the top 56 px belong to the StatusOverlay (alert banner centre, Wi-Fi chip right)
lv_obj_align(bar, LV_ALIGN_TOP_LEFT, 24, 60);
lv_obj_clear_flag(bar, LV_OBJ_FLAG_SCROLLABLE);
g_ign_chip = makeChip(bar, "IGN --");
g_eng_chip = makeChip(bar, "ENG --");
g_clutch_chip = makeChip(bar, "CLUTCH --");
g_cool_chip = makeChip(bar, "COOLING --");
// Gear mismatch: the ring and the gear letter turn red, and the overlay banner says so.
g_mismatch_lbl = lv_label_create(g_screen);
lv_label_set_text(g_mismatch_lbl, LV_SYMBOL_WARNING " GEAR MISMATCH");
lv_obj_set_style_text_font(g_mismatch_lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_mismatch_lbl, COL_WARN, 0);
lv_obj_align(g_mismatch_lbl, LV_ALIGN_TOP_RIGHT, -24, 24);
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
// ---- diff locks, top-right under the overlay's Wi-Fi chip (hidden until enabled).
// Box bottom stays above the GEARBOX OIL stat (its top is at y ~227).
g_diff_box = lv_obj_create(g_screen);
lv_obj_remove_style_all(g_diff_box);
lv_obj_set_size(g_diff_box, DL_BOX_W, dl(DL_REAR_Y + DL_TYRE_L / 2) + 6); // drawing only, no caption
lv_obj_align(g_diff_box, LV_ALIGN_TOP_RIGHT, -16, 60);
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_clear_flag(g_diff_box, LV_OBJ_FLAG_CLICKABLE); // swipes pass through to the screen
lv_obj_add_flag(g_diff_box, LV_OBJ_FLAG_HIDDEN);
g_pts_shaft[0] = dlPoint(DL_SHAFT_X, DL_FRONT_Y);
g_pts_shaft[1] = dlPoint(DL_SHAFT_X, DL_REAR_Y);
makeLine(g_diff_box, g_pts_shaft, 2, 3, true);
// axles run between the tyres' inner edges (a steered tyre's edge sits a little further out)
const float half = DL_TYRE_W / 2;
const float half_steered = half / cosf(DL_STEER * (float)M_PI / 180.0f);
g_pts_axle[0][0] = dlPoint(DL_TRACK_L + half_steered, DL_FRONT_Y);
g_pts_axle[0][1] = dlPoint(DL_TRACK_R - half_steered, DL_FRONT_Y);
g_pts_axle[1][0] = dlPoint(DL_TRACK_L + half, DL_REAR_Y);
g_pts_axle[1][1] = dlPoint(DL_TRACK_R - half, DL_REAR_Y);
g_front_axle.axle = makeLine(g_diff_box, g_pts_axle[0], 2, 3, true);
g_rear_axle.axle = makeLine(g_diff_box, g_pts_axle[1], 2, 3, true);
g_front_axle.tyre[0] = makeTyre(g_diff_box, g_pts_tyre[0][0], g_pts_fill[0][0], DL_TRACK_L, DL_FRONT_Y, DL_STEER);
g_front_axle.tyre[1] = makeTyre(g_diff_box, g_pts_tyre[0][1], g_pts_fill[0][1], DL_TRACK_R, DL_FRONT_Y, DL_STEER);
g_rear_axle.tyre[0] = makeTyre(g_diff_box, g_pts_tyre[1][0], g_pts_fill[1][0], DL_TRACK_L, DL_REAR_Y, 0);
g_rear_axle.tyre[1] = makeTyre(g_diff_box, g_pts_tyre[1][1], g_pts_fill[1][1], DL_TRACK_R, DL_REAR_Y, 0);
diffCross(g_diff_box, g_front_axle, 0, DL_SHAFT_X, DL_FRONT_Y);
diffCross(g_diff_box, g_rear_axle, 1, DL_SHAFT_X, DL_REAR_Y);
// Live DDE values (rail, boost, charge-air temp, battery). A button, not a
// swipe, so polling the engine ECU never starts by accident. Below the
// overlay band (y 60, like the chips), left of the diff-lock drawing.
lv_obj_t* eng = UiKit::button(g_screen, LV_SYMBOL_CHARGE " Engine data", 200, 56,
UiKit::BTN_SECONDARY, onEngineData, NULL);
lv_obj_align(eng, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16, 60);
// Sport displays (torque + power gauges), left of the Engine data button.
lv_obj_t* sport = UiKit::button(g_screen, "Sport", 150, 56,
UiKit::BTN_SECONDARY, onSport, NULL);
lv_obj_align(sport, LV_ALIGN_TOP_RIGHT, -16 - DL_BOX_W - 16 - 200 - 12, 60);
// ---- gear hero -------------------------------------------------------
g_gear_ring = lv_obj_create(g_screen);
@@ -206,6 +432,8 @@ static void build() {
LV_ALIGN_LEFT_MID, 110, -40);
g_gearbox_lbl = makeStat(g_screen, "GEARBOX OIL", &lv_font_montserrat_40,
LV_ALIGN_RIGHT_MID, -110, -40);
g_coolant_title = lv_obj_get_child(lv_obj_get_parent(g_coolant_lbl), 0);
g_gearbox_title = lv_obj_get_child(lv_obj_get_parent(g_gearbox_lbl), 0);
// ---- RPM bar ---------------------------------------------------------
lv_obj_t* rpm_title = lv_label_create(g_screen);
@@ -230,23 +458,27 @@ static void build() {
lv_obj_set_style_text_color(g_rpm_lbl, COL_TEXT, 0);
lv_obj_align(g_rpm_lbl, LV_ALIGN_CENTER, 330, 108);
// ---- bottom row: torque | pedal | output shaft -----------------------
// ---- bottom row: torque | pedal | output shaft | speed ---------------
// Turbine speed is intentionally NOT shown: it's a diagnostic (engagement
// proof), not a driver number. Still decoded in the driver.
g_torque_lbl = makeStat(g_screen, "TORQUE (Nm)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, -340, -34);
LV_ALIGN_BOTTOM_MID, -390, -34);
g_pedal_lbl = makeStat(g_screen, "PEDAL (%)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, 0, -34);
LV_ALIGN_BOTTOM_MID, -130, -34);
// Output shaft in rpm via a PROVISIONAL factor (one Launch point). The label
// carries "~" so the screen doesn't present an unlocked scaling as exact.
g_shaft_lbl = makeStat(g_screen, "OUTPUT (~rpm)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, 340, -34);
LV_ALIGN_BOTTOM_MID, 130, -34);
// Road speed = output shaft / final drive x tyre circumference (Settings >
// Vehicle). Inherits the "~" of the shaft factor.
g_speed_lbl = makeStat(g_screen, "SPEED (~km/h)", &lv_font_montserrat_30,
LV_ALIGN_BOTTOM_MID, 390, -34);
lv_obj_t* hint = lv_label_create(g_screen);
lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: Settings | swipe right: Gauge tuning " LV_SYMBOL_RIGHT);
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(hint, COL_MUTED, 0);
lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -14);
lv_obj_align(hint, LV_ALIGN_BOTTOM_LEFT, 24, -8);
ESP_LOGI("Driveline", "Driveline screen built");
}
@@ -257,7 +489,7 @@ static void build() {
void show() {
build();
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
}
void tick() {
@@ -270,18 +502,20 @@ void tick() {
if (millis() - last_refresh < 100) return;
last_refresh = millis();
bool can_up = CANDriver::isActive();
bool can_up = CANDriver::isActive() || BenchSim::isActive(); // `sim` console counts as a live bus
driveline_t dl = CANDriver::getDriveline();
// Snapshot the shared struct under its own mutex, briefly.
uint8_t gear = GEAR_UNKNOWN;
int16_t coolant = 0, gearbox = 0;
uint8_t flags = 0;
uint16_t alerts = 0;
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
gear = UARTManager::g_automotive_data.gear_lever;
coolant = UARTManager::g_automotive_data.coolant_temp;
gearbox = UARTManager::g_automotive_data.gearbox_oil_temp;
flags = UARTManager::g_automotive_data.valid_flags;
alerts = UARTManager::g_automotive_data.alerts;
xSemaphoreGive(UARTManager::g_data_mutex);
} else {
return; // couldn't read; leave the last frame on screen
@@ -291,20 +525,27 @@ void tick() {
(void)gear; // gear now comes from the driveline pieces, not the UART enum
lvgl_port_lock(-1);
refreshDiffLocks(); // hard-wired inputs: live even with CAN or the key off
// Blank every readout when there's nothing live to show: CAN off, or the key
// is off. The user asked for a full reset on ignition-off so the screen goes
// quiet with the car rather than freezing the last frame. 0x3B4 sends its
// ignition nibble on-change, so this reset is effectively instant.
// ignition nibble on-change, and the 0x1D2 lever fallback (buses without
// 0x3B4) flips within one 200 ms frame, so this reset is effectively instant.
if (!can_up || !dl.ignition_on) {
lv_label_set_text(g_gear_lbl, "--");
lv_label_set_text(g_coolant_lbl, "--");
lv_label_set_text(g_gearbox_lbl, "--");
lv_label_set_text(g_rpm_lbl, "----");
lv_label_set_text(g_torque_lbl, "--");
lv_label_set_text(g_pedal_lbl, "--");
lv_label_set_text(g_shaft_lbl, "--");
setText(g_gear_lbl, "--");
setText(g_coolant_lbl, "--");
setText(g_gearbox_lbl, "--");
setText(g_rpm_lbl, "----");
setText(g_torque_lbl, "--");
setText(g_pedal_lbl, "--");
setText(g_shaft_lbl, "--");
setText(g_speed_lbl, "--");
lv_bar_set_value(g_rpm_bar, 0, LV_ANIM_OFF);
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
setRing(COL_ACCENT);
setColour(g_gear_lbl, COL_TEXT);
setColour(g_coolant_lbl, COL_TEXT); setColour(g_coolant_title, COL_MUTED);
setColour(g_gearbox_lbl, COL_TEXT); setColour(g_gearbox_title, COL_MUTED);
// Leave the ignition chip telling the truth; mute the rest, since their
// values are meaningless with the key out (or absent with CAN off).
if (!can_up) {
@@ -323,41 +564,63 @@ void tick() {
// ---- gear (composed: P/R/N, or D/S/M + engaged number) ---------------
if ((gear_position_t)dl.lever != GEAR_UNKNOWN) {
composeGear(dl, buf, sizeof(buf));
lv_label_set_text(g_gear_lbl, buf);
setText(g_gear_lbl, buf);
} else {
lv_label_set_text(g_gear_lbl, "--");
setText(g_gear_lbl, "--");
}
// ---- temperatures (only when the signal is real) ---------------------
if (flags & VALID_FLAG_COOLANT_TEMP) {
snprintf(buf, sizeof(buf), "%d.%d°C", coolant / 10, abs(coolant % 10));
lv_label_set_text(g_coolant_lbl, buf);
setText(g_coolant_lbl, buf);
}
if (flags & VALID_FLAG_GEARBOX_TEMP) {
snprintf(buf, sizeof(buf), "%d.%d°C", gearbox / 10, abs(gearbox % 10));
lv_label_set_text(g_gearbox_lbl, buf);
setText(g_gearbox_lbl, buf);
}
// ---- thresholds crossed: the value AND its title go red (amber while the
// box only asks for cooling); the overlay banner blinks on top of it all.
if (!(flags & VALID_FLAG_ALERTS)) alerts = 0;
bool cool_hot = (alerts & ALERT_COOLANT_HOT) != 0;
bool gb_hot = (alerts & ALERT_GEARBOX_HOT) != 0;
bool gb_cool = (alerts & ALERT_GEARBOX_COOLING) != 0;
setColour(g_coolant_lbl, cool_hot ? COL_ALERT : COL_TEXT);
setColour(g_coolant_title, cool_hot ? COL_ALERT : COL_MUTED);
setColour(g_gearbox_lbl, gb_hot ? COL_ALERT : gb_cool ? COL_AMBER : COL_TEXT);
setColour(g_gearbox_title, gb_hot ? COL_ALERT : gb_cool ? COL_AMBER : COL_MUTED);
// ---- speeds ----------------------------------------------------------
snprintf(buf, sizeof(buf), "%u", dl.engine_rpm);
lv_label_set_text(g_rpm_lbl, buf);
setText(g_rpm_lbl, buf);
lv_bar_set_value(g_rpm_bar, dl.engine_rpm > RPM_MAX ? RPM_MAX : dl.engine_rpm, LV_ANIM_OFF);
// Torque is signed (negative under overrun/braking); one decimal, matching
// the 0.5 Nm resolution of the field.
snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10));
lv_label_set_text(g_torque_lbl, buf);
// the 0.5 Nm resolution of the field. Engine off: the field holds a junk
// value (812 Nm on Patrol 2, 245 on Patrol 1), so show nothing.
if (dl.engine_run_state == ENGINE_RUN_RUNNING) {
snprintf(buf, sizeof(buf), "%d.%d", dl.engine_torque_x10 / 10, abs(dl.engine_torque_x10 % 10));
} else {
snprintf(buf, sizeof(buf), "--");
}
setText(g_torque_lbl, buf);
snprintf(buf, sizeof(buf), "%u", dl.pedal_percent);
lv_label_set_text(g_pedal_lbl, buf);
setText(g_pedal_lbl, buf);
// Provisional rpm from the single-point Launch factor (see automotive_data.h).
snprintf(buf, sizeof(buf), "%u", can_output_shaft_rpm(dl.output_shaft_raw));
lv_label_set_text(g_shaft_lbl, buf);
setText(g_shaft_lbl, buf);
// Road speed from the same shaft reading and the Settings > Vehicle numbers.
uint16_t kmh_x10 = Vehicle::speedKmhX10(dl.output_shaft_raw);
snprintf(buf, sizeof(buf), "%u", kmh_x10 / 10);
setText(g_speed_lbl, buf);
// ---- status chips ----------------------------------------------------
setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF",
dl.ignition_on ? COL_OK : COL_MUTED);
if (BenchSim::isActive()) setChip(g_ign_chip, "IGN SIM", COL_AMBER); // bench numbers, not the car's
else setChip(g_ign_chip, dl.ignition_on ? "IGN ON" : "IGN OFF",
dl.ignition_on ? COL_OK : COL_MUTED);
switch (dl.engine_run_state) {
case ENGINE_RUN_RUNNING: setChip(g_eng_chip, "ENG RUN", COL_OK); break;
@@ -380,19 +643,11 @@ void tick() {
default: setChip(g_cool_chip, "COOLING ?", COL_MUTED); break;
}
if (dl.gear_mismatch) {
lv_obj_clear_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(g_mismatch_lbl, LV_OBJ_FLAG_HIDDEN);
}
// Gear mismatch: the hero ring and the gear letter turn red.
setRing(dl.gear_mismatch ? COL_ALERT : COL_ACCENT);
setColour(g_gear_lbl, dl.gear_mismatch ? COL_ALERT : COL_TEXT);
lvgl_port_unlock();
}
} // namespace DrivelineScreen
// C entry point used by the SquareLine-generated Settings screen's back gesture.
// Runs inside an LVGL event handler, so the LVGL lock is already held.
extern "C" void app_show_driveline(void) {
DrivelineScreen::show();
}
+2 -10
View File
@@ -5,16 +5,8 @@
* the swap's bus: gear (hero), coolant, gearbox oil temp, engine RPM, turbine
* speed and output shaft, plus ignition / engine / clutch / mismatch status.
*
* WHY THIS IS NOT A SQUARELINE SCREEN
* SquareLine Studio owns include/ui/ and overwrites it on every export. Editing
* generated files loses the edit — that is exactly how the CAN toggle's event
* handler went missing. This screen lives entirely in src/, which SquareLine
* never touches, so it cannot be clobbered. Since 2026-09-21 it IS the boot
* screen: the SquareLine Home screen was removed, and the generated Settings
* screen's back gesture calls app_show_driveline() (defined at the bottom of
* driveline_screen.cpp) to return here.
*
* Navigation: swipe LEFT -> Settings (SquareLine), swipe RIGHT -> Gauge Tuning.
* The boot screen. Navigation: swipe LEFT -> Settings, swipe RIGHT -> Gauge
* Tuning (both hand-coded, like this one).
*
* Signals deliberately NOT shown: engine oil temp (no sensor on this M57N —
* 0x1D0 byte 1 is permanently 0xFF) and battery voltage (0x3B4 publishes the
+382
View File
@@ -0,0 +1,382 @@
/*
* ECU Identification Module Implementation - see ecu_ident.h
*
* Threading: onIdent() runs in the CAN task and only parks the payload;
* everything else (sequencing, NVS, console) runs in loop() via tick().
*/
#include "ecu_ident.h"
#include "diag_probe.h"
#include "bench_sim.h"
#include "serial_lock.h"
#include "drivers/can_driver.h"
#include <Preferences.h>
namespace EcuIdent {
// ============================================================================
// CONSTANTS
// ============================================================================
static const char* NVS_NAMESPACE = "settings";
static const char* NVS_KEY_86 = "ecu_id86";
static const char* NVS_KEY_80 = "ecu_id80";
static const size_t BLOCK_MAX = 96;
static const uint8_t SUB_86 = 0x86, SUB_80 = 0x80;
static const uint8_t ATTEMPTS_PER_SUB = 3; // per boot, while nothing is stored
static const uint32_t RETRY_GAP_MS = 10000; // between attempts
static const uint32_t SETTLE_MS = 5000; // ignition on this long before the first ask
static const uint32_t ANSWER_WAIT_MS = 1500; // DiagProbe's own timeout is 500 ms + linger
// ============================================================================
// STATE
// ============================================================================
typedef struct {
uint8_t sub;
uint8_t len; // 0 = empty
uint8_t raw[BLOCK_MAX];
} block_t;
static block_t g_blk[2] = {{SUB_86, 0, {0}}, {SUB_80, 0, {0}}}; // [0] = 1A 86, [1] = 1A 80
// CAN task -> loop handoff (single writer, single reader)
static volatile bool g_pending = false;
static block_t g_pending_blk;
static bool g_pending_ours = false;
// one-shot read sequencing
static bool g_read_session = false; // true while this boot is allowed to transmit
static uint8_t g_attempts[2] = {0, 0};
static uint32_t g_last_try_ms = 0;
static uint32_t g_ign_since_ms = 0; // first tick with ignition on (0 = not yet)
static bool g_waiting = false; // a request of ours is out
static bool g_gave_up_printed = false;
// passive check
static bool g_changed = false;
static char g_bus_part[12] = ""; // part number of the differing 1A 80 block seen on the bus
// ============================================================================
// HELPERS
// ============================================================================
static void print(const char* fmt, ...) {
char buf[200];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static block_t* blockFor(uint8_t sub) {
if (sub == SUB_86) return &g_blk[0];
if (sub == SUB_80) return &g_blk[1];
return NULL;
}
static block_t* primary() {
if (g_blk[0].len) return &g_blk[0];
if (g_blk[1].len) return &g_blk[1];
return NULL;
}
/** BCD bytes -> decimal string without leading zeros ("" if any nibble > 9). */
static bool bcd(const uint8_t* p, size_t n, char* out, size_t out_sz) {
size_t w = 0;
bool started = false;
for (size_t i = 0; i < n; i++) {
uint8_t hi = p[i] >> 4, lo = p[i] & 0x0F;
if (hi > 9 || lo > 9) { out[0] = 0; return false; }
if (started || hi) { if (w + 1 < out_sz) out[w++] = (char)('0' + hi); started = true; }
if (started || lo) { if (w + 1 < out_sz) out[w++] = (char)('0' + lo); started = true; }
}
if (!started && w + 1 < out_sz) out[w++] = '0';
out[w] = 0;
return true;
}
/** The part number this block carries (observed offsets), "" if it does not fit. */
static void partOf(const block_t* b, char* out, size_t out_sz) {
out[0] = 0;
if (!b || !b->len) return;
// 1A 86: 5A 86 "@B892524 " 06 03 07 00 00 [07 79 97 64] ... (Patrol 1, 2026-09-23)
// 1A 80: 5A 80 00 00 [07 79 49 04] 10 00 00 10 35 39 20 04 01 21 ... (Patrol 2, 2026-10-18)
if (b->sub == SUB_86 && b->len >= 20) bcd(b->raw + 16, 4, out, out_sz);
else if (b->sub == SUB_80 && b->len >= 8) bcd(b->raw + 4, 4, out, out_sz);
}
/** "20YY-MM-DD" from the block's BCD date, "" if absent or implausible. */
static void dateOf(const block_t* b, char* out, size_t out_sz) {
out[0] = 0;
if (!b || !b->len) return;
const uint8_t* d = NULL;
if (b->sub == SUB_86 && b->len >= 14) d = b->raw + 11; // after the 9-char "@B892524 "
else if (b->sub == SUB_80 && b->len >= 18) d = b->raw + 15;
if (!d) return;
char y[4], m[4], dd[4];
if (!bcd(d, 1, y, sizeof(y)) || !bcd(d + 1, 1, m, sizeof(m)) || !bcd(d + 2, 1, dd, sizeof(dd))) return;
int mi = atoi(m), di = atoi(dd);
if (mi < 1 || mi > 12 || di < 1 || di > 31) return;
snprintf(out, out_sz, "20%02d-%02d-%02d", atoi(y), mi, di);
}
/** The VIN prefix the 1A 86 block ends with ("" otherwise). */
static void vinOf(const block_t* b, char* out, size_t out_sz) {
out[0] = 0;
if (!b || b->sub != SUB_86 || b->len < 63) return;
size_t w = 0;
for (size_t i = 53; i < 63 && w + 1 < out_sz; i++) {
char c = (char)b->raw[i];
if (c < 0x20 || c >= 0x7F) { out[0] = 0; return; }
out[w++] = c;
}
out[w] = 0;
}
static void save(const block_t* b) {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, false);
const char* key = (b->sub == SUB_86) ? NVS_KEY_86 : NVS_KEY_80;
if (b->len) prefs.putBytes(key, b->raw, b->len);
else prefs.remove(key);
prefs.end();
}
static void load(block_t* b) {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, true);
const char* key = (b->sub == SUB_86) ? NVS_KEY_86 : NVS_KEY_80;
size_t n = prefs.getBytesLength(key);
if (n > 0 && n <= BLOCK_MAX) {
prefs.getBytes(key, b->raw, n);
b->len = (uint8_t)n;
} else {
b->len = 0;
}
prefs.end();
}
static void describeBlock(const block_t* b, char* buf, size_t n) {
char part[12], date[12];
partOf(b, part, sizeof(part));
dateOf(b, date, sizeof(date));
if (part[0] && date[0]) snprintf(buf, n, "DDE %s - %s", part, date);
else if (part[0]) snprintf(buf, n, "DDE %s", part);
else snprintf(buf, n, "DDE ident 1A %02X, %u bytes", b->sub, b->len);
if (b->sub == SUB_80 && !g_blk[0].len) {
size_t l = strlen(buf);
snprintf(buf + l, n - l, " (1A 80)");
}
}
/** CAN task: park the payload for tick(). A second one before it is taken is dropped. */
static void onIdent(uint8_t sub, const uint8_t* payload, size_t n, bool ours) {
if (g_pending || n < 2 || n > BLOCK_MAX) return;
if (sub != SUB_86 && sub != SUB_80) return;
g_pending_blk.sub = sub;
g_pending_blk.len = (uint8_t)n;
memcpy(g_pending_blk.raw, payload, n);
g_pending_ours = ours;
g_pending = true;
}
/** loop(): a block arrived - store it, or compare it with what is stored. */
static void takePending() {
block_t in = g_pending_blk;
bool ours = g_pending_ours;
g_pending = false;
g_waiting = false;
block_t* b = blockFor(in.sub);
if (!b) return;
char desc[64];
if (b->len == 0) {
*b = in;
save(b);
describeBlock(b, desc, sizeof(desc));
print("[ecu] stored 1A %02X (%u bytes, %s): %s", in.sub, in.len, ours ? "our read" : "seen on the bus", desc);
if (in.sub == SUB_80) { g_changed = false; g_bus_part[0] = 0; }
return;
}
bool same = (b->len == in.len) && memcmp(b->raw, in.raw, in.len) == 0;
if (in.sub == SUB_80) {
if (same) {
if (g_changed) print("[ecu] 1A 80 on the bus matches the stored block again");
g_changed = false;
g_bus_part[0] = 0;
} else {
char stored[12];
partOf(&in, g_bus_part, sizeof(g_bus_part));
partOf(b, stored, sizeof(stored));
if (!g_changed) {
print("[ecu] ECU CHANGED? the 1A 80 block on the bus (%s) differs from the stored one (%s) - `ecu forget` or Re-read ECU",
g_bus_part[0] ? g_bus_part : "?", stored[0] ? stored : "?");
}
g_changed = true;
}
} else if (!same) {
print("[ecu] note: a 1A 86 block on the bus differs from the stored one");
}
}
/** loop(): send the next identification request when every condition holds. */
static void readTick() {
if (!g_read_session || g_waiting) return;
if (g_blk[0].len && g_blk[1].len) { g_read_session = false; return; } // both in hand
// the sub-function still missing with attempts left: 86 first, then 80
int idx = -1;
for (int i = 0; i < 2; i++) {
if (!g_blk[i].len && g_attempts[i] < ATTEMPTS_PER_SUB) { idx = i; break; }
}
if (idx < 0) {
g_read_session = false;
if (!known() && !g_gave_up_printed) {
g_gave_up_printed = true;
print("[ecu] no identification answer after %u tries - UNKNOWN ECU, will try again next boot",
(unsigned)(2 * ATTEMPTS_PER_SUB));
}
return;
}
uint32_t now = millis();
if (!CANDriver::isActive() || BenchSim::isActive()) { g_ign_since_ms = 0; return; }
driveline_t dl = CANDriver::getDriveline();
if (!dl.ignition_on) { g_ign_since_ms = 0; return; }
if (g_ign_since_ms == 0) g_ign_since_ms = now;
if (now - g_ign_since_ms < SETTLE_MS) return;
if (g_last_try_ms != 0 && now - g_last_try_ms < RETRY_GAP_MS) return;
if (!DiagProbe::canSendNow()) return;
g_attempts[idx]++;
g_last_try_ms = now;
print("[ecu] reading the DDE identification (1A %02X, try %u of %u)", g_blk[idx].sub,
g_attempts[idx], ATTEMPTS_PER_SUB);
if (DiagProbe::requestIdent(g_blk[idx].sub)) g_waiting = true;
}
// ============================================================================
// PUBLIC API
// ============================================================================
void init() {
load(&g_blk[0]);
load(&g_blk[1]);
DiagProbe::setIdentHandler(onIdent);
g_read_session = !known(); // stored = never ask again
char desc[64];
describe(desc, sizeof(desc));
print("[ecu] %s%s", desc, g_read_session ? " - will read it once the bus is up with the key on" : "");
}
void tick() {
if (g_pending) takePending();
if (g_waiting && millis() - g_last_try_ms > ANSWER_WAIT_MS) g_waiting = false; // no answer: next try later
readTick();
}
bool known() { return g_blk[0].len != 0 || g_blk[1].len != 0; }
bool changed() { return g_changed; }
void describe(char* buf, size_t n) {
if (g_changed) {
char stored[12];
partOf(&g_blk[1], stored, sizeof(stored));
snprintf(buf, n, "ECU CHANGED? bus %s, stored %s", g_bus_part[0] ? g_bus_part : "?", stored[0] ? stored : "?");
return;
}
block_t* p = primary();
if (!p) { snprintf(buf, n, "UNKNOWN ECU"); return; }
describeBlock(p, buf, n);
}
bool hasPart(const char* part) {
if (!part || !part[0]) return false;
if (g_changed) return strcmp(g_bus_part, part) == 0; // the unit actually on the bus
char p[12];
for (int i = 0; i < 2; i++) {
if (!g_blk[i].len) continue;
partOf(&g_blk[i], p, sizeof(p));
if (p[0] && strcmp(p, part) == 0) return true;
}
return false;
}
void forget() {
for (int i = 0; i < 2; i++) {
g_blk[i].len = 0;
save(&g_blk[i]);
g_attempts[i] = 0;
}
g_changed = false;
g_bus_part[0] = 0;
g_gave_up_printed = false;
g_last_try_ms = 0;
g_waiting = false;
g_read_session = true;
print("[ecu] forgotten - UNKNOWN ECU; reading again once the bus is up with the key on");
}
static void show() {
char desc[64];
describe(desc, sizeof(desc));
print("[ecu] %s", desc);
for (int i = 0; i < 2; i++) {
block_t* b = &g_blk[i];
if (!b->len) {
print("[ecu] 1A %02X: not stored%s", b->sub,
g_read_session ? (g_attempts[i] ? " (tried, no answer yet)" : " (will ask)") : "");
continue;
}
char part[12], date[12], vin[12];
partOf(b, part, sizeof(part));
dateOf(b, date, sizeof(date));
vinOf(b, vin, sizeof(vin));
print("[ecu] 1A %02X: %u bytes, part %s, date %s%s%s", b->sub, b->len,
part[0] ? part : "?", date[0] ? date : "?", vin[0] ? ", VIN prefix " : "", vin);
}
print("[ecu] %s", g_read_session ? "read pending: asks once CAN is on, ignition on 5 s, no scan tool"
: "stored: never asked again (`ecu forget` to re-read)");
}
static void dump() {
for (int i = 0; i < 2; i++) {
block_t* b = &g_blk[i];
if (!b->len) { print("[ecu] 1A %02X: empty", b->sub); continue; }
print("[ecu] 1A %02X (%u bytes):", b->sub, b->len);
for (size_t o = 0; o < b->len; o += 16) {
char hx[3 * 16 + 1];
size_t w = 0, k = (b->len - o < 16) ? (b->len - o) : 16;
for (size_t j = 0; j < k; j++) w += snprintf(hx + w, sizeof(hx) - w, "%02X ", b->raw[o + j]);
if (w) hx[w - 1] = 0;
char as[17];
for (size_t j = 0; j < k; j++) as[j] = (b->raw[o + j] >= 0x20 && b->raw[o + j] < 0x7F) ? (char)b->raw[o + j] : '.';
as[k] = 0;
print("[ecu] +%03u %-48s |%s|", (unsigned)o, hx, as);
}
}
}
static void help() {
print("ecu show which engine ECU this board remembers (read once, never re-asked)");
print("ecu dump the stored identification blocks in hex");
print("ecu forget drop them - UNKNOWN ECU until read again (board moved to another car)");
}
bool handleCommand(const char* line) {
if (strncmp(line, "ecu", 3) != 0 || (line[3] != 0 && line[3] != ' ')) return false;
const char* arg = line + 3;
while (*arg == ' ') arg++;
if (*arg == 0 || !strcmp(arg, "show")) { show(); return true; }
if (!strcmp(arg, "dump")) { dump(); return true; }
if (!strcmp(arg, "forget")) { forget(); return true; }
help();
return true;
}
} // namespace EcuIdent
+81
View File
@@ -0,0 +1,81 @@
/*
* ECU Identification Module
*
* Which engine ECU (DDE) is this board bolted to? Read ONCE and remembered.
*
* Two Patrols with "the same" M57N DDE turned out to carry different units
* (part number 7796678 / 2006 vs 7794904 / 2004, captures 2026-10-18), and a
* third setup is coming. The identity is a LABEL - every broadcast frame the
* firmware decodes was identical on both - so it is stored for the record
* (captures, wiki, Settings > Vehicle) and no broadcast decoding depends on it.
* The one exception is the Engine data screen: the KWP `2C` live-data
* identifiers are per DDE software (hasPart() selects its profile).
*
* Rules (user, 2026-10-18):
* - While nothing is stored: read the identification the first time it is
* possible (CAN on, ignition on for a few seconds, no scan tool on the bus,
* not the bench simulation), a few spaced attempts per boot. Until then the
* screen says UNKNOWN ECU.
* - Once stored: NEVER ask again. A board moved to another car keeps the old
* answer until "Re-read ECU" (Settings > Vehicle) or `ecu forget`.
* - Free passive check: a connected Launch re-reads `1A 80` every cycle, and
* we see the DDE's reply without transmitting. If it differs from the stored
* `1A 80` block the screen says ECU CHANGED?.
*
* Two KWP identification blocks are kept, each as its raw payload (NVS blobs
* `ecu_id86`, `ecu_id80` in the "settings" namespace):
* `1A 86` - 65 bytes on Patrol 1 (verified 2026-09-23 from this board): ASCII
* "@B892524 " (bytes 2-10), BCD date YY MM DD at bytes 11-13, three
* BCD part numbers from byte 16 (7799764 / 7799765 / 7793887, six
* bytes each), VIN prefix "WBANC92090" at bytes 53-62. Tried first
* because this board's own `1A 80` went unanswered that day.
* `1A 80` - what the Launch asks (answered on both Patrols, 31 / 37 bytes):
* BCD part number at bytes 4-7, BCD date YY MM DD at bytes 15-17.
* Second in the sequence; also what the passive check compares.
* Field offsets are the ones observed on these two DDEs (wiki vehicles page);
* a block that does not fit them is still stored and shown by length.
*
* Transmits through DiagProbe only (its guards: one request in flight, single
* shot, refused for 3 s after any foreign tester frame).
*/
#pragma once
#include <Arduino.h>
namespace EcuIdent {
/** Load the stored blocks and hook DiagProbe. Call after DiagProbe::init(). */
void init();
/** One-shot read sequencing and the deferred NVS write. Call from loop(). */
void tick();
/** At least one identification block is stored. */
bool known();
/** A `1A 80` block seen on the bus (another tester's read) differs from the stored one. */
bool changed();
/**
* One line for the screens: "DDE 7799764 - 2006-03-07", "UNKNOWN ECU",
* "ECU CHANGED? bus 7796678, stored 7794904", ...
*/
void describe(char* buf, size_t n);
/**
* The ECU in front of us carries this part number: the differing `1A 80` block
* seen on the bus when changed() is set, otherwise any stored block's number
* ("7796678", "7799764", ...). The Engine data screen keys its per-DDE
* live-data identifiers on it - the one place behaviour follows the label,
* because the `2C` identifiers are addresses inside each DDE's own software.
*/
bool hasPart(const char* part);
/** Drop the stored blocks; UNKNOWN ECU until the next successful read. */
void forget();
/** `ecu show | dump | forget`. */
bool handleCommand(const char* line);
} // namespace EcuIdent
+258
View File
@@ -0,0 +1,258 @@
/*
* Engine Data Screen Module Implementation - see engine_screen.h
*/
#include "engine_screen.h"
#include "ui_kit.h"
#include "diag_probe.h"
#include "ecu_ident.h"
#include "driveline_screen.h"
#include "display/lvgl_v8_port.h"
namespace EngineScreen {
using namespace UiKit;
// ============================================================================
// SCALINGS (raw = the 2-byte value of `6C 10 HH LL`)
// ============================================================================
typedef struct {
DiagProbe::live_id_t id;
const char* title;
const char* unit;
float factor;
float offset;
int decimals;
} channel_t;
static const channel_t CHANNELS[DiagProbe::LIVE_COUNT] = {
// verified 2026-09-23 against the Launch at two operating points (Patrol 1)
{DiagProbe::LIVE_RAIL, "Rail pressure", "bar", 0.03f, 0.0f, 1},
// 8271 raw <-> ~1028-1034 mbar engine off (2026-10-07): 1/8 mbar per count
{DiagProbe::LIVE_BOOST, "Boost (absolute)", "mbar", 0.125f, 0.0f, 0},
// 5295..5301 raw <-> Launch 36-38 C engine off (2026-10-07)
{DiagProbe::LIVE_AIR_TEMP, "Charge-air temp", "\xC2\xB0" "C", 0.01f, -15.0f, 1},
// 4998 raw <-> 12.27 V engine off (2026-10-07, from the capture's file name)
{DiagProbe::LIVE_BATTERY, "Battery", "V", 0.002455f, 0.0f, 2},
};
// ============================================================================
// PER-DDE PROFILES
// ============================================================================
//
// The `2C 10 <id>` identifiers are addresses inside each DDE's own software:
// Patrol 1's set, asked on Patrol 2's unit, returned a refused rail read, a
// flat "2800 mbar" boost and a ">300 C" air temperature (user, 2026-10-18).
// The Launch itself reads `1A 80` every cycle to choose its data set, and on
// Patrol 2 it polled `00C2` for rail pressure. So the identifiers follow the
// ECU identity (`EcuIdent`): the first profile whose part number the stored
// identification carries wins. A slot with identifier 0 is never requested and
// its card says so. No identified ECU, or an ECU with no profile = no polling.
//
// Adding a car: capture the Launch on each value (wiki obd-diagnostic-polling,
// "decode recipe"), then add a row - part numbers from `ecu show`.
typedef struct {
const char* name; // for the status line
const char* parts[4]; // any part number (1A 80 or 1A 86) of this DDE, NULL-terminated
DiagProbe::live_set_t set; // define id + one identifier per live_id_t slot (0 = unknown)
uint8_t provisional_mask; // bit per slot: scaling fitted to a single Launch reading
} profile_t;
static const profile_t PROFILES[] = {
// Patrol 1: DDE 7796678 (1A 80, 2006-02) / 7799764, 7799765, 7793887 (1A 86, 2006-03)
{"DDE 7796678 (Patrol 1)", {"7796678", "7799764", "7799765", "7793887"},
{0x15E0, {0x00DF, 0x0091, 0x16A8, 0x0093}},
(1 << DiagProbe::LIVE_BOOST) | (1 << DiagProbe::LIVE_AIR_TEMP) | (1 << DiagProbe::LIVE_BATTERY)},
// Patrol 2: DDE 7794904 (1A 80, 2004-01) = 7796156 / 7796157 / 7789877
// (1A 86, 2006-05-17, VIN prefix WBAGM21070 = E65 7-series; both blocks
// read by this board on 2026-10-18, `ecu dump` in the wiki). Every
// identifier differs from Patrol 1's, the scalings look the same: rail
// `00C2` (~330 bar at idle), boost `003A` (1018 mbar idle, 1186 on a blip),
// battery `002F` (14.0 V running, 12.7 V engine off) - all from Launch
// captures on 2026-10-18 without the Launch's own readings noted, so all
// provisional. No define seen. Charge-air temperature: not captured yet.
{"DDE 7794904 (Patrol 2)", {"7794904", "7796156", "7796157", "7789877"},
{0, {0x00C2, 0x003A, 0, 0x002F}},
(1 << DiagProbe::LIVE_RAIL) | (1 << DiagProbe::LIVE_BOOST) | (1 << DiagProbe::LIVE_BATTERY)},
};
static const int PROFILE_COUNT = sizeof(PROFILES) / sizeof(PROFILES[0]);
static const uint32_t STALE_MS = 3000; // value older than this shows "--"
// ============================================================================
// STATE
// ============================================================================
static lv_obj_t* g_screen = NULL;
static lv_obj_t* g_status = NULL;
static lv_obj_t* g_value[DiagProbe::LIVE_COUNT];
static lv_obj_t* g_raw[DiagProbe::LIVE_COUNT];
static lv_obj_t* g_tag[DiagProbe::LIVE_COUNT];
static const profile_t* g_profile = NULL; // the one in use (NULL = none)
static bool g_profile_known = false; // g_profile has been evaluated at least once
/** The profile for the identified ECU, NULL when unknown or not in the table. */
static const profile_t* findProfile() {
if (!EcuIdent::known()) return NULL;
for (int i = 0; i < PROFILE_COUNT; i++)
for (int k = 0; k < 4 && PROFILES[i].parts[k]; k++)
if (EcuIdent::hasPart(PROFILES[i].parts[k])) return &PROFILES[i];
return NULL;
}
/** Re-evaluate the profile; install its identifier set on change. */
static void applyProfile() {
const profile_t* p = findProfile();
if (g_profile_known && p == g_profile) return;
g_profile_known = true;
g_profile = p;
DiagProbe::liveConfigure(p ? &p->set : NULL);
if (!p) DiagProbe::liveStop();
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
if (!g_tag[i]) continue;
bool prov = p && (p->provisional_mask & (1 << i));
if (prov) lv_obj_clear_flag(g_tag[i], LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_tag[i], LV_OBJ_FLAG_HIDDEN);
}
}
static void onBack(lv_event_t* e) {
(void)e;
DiagProbe::liveStop();
DrivelineScreen::show();
}
static void onGesture(lv_event_t* e) {
(void)e;
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act());
DiagProbe::liveStop();
DrivelineScreen::show();
}
}
static void makeCard(lv_obj_t* parent, int i) {
const channel_t& ch = CHANNELS[i];
lv_obj_t* c = card(parent);
lv_obj_set_size(c, 476, 200);
lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_all(c, 20, 0);
lv_obj_set_style_pad_row(c, 8, 0);
lv_obj_t* top = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(top, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(top, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
label(top, ch.title, &lv_font_montserrat_24, UI_COL_MUTED);
lv_obj_t* tag = label(top, "provisional", &lv_font_montserrat_14, UI_COL_AMBER);
lv_obj_set_style_border_color(tag, UI_COL_AMBER, 0);
lv_obj_set_style_border_width(tag, 1, 0);
lv_obj_set_style_radius(tag, 6, 0);
lv_obj_set_style_pad_hor(tag, 8, 0);
lv_obj_set_style_pad_ver(tag, 3, 0);
lv_obj_add_flag(tag, LV_OBJ_FLAG_HIDDEN); // shown per profile
g_tag[i] = tag;
lv_obj_t* row = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(row, 12, 0);
g_value[i] = label(row, "--", &lv_font_montserrat_48, UI_COL_TEXT);
lv_obj_t* u = label(row, ch.unit, &lv_font_montserrat_24, UI_COL_MUTED);
lv_obj_set_style_pad_bottom(u, 6, 0);
g_raw[i] = label(c, "raw --", &lv_font_montserrat_20, UI_COL_MUTED);
}
static void build() {
if (g_screen) return;
g_screen = screen();
lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL);
header(g_screen, "ENGINE DATA", onBack);
g_status = label(g_screen, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_set_pos(g_status, 24, 84);
lv_obj_t* grid = box(g_screen, LV_FLEX_FLOW_ROW_WRAP);
lv_obj_set_size(grid, 1024 - 48, 200 * 2 + 24);
lv_obj_set_pos(grid, 24, 126);
lv_obj_set_style_pad_column(grid, 24, 0);
lv_obj_set_style_pad_row(grid, 24, 0);
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) makeCard(grid, i);
}
static void refresh() {
char st[160];
lv_color_t col = UI_COL_MUTED;
if (!g_profile) {
if (!EcuIdent::known()) {
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " Engine ECU not identified yet - no live data until it is read (key on, see Settings > Vehicle)");
} else {
char ecu[64];
EcuIdent::describe(ecu, sizeof(ecu));
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " %s - no live-data identifiers known for this ECU yet (capture it with the Launch)", ecu);
}
col = UI_COL_AMBER;
} else {
switch (DiagProbe::liveState()) {
case DiagProbe::LIVE_RUNNING:
snprintf(st, sizeof(st), LV_SYMBOL_OK " Live from the engine ECU, %s", g_profile->name); col = UI_COL_OK; break;
case DiagProbe::LIVE_PAUSED_TESTER:
snprintf(st, sizeof(st), LV_SYMBOL_PAUSE " Paused: another diagnostic tester is connected (e.g. the Launch)"); col = UI_COL_AMBER; break;
case DiagProbe::LIVE_CAN_OFF:
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System"); col = UI_COL_WARN; break;
case DiagProbe::LIVE_NO_ANSWER:
snprintf(st, sizeof(st), LV_SYMBOL_WARNING " No answer from the engine ECU - is the ignition on?"); col = UI_COL_WARN; break;
default:
snprintf(st, sizeof(st), "Starting..."); break;
}
}
setText(g_status, st);
setTextColor(g_status, col);
char buf[64];
for (int i = 0; i < DiagProbe::LIVE_COUNT; i++) {
const channel_t& ch = CHANNELS[i];
uint16_t vid = g_profile ? g_profile->set.ids[ch.id] : 0;
if (vid == 0) {
setText(g_value[i], "--");
setText(g_raw[i], g_profile ? "identifier not known for this ECU yet" : "no ECU profile");
continue;
}
DiagProbe::live_value_t v = DiagProbe::liveValue(ch.id);
if (v.valid && v.age_ms < STALE_MS) {
snprintf(buf, sizeof(buf), "%.*f", ch.decimals, v.raw * ch.factor + ch.offset);
setText(g_value[i], buf);
snprintf(buf, sizeof(buf), "raw %u (0x%04X) id %04X", v.raw, v.raw, vid);
} else {
setText(g_value[i], "--");
if (v.nrc) snprintf(buf, sizeof(buf), "refused by the ECU (NRC 0x%02X) id %04X", v.nrc, vid);
else if (v.valid) snprintf(buf, sizeof(buf), "raw %u (stale) id %04X", v.raw, vid);
else snprintf(buf, sizeof(buf), "raw -- id %04X", vid);
}
setText(g_raw[i], buf);
}
}
void show() {
build();
applyProfile();
if (g_profile) DiagProbe::liveKeepAlive();
refresh();
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
}
void tick() {
if (g_screen == NULL || lv_scr_act() != g_screen) return;
static uint32_t last = 0;
if (millis() - last < 250) return;
last = millis();
lvgl_port_lock(-1);
applyProfile(); // the ECU may get identified while we watch
if (g_profile) DiagProbe::liveKeepAlive(); // polling stops ~1.5 s after the screen is left
refresh();
lvgl_port_unlock();
}
} // namespace EngineScreen
+31
View File
@@ -0,0 +1,31 @@
/*
* Engine Data Screen Module
*
* Four live values read from the DDE (engine ECU) with the same KWP `2C 10`
* requests the Launch scanner uses: rail pressure, boost (charge-air pressure,
* actual), charge-air temperature, battery voltage. Polling (DiagProbe's live
* mode) runs only while this screen is shown and pauses while another tester
* is on the bus.
*
* Scalings come from Launch captures (wiki/pages/obd-diagnostic-polling.md);
* the ones resting on a single reading are tagged "provisional" on screen, and
* every value shows its raw number so it can be compared with the Launch.
*
* Opened from the "Engine data" button on the Driveline screen; the Driveline
* button or a right swipe goes back.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
namespace EngineScreen {
/** Build (idempotent) and load. Caller holds the LVGL lock. */
void show();
/** Keep the poll alive and refresh values while shown. Call from loop(); takes its own lock. */
void tick();
} // namespace EngineScreen
+48 -2
View File
@@ -1,5 +1,5 @@
/*
* ESP-NOW Link Module Implementation (Controller A, transmit only)
* ESP-NOW Link Module Implementation (Main CTRL, transmit only)
*/
#include "espnow_link.h"
@@ -16,6 +16,13 @@ static const uint8_t BROADCAST_MAC[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
static bool g_ready = false;
static uint32_t g_sent = 0;
static uint32_t g_fail = 0;
static receive_handler_t g_rx_handler = NULL;
// IDF 5.x receive callback: sender MAC is in the info struct.
static void onReceive(const esp_now_recv_info_t* info, const uint8_t* data, int len) {
if (g_rx_handler == NULL || info == NULL || len <= 0) return;
g_rx_handler(info->src_addr, data, (size_t)len);
}
// IDF 5.5 (pioarduino / Arduino 3.3) passes wifi_tx_info_t*; older cores passed the MAC.
static void onSent(const wifi_tx_info_t* info, esp_now_send_status_t status) {
@@ -45,6 +52,7 @@ bool init() {
return false;
}
esp_now_register_send_cb(onSent);
esp_now_register_recv_cb(onReceive);
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, BROADCAST_MAC, 6);
@@ -62,14 +70,30 @@ bool init() {
return true;
}
// Anything that restarts the Wi-Fi driver drops ESP-NOW with it. Re-init at
// most once a second instead of failing every frame from then on.
static void reinitIfDue() {
static uint32_t last = 0;
if (millis() - last < 1000) return;
last = millis();
g_ready = false;
ESP_LOGW("EspNow", "ESP-NOW not initialised - re-initialising");
init();
}
bool send(const uint8_t* frame, size_t len) {
if (!g_ready || len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
if (!g_ready) {
reinitIfDue();
if (!g_ready) return false;
}
esp_err_t err = esp_now_send(BROADCAST_MAC, frame, len);
if (err == ESP_OK) {
g_sent++;
return true;
}
g_fail++;
if (err == ESP_ERR_ESPNOW_NOT_INIT) reinitIfDue();
return false;
}
@@ -77,4 +101,26 @@ bool isReady() { return g_ready; }
uint32_t sentCount() { return g_sent; }
uint32_t failCount() { return g_fail; }
void setReceiveHandler(receive_handler_t handler) { g_rx_handler = handler; }
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len) {
if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return false;
if (!g_ready) {
reinitIfDue();
if (!g_ready) return false;
}
if (!esp_now_is_peer_exist(mac)) {
esp_now_peer_info_t peer = {};
memcpy(peer.peer_addr, mac, 6);
peer.channel = 0; // current channel
peer.encrypt = false; // SECURE frames carry their own encryption
peer.ifidx = WIFI_IF_STA;
if (esp_now_add_peer(&peer) != ESP_OK) {
ESP_LOGE("EspNow", "esp_now_add_peer(B) failed");
return false;
}
}
return esp_now_send(mac, frame, len) == ESP_OK;
}
} // namespace EspNowLink
+12 -1
View File
@@ -1,10 +1,14 @@
/*
* ESP-NOW Link Module (Controller A side, transmit only)
* ESP-NOW Link Module (Main CTRL side)
*
* Second transport for the A -> B link: every frame the UART manager builds
* is also broadcast over ESP-NOW, so B keeps receiving if the wire is lost.
* B dedupes on packet_id, so both paths may be live at once.
*
* Since 2026-09-27 the radio also listens: B unicasts STATUS frames back and
* A unicasts SECURE frames to B (LinkPeer). Frames received are handed to the
* handler set with setReceiveHandler(); sendTo() unicasts to one MAC.
*
* Radio policy: the Wi-Fi radio stays in STA mode permanently (the WiFi
* manager's "off" only stops scanning). A transmits on ESPNOW_CHANNEL unless
* associated to an access point, in which case the AP's channel is used and
@@ -34,4 +38,11 @@ bool isReady();
uint32_t sentCount();
uint32_t failCount();
/** Frames received from any sender (runs in the Wi-Fi task - copy and return). */
typedef void (*receive_handler_t)(const uint8_t mac[6], const uint8_t* frame, size_t len);
void setReceiveHandler(receive_handler_t handler);
/** Unicast one complete frame to a MAC (peer added on first use, unencrypted). */
bool sendTo(const uint8_t mac[6], const uint8_t* frame, size_t len);
} // namespace EspNowLink
+370
View File
@@ -0,0 +1,370 @@
/*
* Link Peer Module Implementation (Main CTRL)
*
* Threading: onFrame() runs in the Wi-Fi task and only copies the STATUS into
* g_peer under a mutex. Everything else (NVS, sending, console) is the loop task.
*/
#include "link_peer.h"
#include "espnow_link.h"
#include "uart_manager.h"
#include "wifi_manager.h"
#include "ota_update.h"
#include "serial_lock.h"
#include "protocol/link_secure.h"
#include <Preferences.h>
#include <esp_wifi.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
namespace LinkPeer {
static const char* NVS_LINK = "linkpeer"; // key (32 B)
#define CREDS_PUSH_MIN_MS 15000 // never push credentials more often than this
#define PAIR_REPEATS 3 // PAIR is sent this many times over the wire
static bool g_paired = false;
static uint8_t g_key[LINK_KEY_LEN];
static uint16_t g_key_fp = 0;
// last STATUS from B (written by the Wi-Fi task)
static SemaphoreHandle_t g_mutex = NULL;
static link_status_t g_st = {};
static uint8_t g_b_mac[6] = {0};
static uint32_t g_last_status_ms = 0;
static bool g_ever_heard = false;
static uint32_t g_status_count = 0, g_secure_sent = 0, g_secure_fail = 0;
// credential sync
static uint32_t g_pushed_hash = 0;
static uint32_t g_last_push_ms = 0;
static void lock() { xSemaphoreTake(g_mutex, portMAX_DELAY); }
static void unlock() { xSemaphoreGive(g_mutex); }
static void print(const char* fmt, ...) {
char buf[200];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static const char* phaseName(uint8_t p) {
switch (p) {
case LINK_OTA_CHECKING: return "checking";
case LINK_OTA_UP_TO_DATE: return "up to date";
case LINK_OTA_AVAILABLE: return "update available";
case LINK_OTA_INSTALLING: return "installing";
case LINK_OTA_FAILED: return "failed";
default: return "idle";
}
}
// ---- NVS --------------------------------------------------------------------
static void loadKey() {
Preferences p;
p.begin(NVS_LINK, true);
g_paired = p.getBytesLength("key") == LINK_KEY_LEN;
if (g_paired) p.getBytes("key", g_key, LINK_KEY_LEN);
p.end();
g_key_fp = g_paired ? link_key_fingerprint(g_key) : 0;
}
static void storeKey() {
Preferences p;
p.begin(NVS_LINK, false);
p.putBytes("key", g_key, LINK_KEY_LEN);
p.end();
}
static void clearKey() {
Preferences p;
p.begin(NVS_LINK, false);
p.clear();
p.end();
g_paired = false;
g_key_fp = 0;
memset(g_key, 0, sizeof(g_key));
}
// ---- inbound (Wi-Fi task) ---------------------------------------------------
static void onFrame(const uint8_t mac[6], const uint8_t* frame, size_t len) {
uint8_t type = 0, plen = 0;
const uint8_t* payload = NULL;
if (frame_parse(frame, len, &type, &payload, &plen) != FRAME_OK) return;
if (type != PACKET_TYPE_STATUS) return;
if (xSemaphoreTake(g_mutex, pdMS_TO_TICKS(10)) != pdTRUE) return;
memcpy(&g_st, payload, sizeof(g_st));
g_st.version[sizeof(g_st.version) - 1] = 0;
g_st.latest[sizeof(g_st.latest) - 1] = 0;
g_st.message[sizeof(g_st.message) - 1] = 0;
memcpy(g_b_mac, mac, 6);
g_last_status_ms = millis();
g_ever_heard = true;
g_status_count++;
xSemaphoreGive(g_mutex);
}
// ---- public: status ---------------------------------------------------------
peer_status_t getStatus() {
peer_status_t p = {};
lock();
p.st = g_st;
memcpy(p.mac, g_b_mac, 6);
uint32_t last = g_last_status_ms;
bool ever = g_ever_heard;
unlock();
p.age_ms = ever ? millis() - last : 0xFFFFFFFF;
p.heard = ever && p.age_ms < LINK_STATUS_TIMEOUT_MS;
p.paired = g_paired;
p.key_fp = g_key_fp;
p.key_match = g_paired && p.st.key_fp == g_key_fp;
return p;
}
// ---- outbound ---------------------------------------------------------------
static bool sendSecure(uint8_t inner_type, const void* inner, size_t inner_len, char* why, size_t n) {
peer_status_t p = getStatus();
if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard"); return false; }
if (!p.paired) { snprintf(why, n, "not paired - run `link pair` with the wire connected"); return false; }
if (!p.key_match) { snprintf(why, n, "Inst. Cluster holds a different key - run `link pair` again"); return false; }
uint8_t payload[PACKET_MAX_PAYLOAD], frame[PACKET_MAX_SIZE];
size_t plen = link_secure_seal(g_key, inner_type, inner, inner_len, payload);
if (!plen) { snprintf(why, n, "encryption failed"); return false; }
size_t flen = frame_build(PACKET_TYPE_SECURE, payload, (uint8_t)plen, frame);
if (!flen || !EspNowLink::sendTo(p.mac, frame, flen)) {
g_secure_fail++;
snprintf(why, n, "ESP-NOW send failed");
return false;
}
g_secure_sent++;
return true;
}
static bool sendOtaCmd(uint8_t cmd, uint8_t flags, char* why, size_t n) {
link_ota_cmd_t c = {};
c.cmd = cmd;
c.flags = flags;
c.nonce = esp_random();
return sendSecure(LINK_INNER_OTA_CMD, &c, sizeof(c), why, n);
}
static uint32_t hashStr(uint32_t h, const char* s) {
for (; *s; s++) h = (h ^ (uint8_t)*s) * 16777619u; // FNV-1a
return h;
}
/** Push A's remembered network (or a FORGET) to B. */
static bool pushCredentials(char* why, size_t n, bool log) {
link_wifi_creds_t c = {};
char pass[65];
bool have = WiFiManager::getSavedCredentials(c.ssid, sizeof(c.ssid), pass, sizeof(pass));
if (have) {
c.action = LINK_WIFI_SET;
strlcpy(c.pass, pass, sizeof(c.pass));
} else {
c.action = LINK_WIFI_FORGET;
}
bool ok = sendSecure(LINK_INNER_WIFI_CREDS, &c, sizeof(c), why, n);
memset(pass, 0, sizeof(pass));
if (ok) {
g_pushed_hash = have ? hashStr(hashStr(2166136261u, c.ssid), c.pass) : 1;
g_last_push_ms = millis();
if (log) print(have ? "[link] Wi-Fi credentials for '%s' sent to Inst. Cluster (encrypted)"
: "[link] told Inst. Cluster to forget its Wi-Fi credentials", c.ssid);
}
memset(&c, 0, sizeof(c));
return ok;
}
// B lacks credentials A has, or A's changed, or A forgot them while B still has them.
static void syncCredentials() {
peer_status_t p = getStatus();
if (!p.heard || !p.paired || !p.key_match) return;
if (millis() - g_last_push_ms < CREDS_PUSH_MIN_MS && g_last_push_ms != 0) return;
char ssid[33], pass[65];
bool have = WiFiManager::getSavedCredentials(ssid, sizeof(ssid), pass, sizeof(pass));
uint32_t h = have ? hashStr(hashStr(2166136261u, ssid), pass) : 1;
memset(pass, 0, sizeof(pass));
bool b_has = (p.st.flags & LINK_STATUS_HAVE_WIFI) != 0;
bool need = have ? (!b_has || h != g_pushed_hash)
: (b_has && g_pushed_hash != 1);
if (!need) return;
char why[64];
pushCredentials(why, sizeof(why), true);
}
// ---- pairing ----------------------------------------------------------------
static bool pair(char* why, size_t n) {
if (UARTManager::getState() == UARTManager::UART_STATE_OFF) {
snprintf(why, n, "link is off - enable 'Send to Inst. Cluster' in Settings first");
return false;
}
link_pair_t pk = {};
pk.magic = LINK_PAIR_MAGIC;
esp_fill_random(pk.key, LINK_KEY_LEN);
esp_wifi_get_mac(WIFI_IF_STA, pk.a_mac);
uint8_t frame[PACKET_MAX_SIZE];
size_t flen = frame_build(PACKET_TYPE_PAIR, &pk, sizeof(pk), frame);
int sent = 0;
for (int i = 0; i < PAIR_REPEATS; i++) {
if (UARTManager::sendWire(frame, flen)) sent++;
delay(40);
}
if (!sent) { snprintf(why, n, "UART write failed"); memset(&pk, 0, sizeof(pk)); return false; }
memcpy(g_key, pk.key, LINK_KEY_LEN);
memset(&pk, 0, sizeof(pk));
g_paired = true;
g_key_fp = link_key_fingerprint(g_key);
storeKey();
g_pushed_hash = 0; // re-send the credentials under the new key
g_last_push_ms = 0;
print("[link] PAIR sent over the wire %d time(s); new key fingerprint %04X. "
"Inst. Cluster confirms in its next STATUS (`link status`).", sent, g_key_fp);
return true;
}
// ---- public: requests (UI) --------------------------------------------------
static bool bReady(char* why, size_t n, bool need_parked) {
peer_status_t p = getStatus();
if (!p.heard) { snprintf(why, n, "Inst. Cluster not heard - is it powered?"); return false; }
if (!p.paired || !p.key_match) {
snprintf(why, n, "Inst. Cluster is not paired with this controller (console: link pair, wire connected)");
return false;
}
if (!(p.st.flags & LINK_STATUS_HAVE_WIFI)) {
snprintf(why, n, "Inst. Cluster has no Wi-Fi credentials yet - join a network on this screen first");
return false;
}
if (p.st.ota_phase == LINK_OTA_CHECKING || p.st.ota_phase == LINK_OTA_INSTALLING) {
snprintf(why, n, "Inst. Cluster is busy (%s)", phaseName(p.st.ota_phase));
return false;
}
if (need_parked && !Ota::isParked(why, n)) return false;
// Same network as B => same radio channel, so B's STATUS frames (progress)
// keep reaching this screen while B is joined.
if (WiFiManager::getStatus().link != WiFiManager::LINK_CONNECTED) {
snprintf(why, n, "join Wi-Fi on this controller first, so Inst. Cluster's progress can be followed");
return false;
}
return true;
}
bool requestCheck(char* why, size_t n) {
if (!bReady(why, n, false)) { print("[link] check refused: %s", why); return false; }
return sendOtaCmd(LINK_OTA_CMD_CHECK, 0, why, n);
}
bool requestInstall(char* why, size_t n) {
if (!bReady(why, n, true)) { print("[link] install refused: %s", why); return false; }
return sendOtaCmd(LINK_OTA_CMD_INSTALL, 0, why, n);
}
// ---- lifecycle --------------------------------------------------------------
void init() {
if (g_mutex == NULL) g_mutex = xSemaphoreCreateMutex();
loadKey();
EspNowLink::setReceiveHandler(onFrame);
print("[link] Inst. Cluster: %s", g_paired ? "pairing key loaded" : "NOT paired - `link pair` with the wire connected");
}
void tick() {
static uint32_t last = 0;
static bool was_heard = false;
static uint8_t last_phase = 0xFF;
static bool was_match = false;
if (millis() - last < 1000) return;
last = millis();
peer_status_t p = getStatus();
if (p.heard != was_heard) {
was_heard = p.heard;
if (p.heard) print("[link] Inst. Cluster heard: %s, %s, %lu s up", p.st.version,
p.key_match ? "paired" : (p.st.key_fp ? "paired with ANOTHER key" : "unpaired"),
(unsigned long)p.st.uptime_s);
else print("[link] Inst. Cluster silent for %lu s", (unsigned long)(p.age_ms / 1000));
}
if (p.heard && p.key_match && !was_match) {
print("[link] Inst. Cluster confirmed pairing (fingerprint %04X)", p.st.key_fp);
}
was_match = p.heard && p.key_match;
if (p.heard && p.st.ota_phase != last_phase) {
if (last_phase != 0xFF || p.st.ota_phase != LINK_OTA_IDLE)
print("[link] Inst. Cluster update: %s%s%s%s%s", phaseName(p.st.ota_phase),
p.st.latest[0] ? ", latest " : "", p.st.latest,
p.st.ota_phase == LINK_OTA_FAILED ? " - " : "",
p.st.ota_phase == LINK_OTA_FAILED ? p.st.message : "");
last_phase = p.st.ota_phase;
}
syncCredentials();
}
// ---- console ----------------------------------------------------------------
static void help() {
print("link status Inst. Cluster: version, pairing, update phase");
print("link pair new shared key -> B over the UART wire (bench, wire connected)");
print("link unpair forget the key here (B keeps its own until re-paired)");
print("link creds send the remembered Wi-Fi network to B now");
print("link ota check|install [force]|rollback drive B's updater");
}
bool handleCommand(const char* line) {
if (strncmp(line, "link", 4) != 0 || (line[4] != 0 && line[4] != ' ')) return false;
const char* a = line + 4;
while (*a == ' ') a++;
char why[96] = "";
if (!*a || !strcmp(a, "help")) { help(); return true; }
if (!strcmp(a, "status")) {
peer_status_t p = getStatus();
print("[link] this side: %s (fingerprint %04X) | STATUS frames %lu | SECURE sent %lu, failed %lu",
p.paired ? "paired" : "NOT paired", p.key_fp, (unsigned long)g_status_count,
(unsigned long)g_secure_sent, (unsigned long)g_secure_fail);
if (!g_ever_heard) { print("[link] Inst. Cluster never heard"); return true; }
print("[link] Inst. Cluster %02X:%02X:%02X:%02X:%02X:%02X, %s (%lu s ago)",
p.mac[0], p.mac[1], p.mac[2], p.mac[3], p.mac[4], p.mac[5],
p.heard ? "alive" : "SILENT", (unsigned long)(p.age_ms / 1000));
print("[link] firmware %s | key %04X (%s) | Wi-Fi creds %s%s%s",
p.st.version, p.st.key_fp, p.key_match ? "matches" : p.st.key_fp ? "DIFFERENT" : "none",
(p.st.flags & LINK_STATUS_HAVE_WIFI) ? "yes" : "no",
(p.st.flags & LINK_STATUS_WIFI_JOINED) ? ", joined" : "",
(p.st.flags & LINK_STATUS_PENDING_VERIFY) ? " | fresh image, unconfirmed" : "");
print("[link] update: %s%s%s%s%s | up %lu s | heap %lu",
phaseName(p.st.ota_phase),
p.st.latest[0] ? ", latest " : "", p.st.latest,
p.st.message[0] ? " - " : "", p.st.message,
(unsigned long)p.st.uptime_s, (unsigned long)p.st.free_heap);
return true;
}
if (!strcmp(a, "pair")) { if (!pair(why, sizeof(why))) print("[link] pair refused: %s", why); return true; }
if (!strcmp(a, "unpair")) { clearKey(); print("[link] pairing key removed here"); return true; }
if (!strcmp(a, "creds")) {
if (!pushCredentials(why, sizeof(why), true)) print("[link] creds refused: %s", why);
return true;
}
if (!strncmp(a, "ota", 3)) {
const char* b = a + 3;
while (*b == ' ') b++;
bool ok = false;
if (!strcmp(b, "check")) ok = requestCheck(why, sizeof(why));
else if (!strcmp(b, "install")) ok = requestInstall(why, sizeof(why));
else if (!strcmp(b, "install force")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_INSTALL, LINK_OTA_FORCE, why, sizeof(why));
else if (!strcmp(b, "rollback")) ok = bReady(why, sizeof(why), true) && sendOtaCmd(LINK_OTA_CMD_ROLLBACK, 0, why, sizeof(why));
else { help(); return true; }
print(ok ? "[link] command sent to Inst. Cluster - watch `link status`" : "[link] refused: %s", why);
return true;
}
help();
return true;
}
} // namespace LinkPeer
+49
View File
@@ -0,0 +1,49 @@
/*
* Link Peer Module (Main CTRL) - what A knows about Inst. Cluster, and the
* maintenance traffic that keeps B updatable. See
* ESP32-S3-LCD-1.3/wiki/pages/controller-b-ota.md (B's wiki).
*
* STATUS B -> A ESP-NOW unicast every 5 s: B's version, OTA phase, uptime.
* Shown on Settings -> Updates as the "Inst. Cluster" card.
* PAIR A -> B `link pair` on the console, UART WIRE ONLY: a fresh random
* key, kept in NVS on both sides. Both repos are public, so
* this is the only secret and it never travels by radio.
* SECURE A -> B ESP-NOW unicast, AES-256-GCM under the pairing key:
* the remembered Wi-Fi credentials (pushed automatically
* whenever B lacks them or they change) and OTA commands.
*
* Console: link status | pair | unpair | creds | ota check | ota install [force] | ota rollback
*/
#pragma once
#include <Arduino.h>
#include "protocol/automotive_data.h"
namespace LinkPeer {
/** Load the pairing key, hook the ESP-NOW receive path. After EspNowLink::init(). */
void init();
/** Credential sync + logging. Call from loop(). */
void tick();
typedef struct {
bool heard; // STATUS within LINK_STATUS_TIMEOUT_MS
uint32_t age_ms; // since the last STATUS
uint8_t mac[6]; // B's STA MAC
link_status_t st; // last STATUS as received
bool paired; // this controller holds a pairing key
bool key_match; // B reports the fingerprint of OUR key
uint16_t key_fp; // our key's fingerprint (0 = none)
} peer_status_t;
peer_status_t getStatus();
/** Ask B to check / install (behind the same parking gate as A's own update). */
bool requestCheck(char* why, size_t n);
bool requestInstall(char* why, size_t n);
bool handleCommand(const char* line);
} // namespace LinkPeer
+730
View File
@@ -0,0 +1,730 @@
/**
* ota_update.cpp - see ota_update.h for the command set and safety rules.
*
* Flow of `ota install`:
* 1. gate: Wi-Fi joined, vehicle parked
* 2. GET /api/v1/repos/<repo>/releases/latest -> tag_name
* 3. GET /<repo>/releases/download/<tag>/manifest.txt
* 4. verify ECDSA P-256 signature over "target|version|sha256" (before download)
* 5. GET /<repo>/releases/download/<tag>/firmware.bin -> idle OTA slot,
* hashing as it streams; sha256 must equal the signed one
* 6. esp_ota_end() (image self-check), gate again, switch boot slot, reboot
* 7. next boot: the image is PENDING_VERIFY until tick() confirms it
*/
#include "modules/ota_update.h"
#include "modules/serial_lock.h"
#include "drivers/can_driver.h"
#include "protocol/automotive_data.h"
#include "config/ota_config.h"
#include "modules/display_init.h"
#include "modules/tunables.h"
#include "display/lvgl_v8_port.h"
#include <lvgl.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <esp_ota_ops.h>
#include <esp_partition.h>
#include <mbedtls/sha256.h>
#include <mbedtls/pk.h>
#include <mbedtls/platform.h>
#include <esp_heap_caps.h>
#include <stdarg.h>
// Take over Arduino's rollback hook: by default initArduino() marks a new image
// valid before setup() even runs, so a crash in setup would never roll back.
// Returning true leaves the image PENDING_VERIFY until Ota::tick() confirms it.
extern "C" bool verifyRollbackLater() { return true; }
namespace Ota {
static void setNoticeProgress(int pct); // defined with the full-screen notice below
#define OTA_CONFIRM_S 30 // healthy uptime before a new image is kept
#define TOSTR_(x) #x
#define TOSTR(x) TOSTR_(x)
static const uint32_t OTA_CONFIRM_MS = OTA_CONFIRM_S * 1000;
static const uint32_t BUS_SILENT_MS = 2000; // no frames for this long = ignition off / bench
static const uint32_t STALL_TIMEOUT_MS = 15000; // download aborts if no bytes arrive this long
static const size_t CHUNK = 4096;
// Jobs run inside the Arduino loop task (8 KB internal stack), not a task of
// their own: with the display + Wi-Fi up, internal RAM has no block big enough
// for another TLS-capable stack (measured 2026-09-26: 15.9 KB free, largest
// block 7.6 KB), and the stack can't go to PSRAM because esp_ota_write()
// disables the flash cache. The loop (screen value ticks, console) pauses
// while a job runs - acceptable: parked, and an install ends in a reboot.
typedef struct {
char tag[32];
char target[16];
char version[32];
uint32_t size;
char sha256[65]; // lowercase hex
uint8_t sig[80]; // DER ECDSA signature
size_t sig_len;
} manifest_t;
enum job_t { JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE };
static bool g_job_pending = false;
static job_t g_job = JOB_CHECK;
static bool g_pending_verify = false;
// What the Settings screen shows. Written by the loop task (jobs) and the LVGL
// task (requests), read by the loop task - a spinlock keeps copies consistent.
static portMUX_TYPE g_ui_mux = portMUX_INITIALIZER_UNLOCKED;
static ui_status_t g_ui = {PHASE_IDLE, "", ""};
static char g_last_msg[96] = ""; // last console line, reused as the failure reason
static void setPhase(phase_t p, const char* latest = NULL, const char* msg = NULL) {
portENTER_CRITICAL(&g_ui_mux);
g_ui.phase = p;
if (latest) { strncpy(g_ui.latest, latest, sizeof(g_ui.latest) - 1); g_ui.latest[sizeof(g_ui.latest) - 1] = 0; }
const char* m = msg ? msg : "";
strncpy(g_ui.message, m, sizeof(g_ui.message) - 1);
g_ui.message[sizeof(g_ui.message) - 1] = 0;
portEXIT_CRITICAL(&g_ui_mux);
}
// ============================================================================
// Helpers
// ============================================================================
static void vlog(bool remember, const char* fmt, va_list ap) {
char buf[220];
vsnprintf(buf, sizeof(buf), fmt, ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
if (remember) {
const char* m = strncmp(buf, "[ota] ", 6) == 0 ? buf + 6 : buf;
portENTER_CRITICAL(&g_ui_mux);
strncpy(g_last_msg, m, sizeof(g_last_msg) - 1);
g_last_msg[sizeof(g_last_msg) - 1] = 0;
portEXIT_CRITICAL(&g_ui_mux);
}
}
/** Console line; also kept as the reason the screen shows if the job fails. */
static void print(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vlog(true, fmt, ap);
va_end(ap);
}
/** Console-only diagnostics (heap, stack) that must not replace a failure reason. */
static void debug(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
vlog(false, fmt, ap);
va_end(ap);
}
static void failPhase() {
char m[96];
portENTER_CRITICAL(&g_ui_mux);
memcpy(m, g_last_msg, sizeof(m));
portEXIT_CRITICAL(&g_ui_mux);
setPhase(PHASE_FAILED, NULL, m);
}
static const char* stateName(esp_ota_img_states_t s) {
switch (s) {
case ESP_OTA_IMG_NEW: return "new";
case ESP_OTA_IMG_PENDING_VERIFY: return "pending-verify";
case ESP_OTA_IMG_VALID: return "valid";
case ESP_OTA_IMG_INVALID: return "invalid";
case ESP_OTA_IMG_ABORTED: return "aborted";
default: return "undefined";
}
}
/**
* The vehicle must be parked to update: installing ends in a reboot that blanks
* Inst. Cluster's gauges. A silent bus (ignition off, or the bench) counts as
* parked. Lever UNKNOWN is allowed so a missing gear frame can't block a bench
* update; engine and output shaft are the checks that matter.
*/
static bool parked(char* why, size_t n) {
if (!CANDriver::isActive()) return true;
can_stats_t s = CANDriver::getStats();
if (millis() - s.last_receive_time > BUS_SILENT_MS) return true;
driveline_t d = CANDriver::getDriveline();
if (d.engine_rpm > 0 || d.engine_run_state == ENGINE_RUN_RUNNING ||
d.engine_run_state == ENGINE_RUN_STARTING) {
snprintf(why, n, "engine running (%u rpm) - switch the engine off", d.engine_rpm);
return false;
}
if (d.output_shaft_raw != 0) {
snprintf(why, n, "vehicle moving (output shaft turning)");
return false;
}
if (d.lever != GEAR_PARK && d.lever != GEAR_NEUTRAL && d.lever != GEAR_UNKNOWN) {
snprintf(why, n, "lever in a drive gear - select P");
return false;
}
return true;
}
static bool gate(bool need_wifi, bool need_parked = true, char* why_out = NULL, size_t why_n = 0) {
char why[96];
bool ok = true;
if (need_parked && !parked(why, sizeof(why))) {
ok = false;
} else if (need_wifi && WiFi.status() != WL_CONNECTED) {
snprintf(why, sizeof(why), "Wi-Fi not connected - join a network first");
ok = false;
}
if (!ok) {
print("[ota] refused: %s", why);
if (why_out) snprintf(why_out, why_n, "%s", why);
}
return ok;
}
static void toHex(const uint8_t* in, size_t n, char* out) {
static const char* d = "0123456789abcdef";
for (size_t i = 0; i < n; i++) {
out[2 * i] = d[in[i] >> 4];
out[2 * i + 1] = d[in[i] & 0x0F];
}
out[2 * n] = 0;
}
static int hexNibble(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
static bool fromHex(const char* s, uint8_t* out, size_t cap, size_t* len) {
size_t n = strlen(s);
if (n == 0 || (n % 2) || n / 2 > cap) return false;
for (size_t i = 0; i < n; i += 2) {
int hi = hexNibble(s[i]), lo = hexNibble(s[i + 1]);
if (hi < 0 || lo < 0) return false;
out[i / 2] = (uint8_t)((hi << 4) | lo);
}
*len = n / 2;
return true;
}
/** Tags end up in URLs; accept only [A-Za-z0-9._-]. */
static bool safeToken(const char* s) {
if (!*s) return false;
for (; *s; s++) {
if (!isalnum((unsigned char)*s) && *s != '.' && *s != '_' && *s != '-') return false;
}
return true;
}
/** HTTPS GET of a small text body (API reply, manifest). */
static bool httpsGetText(const char* url, String& body, int& code) {
WiFiClientSecure client;
client.setCACert(OTA_CA_PEM);
HTTPClient http;
http.setConnectTimeout(10000);
http.setTimeout(15000);
if (!http.begin(client, url)) {
code = -1;
return false;
}
http.setUserAgent("patrol-a-ota/" FW_VERSION);
code = http.GET();
bool ok = (code == HTTP_CODE_OK);
if (ok) body = http.getString();
http.end();
return ok;
}
/** Pull "key":"value" out of a flat JSON reply without a JSON library. */
static bool jsonString(const String& s, const char* key, char* out, size_t n) {
String k = String("\"") + key + "\"";
int i = s.indexOf(k);
if (i < 0) return false;
i = s.indexOf(':', i + k.length());
if (i < 0) return false;
i = s.indexOf('"', i);
if (i < 0) return false;
int j = s.indexOf('"', i + 1);
if (j < 0 || (size_t)(j - i - 1) >= n) return false;
s.substring(i + 1, j).toCharArray(out, n);
return true;
}
static bool fetchManifest(manifest_t& m) {
memset(&m, 0, sizeof(m));
String body;
int code;
if (!httpsGetText(OTA_LATEST_API_URL, body, code)) {
if (code == 404) print("[ota] no release published yet (push a v* tag)");
else print("[ota] release lookup failed (HTTP %d)", code);
return false;
}
if (!jsonString(body, "tag_name", m.tag, sizeof(m.tag)) || !safeToken(m.tag)) {
print("[ota] could not read tag_name from the release reply");
return false;
}
String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/manifest.txt";
if (!httpsGetText(url.c_str(), body, code)) {
print("[ota] release %s has no manifest.txt (HTTP %d)", m.tag, code);
return false;
}
char sig_hex[2 * sizeof(m.sig) + 1] = {0};
int start = 0;
while (start < (int)body.length()) {
int nl = body.indexOf('\n', start);
if (nl < 0) nl = body.length();
String line = body.substring(start, nl);
line.trim();
start = nl + 1;
int eq = line.indexOf('=');
if (eq <= 0) continue;
String k = line.substring(0, eq), v = line.substring(eq + 1);
if (k == "target") v.toCharArray(m.target, sizeof(m.target));
else if (k == "version") v.toCharArray(m.version, sizeof(m.version));
else if (k == "size") m.size = (uint32_t)v.toInt();
else if (k == "sha256") v.toCharArray(m.sha256, sizeof(m.sha256));
else if (k == "sig" && v.length() < sizeof(sig_hex)) v.toCharArray(sig_hex, sizeof(sig_hex));
}
if (strcmp(m.target, OTA_TARGET) != 0) {
print("[ota] manifest is for '%s', not '%s' - refusing", m.target, OTA_TARGET);
return false;
}
if (strcmp(m.version, m.tag) != 0 || m.size == 0 || strlen(m.sha256) != 64 ||
!fromHex(sig_hex, m.sig, sizeof(m.sig), &m.sig_len)) {
print("[ota] manifest for %s is malformed", m.tag);
return false;
}
for (char* c = m.sha256; *c; c++) *c = tolower(*c);
return true;
}
/** ECDSA P-256 over SHA-256("target|version|sha256hex"), checked before downloading. */
static bool verifySignature(const manifest_t& m) {
char stmt[160];
int n = snprintf(stmt, sizeof(stmt), "%s|%s|%s", m.target, m.version, m.sha256);
uint8_t h[32];
mbedtls_sha256((const unsigned char*)stmt, n, h, 0);
mbedtls_pk_context pk;
mbedtls_pk_init(&pk);
int rc = mbedtls_pk_parse_public_key(&pk, (const unsigned char*)OTA_SIGNING_PUBKEY_PEM,
sizeof(OTA_SIGNING_PUBKEY_PEM));
if (rc == 0) rc = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, h, sizeof(h), m.sig, m.sig_len);
mbedtls_pk_free(&pk);
if (rc != 0) print("[ota] SIGNATURE INVALID for %s (mbedtls -0x%04X) - refusing", m.tag, -rc);
return rc == 0;
}
// ============================================================================
// Install
// ============================================================================
/** Download firmware.bin into the idle slot, hashing as it streams; true if it matches the signed manifest. */
static bool writeImage(const manifest_t& m, const esp_partition_t* part) {
String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/firmware.bin";
WiFiClientSecure client;
client.setCACert(OTA_CA_PEM);
HTTPClient http;
http.setConnectTimeout(10000);
http.setTimeout(15000);
if (!http.begin(client, url)) { print("[ota] bad download URL"); return false; }
http.setUserAgent("patrol-a-ota/" FW_VERSION);
int code = http.GET();
if (code != HTTP_CODE_OK) { print("[ota] download failed (HTTP %d)", code); http.end(); return false; }
if (http.getSize() != (int)m.size) {
print("[ota] server size %d != manifest size %lu", http.getSize(), (unsigned long)m.size);
http.end();
return false;
}
esp_ota_handle_t h = 0;
esp_err_t err = esp_ota_begin(part, OTA_WITH_SEQUENTIAL_WRITES, &h);
if (err != ESP_OK) { print("[ota] esp_ota_begin: %s", esp_err_to_name(err)); http.end(); return false; }
uint8_t* buf = (uint8_t*)malloc(CHUNK);
mbedtls_sha256_context sc;
mbedtls_sha256_init(&sc);
mbedtls_sha256_starts(&sc, 0);
NetworkClient* stream = http.getStreamPtr();
uint32_t got = 0, last_rx = millis();
int last_decile = -1;
bool ok = (buf != NULL);
while (ok && got < m.size) {
size_t avail = stream->available();
if (avail == 0) {
// connected() can read false for a moment between TLS records, so a
// drop only counts after 2 s of silence (it aborted a download at
// 570 B once, 2026-09-26; the retry went through).
uint32_t idle = millis() - last_rx;
if ((!http.connected() && idle > 2000) || idle > STALL_TIMEOUT_MS) {
print("[ota] download stalled at %lu/%lu bytes", (unsigned long)got, (unsigned long)m.size);
ok = false;
break;
}
vTaskDelay(pdMS_TO_TICKS(5));
continue;
}
size_t want = min(min(avail, CHUNK), (size_t)(m.size - got));
int r = stream->read(buf, want);
if (r <= 0) continue;
last_rx = millis();
mbedtls_sha256_update(&sc, buf, r);
err = esp_ota_write(h, buf, r);
if (err != ESP_OK) { print("[ota] flash write: %s", esp_err_to_name(err)); ok = false; break; }
got += r;
int pct = (int)((uint64_t)got * 100 / m.size);
setNoticeProgress(pct);
int decile = pct / 10;
if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; }
}
http.end();
free(buf);
uint8_t digest[32];
char digest_hex[65];
mbedtls_sha256_finish(&sc, digest);
mbedtls_sha256_free(&sc);
toHex(digest, sizeof(digest), digest_hex);
if (ok && strcmp(digest_hex, m.sha256) != 0) {
print("[ota] SHA-256 MISMATCH - image does not match the signed manifest");
ok = false;
}
if (!ok) { esp_ota_abort(h); print("[ota] aborted; still running %s", FW_VERSION); return false; }
err = esp_ota_end(h); // validates the image structure + its embedded hash
if (err != ESP_OK) { print("[ota] image check failed: %s", esp_err_to_name(err)); return false; }
return true;
}
// ---- Full-screen notice on lv_layer_top() (above every screen) ----------------
// Since the core runs with XIP from PSRAM and an IRAM-safe RGB refill ISR
// (2026-09-27), flash writes no longer blank the panel, so the screen stays ON
// during the download and shows a progress bar. The user must see that the
// update is alive; a dark screen invited switching the ignition off mid-write.
static lv_obj_t* g_notice = NULL;
static lv_obj_t* g_notice_lbl = NULL;
static lv_obj_t* g_notice_bar = NULL;
static lv_obj_t* g_notice_pct = NULL;
static lv_obj_t* g_notice_warn = NULL;
static int g_notice_last_pct = -1;
static void showNotice(const char* text, bool with_progress = false) {
lvgl_port_lock(-1);
if (g_notice == NULL) {
g_notice = lv_obj_create(lv_layer_top());
lv_obj_remove_style_all(g_notice);
lv_obj_set_size(g_notice, LV_PCT(100), LV_PCT(100));
lv_obj_set_style_bg_color(g_notice, lv_color_black(), 0);
lv_obj_set_style_bg_opa(g_notice, LV_OPA_COVER, 0);
lv_obj_add_flag(g_notice, LV_OBJ_FLAG_CLICKABLE); // swallow touches while shown
g_notice_lbl = lv_label_create(g_notice);
lv_obj_set_style_text_font(g_notice_lbl, &lv_font_montserrat_30, 0);
lv_obj_set_style_text_color(g_notice_lbl, lv_color_white(), 0);
lv_obj_set_style_text_align(g_notice_lbl, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_align(g_notice_lbl, LV_ALIGN_CENTER, 0, -90);
g_notice_bar = lv_bar_create(g_notice);
lv_obj_set_size(g_notice_bar, 640, 28);
lv_obj_align(g_notice_bar, LV_ALIGN_CENTER, 0, 10);
lv_bar_set_range(g_notice_bar, 0, 100);
lv_bar_set_value(g_notice_bar, 0, LV_ANIM_OFF);
lv_obj_set_style_bg_color(g_notice_bar, lv_color_hex(0x252D36), LV_PART_MAIN);
lv_obj_set_style_bg_opa(g_notice_bar, LV_OPA_COVER, LV_PART_MAIN);
lv_obj_set_style_radius(g_notice_bar, 14, LV_PART_MAIN);
lv_obj_set_style_bg_color(g_notice_bar, lv_color_hex(0x3DA9FC), LV_PART_INDICATOR);
lv_obj_set_style_bg_opa(g_notice_bar, LV_OPA_COVER, LV_PART_INDICATOR);
lv_obj_set_style_radius(g_notice_bar, 14, LV_PART_INDICATOR);
g_notice_pct = lv_label_create(g_notice);
lv_obj_set_style_text_font(g_notice_pct, &lv_font_montserrat_24, 0);
lv_obj_set_style_text_color(g_notice_pct, lv_color_white(), 0);
lv_label_set_text(g_notice_pct, "0%");
lv_obj_align_to(g_notice_pct, g_notice_bar, LV_ALIGN_OUT_BOTTOM_MID, 0, 12);
g_notice_warn = lv_label_create(g_notice);
lv_obj_set_style_text_font(g_notice_warn, &lv_font_montserrat_24, 0);
lv_obj_set_style_text_color(g_notice_warn, lv_color_hex(0xF5A524), 0);
lv_obj_set_style_text_align(g_notice_warn, LV_TEXT_ALIGN_CENTER, 0);
lv_label_set_text(g_notice_warn, LV_SYMBOL_WARNING " Do not switch off the ignition");
lv_obj_align(g_notice_warn, LV_ALIGN_CENTER, 0, 130);
}
lv_label_set_text(g_notice_lbl, text);
if (with_progress) {
lv_bar_set_value(g_notice_bar, 0, LV_ANIM_OFF);
lv_label_set_text(g_notice_pct, "0%");
lv_obj_clear_flag(g_notice_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(g_notice_pct, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(g_notice_warn, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(g_notice_bar, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(g_notice_pct, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(g_notice_warn, LV_OBJ_FLAG_HIDDEN);
}
g_notice_last_pct = -1;
lv_obj_clear_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
lvgl_port_unlock();
}
/** Progress bar update from the download loop (loop task). Cheap: one bar + label. */
static void setNoticeProgress(int pct) {
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
if (pct == g_notice_last_pct || g_notice_bar == NULL) return;
g_notice_last_pct = pct;
char t[8];
snprintf(t, sizeof(t), "%d%%", pct);
if (!lvgl_port_lock(50)) return; // never stall the download on the UI lock
lv_bar_set_value(g_notice_bar, pct, LV_ANIM_OFF);
lv_label_set_text(g_notice_pct, t);
lvgl_port_unlock();
}
static void hideNotice() {
lvgl_port_lock(-1);
if (g_notice) lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN);
lvgl_port_unlock();
}
static void install(bool force) {
manifest_t m;
if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; }
if (!force && strcmp(m.version, FW_VERSION) == 0) {
print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION);
setPhase(PHASE_UP_TO_DATE, m.version);
return;
}
const esp_partition_t* part = esp_ota_get_next_update_partition(NULL);
if (!part) { print("[ota] no idle OTA slot (partition table?)"); failPhase(); return; }
if (m.size > part->size) {
print("[ota] image %lu B does not fit slot %s (%lu B)",
(unsigned long)m.size, part->label, (unsigned long)part->size);
failPhase();
return;
}
print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size);
// The screen stays on: with XIP from PSRAM + an IRAM-safe RGB refill ISR the
// flash writes no longer starve the panel (verified 2026-09-27: 24 frames/s
// for the whole download). The bar is driven from the download loop.
char msg[160];
snprintf(msg, sizeof(msg), "Updating to %s", m.version);
showNotice(msg, true);
bool ok = writeImage(m, part);
// The download took a while - the driver may have started the engine since.
if (ok && !gate(false)) {
print("[ota] new image left inactive in %s; retry when parked", part->label);
ok = false;
}
if (ok) {
esp_err_t err = esp_ota_set_boot_partition(part);
if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); ok = false; }
}
if (!ok) {
failPhase();
snprintf(msg, sizeof(msg), "Update failed\n\nStill running %s", FW_VERSION);
showNotice(msg);
delay(5000);
hideNotice();
return;
}
print("[ota] verified and installed %s. Rebooting in 3 s; it confirms itself after %lu s of uptime.",
m.version, (unsigned long)(OTA_CONFIRM_MS / 1000));
snprintf(msg, sizeof(msg), "Installed %s\n\nRestarting...", m.version);
showNotice(msg);
Tunables::flush();
delay(3000);
esp_restart();
}
static void check() {
manifest_t m;
if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; }
bool same = strcmp(m.version, FW_VERSION) == 0;
print("[ota] running %s | latest release %s (%lu bytes, signature OK)%s",
FW_VERSION, m.version, (unsigned long)m.size,
same ? " - up to date" : " - `ota install` to update");
setPhase(same ? PHASE_UP_TO_DATE : PHASE_AVAILABLE, m.version);
}
// This core's mbedtls is built with CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC: every TLS
// session wants ~40 KB of *internal* RAM, which the display + Wi-Fi leave no
// room for. Route mbedtls to PSRAM (internal as fallback) while a job runs.
// Both allocators free with heap_caps_free(), so swapping them is always safe.
static void* tlsCallocPsram(size_t n, size_t size) {
return heap_caps_calloc_prefer(n, size, 2, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
}
static void* tlsCallocInternal(size_t n, size_t size) {
return heap_caps_calloc(n, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
}
static void printHeap(const char* when) {
debug("[ota] heap %s: internal free %u (largest block %u), PSRAM free %u", when,
(unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
(unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
(unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
}
static void runJob(job_t job) {
mbedtls_platform_set_calloc_free(tlsCallocPsram, heap_caps_free);
if (job == JOB_CHECK) check();
else install(job == JOB_INSTALL_FORCE);
mbedtls_platform_set_calloc_free(tlsCallocInternal, heap_caps_free);
debug("[ota] loop stack headroom after job: %u B", (unsigned)uxTaskGetStackHighWaterMark(NULL));
}
static bool startJob(job_t job, char* why = NULL, size_t why_n = 0) {
if (g_job_pending) {
if (why) snprintf(why, why_n, "busy");
return false;
}
if (!gate(true, job != JOB_CHECK, why, why_n)) return false; // checking is harmless; installing needs parked
setPhase(job == JOB_CHECK ? PHASE_CHECKING : PHASE_INSTALLING);
g_job = job;
g_job_pending = true; // runs on the next tick(), in the loop task
print("[ota] working - console and screen values pause until done");
return true;
}
// ============================================================================
// Status / rollback
// ============================================================================
static void status() {
const esp_partition_t* run = esp_ota_get_running_partition();
const esp_partition_t* other = esp_ota_get_next_update_partition(NULL);
esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED;
esp_ota_get_state_partition(run, &st);
print("[ota] version %s (built %s %s), slot %s, state %s%s", FW_VERSION, __DATE__, __TIME__,
run ? run->label : "?", stateName(st),
g_pending_verify ? " - confirms after " TOSTR(OTA_CONFIRM_S) " s uptime" : "");
if (other) {
esp_app_desc_t d;
esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED;
esp_ota_get_state_partition(other, &ost);
if (esp_ota_get_partition_description(other, &d) == ESP_OK) {
print("[ota] other slot %s: image built %s %s, state %s", other->label, d.date, d.time, stateName(ost));
} else {
print("[ota] other slot %s: empty", other->label);
}
}
print("[ota] updates from %s/%s/releases (%s)", OTA_SERVER, OTA_REPO, OTA_TARGET);
printHeap("now");
}
static void rollback() {
if (!gate(false)) return;
if (g_pending_verify) {
print("[ota] rejecting this unconfirmed image; rebooting into the previous one");
Tunables::flush();
delay(500);
esp_ota_mark_app_invalid_rollback_and_reboot();
return;
}
const esp_partition_t* other = esp_ota_get_next_update_partition(NULL);
esp_app_desc_t d;
esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED;
if (!other || esp_ota_get_partition_description(other, &d) != ESP_OK) {
print("[ota] no previous image to roll back to");
return;
}
esp_ota_get_state_partition(other, &ost);
if (ost == ESP_OTA_IMG_INVALID || ost == ESP_OTA_IMG_ABORTED) {
print("[ota] previous image in %s is marked %s - refusing", other->label, stateName(ost));
return;
}
esp_err_t err = esp_ota_set_boot_partition(other);
if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); return; }
print("[ota] booting %s in 2 s", other->label);
Tunables::flush();
delay(2000);
esp_restart();
}
static void help() {
print("ota status running version, slot, rollback state");
print("ota check ask Gitea for the latest release (needs Wi-Fi)");
print("ota install [force] download + verify + flash idle slot + reboot (parked only)");
print("ota rollback boot the previous slot (parked only)");
print("Tip: `diag raw off` first so CANRAW lines don't bury the progress output.");
}
// ============================================================================
// Public API
// ============================================================================
const char* version() { return FW_VERSION; }
ui_status_t getStatus() {
ui_status_t s;
portENTER_CRITICAL(&g_ui_mux);
s = g_ui;
portEXIT_CRITICAL(&g_ui_mux);
return s;
}
bool requestCheck(char* why, size_t n) { return startJob(JOB_CHECK, why, n); }
bool requestInstall(char* why, size_t n) { return startJob(JOB_INSTALL, why, n); }
bool isParked(char* why, size_t n) { return parked(why, n); }
void init() {
const esp_partition_t* run = esp_ota_get_running_partition();
esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED;
if (run && esp_ota_get_state_partition(run, &st) == ESP_OK && st == ESP_OTA_IMG_PENDING_VERIFY) {
g_pending_verify = true;
}
print("[ota] firmware %s, slot %s%s", FW_VERSION, run ? run->label : "?",
g_pending_verify ? " - NEW IMAGE, unconfirmed (a reset in the next " TOSTR(OTA_CONFIRM_S) " s rolls back)" : "");
}
void tick() {
if (g_job_pending) {
g_job_pending = false;
runJob(g_job);
}
if (g_pending_verify && millis() > OTA_CONFIRM_MS) {
esp_ota_mark_app_valid_cancel_rollback();
g_pending_verify = false;
print("[ota] firmware %s confirmed - rollback cancelled", FW_VERSION);
}
}
bool handleCommand(const char* line) {
char buf[48];
strncpy(buf, line, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
char* argv[4] = {0};
int argc = 0;
for (char* t = strtok(buf, " \t"); t && argc < 4; t = strtok(NULL, " \t")) argv[argc++] = t;
if (argc == 0 || strcmp(argv[0], "ota") != 0) return false;
if (argc == 1 || !strcmp(argv[1], "help")) help();
else if (!strcmp(argv[1], "status")) status();
else if (!strcmp(argv[1], "check")) startJob(JOB_CHECK);
else if (!strcmp(argv[1], "install")) startJob(argc > 2 && !strcmp(argv[2], "force") ? JOB_INSTALL_FORCE : JOB_INSTALL);
else if (!strcmp(argv[1], "rollback")) rollback();
else help();
return true;
}
} // namespace Ota
+74
View File
@@ -0,0 +1,74 @@
/**
* ota_update.h - pull firmware updates from this repo's Gitea releases.
*
* Manual only: nothing checks or installs by itself. Driven from the Settings
* screen (Updates section: check, then install behind a confirm dialog) and the
* `ota` serial console.
*
* ota status running version, slot, rollback state
* ota check ask Gitea for the latest release, compare versions
* ota install [force] download, verify signature, flash idle slot, reboot
* ota rollback boot the previous slot
*
* Safety:
* - refused unless the vehicle is parked (engine off, output shaft still, lever
* not in a drive gear) - checked before the download AND again before the
* boot slot is switched. Silent bus (bench / ignition off) counts as parked.
* - image must match the signed manifest (sha256 + ECDSA P-256 over
* "target|version|sha256"); otherwise the idle slot is never activated.
* - a new image must run OTA_CONFIRM_MS before it is marked valid; a reset
* or crash before that makes the bootloader fall back to the old slot.
*
* Needs Wi-Fi joined to a network with internet (Settings screen). Joining an
* AP moves the radio channel; the ESP-NOW link to Inst. Cluster follows it.
* See wiki/pages/ota-updates.md.
*/
#ifndef OTA_UPDATE_H
#define OTA_UPDATE_H
#include <Arduino.h>
namespace Ota {
/** Log version/slot; note if this boot is an unconfirmed new image. Call early in setup(). */
void init();
/** Confirms a freshly installed image once it has run long enough. Call from loop(). */
void tick();
/** Console entry point (`ota ...`). Returns false if the line isn't an ota command. */
bool handleCommand(const char* line);
/** Firmware version baked in at build time ("dev" for local builds). */
const char* version();
// ---- Settings screen -------------------------------------------------------
typedef enum {
PHASE_IDLE, // nothing asked yet this boot
PHASE_CHECKING,
PHASE_UP_TO_DATE, // latest == running
PHASE_AVAILABLE, // latest != running
PHASE_INSTALLING,
PHASE_FAILED // message says why
} phase_t;
typedef struct {
phase_t phase;
char latest[32]; // latest release tag, once known
char message[96]; // failure reason
} ui_status_t;
ui_status_t getStatus();
/** Queue a check / install (runs in the loop task). False + reason if refused now. */
bool requestCheck(char* why, size_t n);
bool requestInstall(char* why, size_t n);
/** The parking gate on its own (Inst. Cluster's install is guarded by it too). */
bool isParked(char* why, size_t n);
} // namespace Ota
#endif // OTA_UPDATE_H
+224
View File
@@ -0,0 +1,224 @@
/*
* Performance Monitor implementation. See perf_monitor.h.
*
* onFrame()/onFlush() run in the LVGL task; everything else in loop(). The
* counters are plain 32-bit words read under a short critical section, so the
* hooks cost nothing measurable.
*/
#include "perf_monitor.h"
#include "serial_lock.h"
#include "display/lvgl_v8_port.h"
#include <lvgl.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_heap_caps.h>
#include <esp_timer.h>
#include <string.h>
namespace PerfMon {
// ---- accumulators (LVGL task writes, loop reads) ---------------------------
static portMUX_TYPE g_mux = portMUX_INITIALIZER_UNLOCKED;
static uint32_t g_frames = 0;
static uint32_t g_frame_ms_sum = 0;
static uint32_t g_frame_ms_max = 0;
static uint32_t g_frame_px_sum = 0;
static uint32_t g_flushes = 0;
static uint32_t g_flush_us_sum = 0;
static uint32_t g_flush_px_sum = 0;
// vsync counters: written from the panel ISR, read from the reporter. 32-bit
// aligned loads/stores are atomic on this core; no lock in the ISR.
static volatile uint32_t g_vsync_count = 0;
static volatile uint32_t g_vsync_gap_max_us = 0;
static volatile uint32_t g_vsync_last_us = 0;
static esp_timer_handle_t g_timer = NULL;
// ---- window bookkeeping (loop) --------------------------------------------
static int64_t g_window_start_us = 0;
static uint64_t g_idle_start[2] = {0, 0};
static bool g_periodic = false;
static uint32_t g_period_ms = 1000;
static uint32_t g_last_report_ms = 0;
static void print(const char* fmt, ...) {
char buf[240];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static uint64_t idleCounter(int core) {
#if CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS
// Run-time counter unit is microseconds (esp_timer) on ESP-IDF.
return (uint64_t)ulTaskGetIdleRunTimeCounterForCore(core);
#else
(void)core;
return 0;
#endif
}
static void timerCallback(void* arg);
static void resetWindow() {
portENTER_CRITICAL(&g_mux);
g_frames = g_frame_ms_sum = g_frame_ms_max = g_frame_px_sum = 0;
g_flushes = g_flush_us_sum = g_flush_px_sum = 0;
portEXIT_CRITICAL(&g_mux);
g_vsync_count = 0;
g_vsync_gap_max_us = 0;
g_window_start_us = esp_timer_get_time();
g_idle_start[0] = idleCounter(0);
g_idle_start[1] = idleCounter(1);
}
void init() {
resetWindow();
if (!g_timer) {
esp_timer_create_args_t a = {};
a.callback = timerCallback;
a.arg = NULL;
a.dispatch_method = ESP_TIMER_TASK;
a.name = "perf";
esp_timer_create(&a, &g_timer);
}
}
void onFrame(uint32_t time_ms, uint32_t px) {
portENTER_CRITICAL(&g_mux);
g_frames++;
g_frame_ms_sum += time_ms;
if (time_ms > g_frame_ms_max) g_frame_ms_max = time_ms;
g_frame_px_sum += px;
portEXIT_CRITICAL(&g_mux);
}
void onFlush(uint32_t time_us, uint32_t px) {
portENTER_CRITICAL(&g_mux);
g_flushes++;
g_flush_us_sum += time_us;
g_flush_px_sum += px;
portEXIT_CRITICAL(&g_mux);
}
void IRAM_ATTR onVsync() {
uint32_t now = (uint32_t)esp_timer_get_time();
uint32_t last = g_vsync_last_us;
g_vsync_last_us = now;
g_vsync_count = g_vsync_count + 1;
if (last != 0) {
uint32_t gap = now - last;
if (gap > g_vsync_gap_max_us) g_vsync_gap_max_us = gap;
}
}
/** Emit one PERF line for the window since the last reset, then reset. */
static void report() {
int64_t now_us = esp_timer_get_time();
uint64_t win_us = (uint64_t)(now_us - g_window_start_us);
if (win_us < 1000) win_us = 1000;
uint32_t frames, ms_sum, ms_max, px_sum, flushes, fl_us, fl_px;
portENTER_CRITICAL(&g_mux);
frames = g_frames; ms_sum = g_frame_ms_sum; ms_max = g_frame_ms_max; px_sum = g_frame_px_sum;
flushes = g_flushes; fl_us = g_flush_us_sum; fl_px = g_flush_px_sum;
portEXIT_CRITICAL(&g_mux);
uint32_t vsyncs = g_vsync_count;
uint32_t vgap = g_vsync_gap_max_us;
unsigned vsync_per_s = (unsigned)((uint64_t)vsyncs * 1000000ULL / win_us);
uint64_t idle0 = idleCounter(0) - g_idle_start[0];
uint64_t idle1 = idleCounter(1) - g_idle_start[1];
unsigned idle0_pct = (unsigned)((idle0 * 100) / win_us);
unsigned idle1_pct = (unsigned)((idle1 * 100) / win_us);
if (idle0_pct > 100) idle0_pct = 100;
if (idle1_pct > 100) idle1_pct = 100;
// fps x10 for one decimal without floats in the format
unsigned fps10 = (unsigned)((uint64_t)frames * 10000000ULL / win_us);
unsigned avg_ms10 = frames ? (ms_sum * 10) / frames : 0;
unsigned kpx = frames ? (px_sum / frames) / 1000 : 0;
unsigned flush_ms_per_s = (unsigned)(((uint64_t)fl_us * 1000ULL) / win_us); // ms of copying per second
unsigned lv_idle = 0;
if (lvgl_port_lock_available()) {
lv_idle = lv_timer_get_idle();
}
print("PERF,%lu,%u.%u,%u.%u,%lu,%u,%u,%u,%u,%u,%u,%u,%u,%u,%lu",
(unsigned long)millis(),
fps10 / 10, fps10 % 10,
avg_ms10 / 10, avg_ms10 % 10,
(unsigned long)ms_max,
kpx,
flush_ms_per_s,
lv_idle,
idle0_pct, idle1_pct,
(unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
(unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
(unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM),
vsync_per_s, (unsigned long)vgap);
(void)flushes; (void)fl_px;
resetWindow();
}
static void help() {
print("perf one PERF line for the window since the last report");
print("perf on [sec] PERF line every <sec> seconds (default 1) while you provoke symptoms");
print("perf off");
print("PERF,ts,fps,avg_ms,max_ms,kpx/frame,flush_ms/s,lvgl_idle%%,idle0%%,idle1%%,int_free,int_largest,psram_free,vsync/s,vsync_gap_max_us");
}
bool handleCommand(const char* line) {
char buf[48];
strncpy(buf, line, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
char* argv[3] = {0};
int argc = 0;
for (char* tok = strtok(buf, " \t"); tok && argc < 3; tok = strtok(NULL, " \t")) argv[argc++] = tok;
if (argc == 0 || strcmp(argv[0], "perf") != 0) return false;
if (argc == 1) { report(); return true; }
if (!strcmp(argv[1], "help")) { help(); return true; }
if (!strcmp(argv[1], "on")) {
long s = (argc == 3) ? strtol(argv[2], NULL, 10) : 1;
if (s < 1) s = 1;
if (s > 60) s = 60;
g_period_ms = (uint32_t)s * 1000;
g_periodic = true;
g_last_report_ms = millis();
resetWindow();
// esp_timer, not loop(): the OTA job blocks loop() for the whole download
// and that is exactly when we want to see the panel counters.
if (g_timer) esp_timer_stop(g_timer);
if (g_timer) esp_timer_start_periodic(g_timer, (uint64_t)g_period_ms * 1000ULL);
print("[perf] periodic every %ld s (columns: ts,fps,avg_ms,max_ms,kpx,flush_ms/s,lv_idle,idle0,idle1,int_free,int_largest,psram,vsync/s,vsync_gap_max_us)", s);
return true;
}
if (!strcmp(argv[1], "off")) {
g_periodic = false;
if (g_timer) esp_timer_stop(g_timer);
print("[perf] periodic off");
return true;
}
help();
return true;
}
static void timerCallback(void* arg) {
(void)arg;
if (g_periodic) report();
}
void tick() {
// Reporting moved to the esp_timer (see handleCommand "on").
}
} // namespace PerfMon
+60
View File
@@ -0,0 +1,60 @@
/*
* Performance Monitor
*
* Measures what the display pipeline actually does, so display experiments
* (bounce buffers, draw-buffer size, XIP from PSRAM - wiki open question #13)
* can be compared with numbers instead of impressions:
*
* - render frames/s and ms per frame (LVGL's monitor_cb: render + flush)
* - time spent copying pixels into the PSRAM framebuffer (flush_cb)
* - LVGL task idle % (lv_timer_get_idle)
* - CPU idle % per core (FreeRTOS run-time stats)
* - internal heap, largest block, PSRAM free
*
* Console:
* perf one line for the last window
* perf on [sec] print a PERF, line every <sec> s (default 1) - use while
* provoking symptoms (Wi-Fi scan, tuning save, OTA)
* perf off
*
* PERF line (CSV, greppable like CANRAW):
* PERF,<ts_ms>,<fps>,<avg_ms>,<max_ms>,<kpx/frame>,<flush_ms/s>,
* <lvgl_idle%>,<idle0%>,<idle1%>,<int_free>,<int_largest>,<psram_free>,
* <vsync/s>,<vsync_gap_max_us>
* vsync/s is the panel's own refresh rate (constant when healthy);
* vsync_gap_max_us is the longest interval between two refreshes in the
* window - a DMA underrun/restart stretches it.
*/
#pragma once
#include <Arduino.h>
namespace PerfMon {
/** Call once in setup(), before the LVGL port starts. */
void init();
/** Hook for lv_disp_drv_t::monitor_cb - one rendered frame (ms, pixels). */
void onFrame(uint32_t time_ms, uint32_t px);
/** Hook for the flush callback - one pixel copy into the framebuffer. */
void onFlush(uint32_t time_us, uint32_t px);
/**
* Hook for the RGB panel's refresh-finished (vsync) interrupt. ISR context:
* counts frames the panel actually completed and the longest gap between two,
* which is where a DMA underrun / restart (flicker, dots) shows up.
*/
void onVsync();
/** Console line beginning with "perf". */
bool handleCommand(const char* line);
/**
* Kept for compatibility; periodic reporting now runs from an esp_timer so it
* survives a blocked loop() (the OTA job). Safe to call, does nothing.
*/
void tick();
} // namespace PerfMon
+151
View File
@@ -0,0 +1,151 @@
/*
* Reverse lights on DO0 - see reverse_light.h
*/
#include "reverse_light.h"
#include "settings_manager.h"
#include "drivers/can_driver.h"
#include "display/lvgl_v8_port.h"
#include "serial_lock.h"
#include <esp_display_panel.hpp>
#include <stdarg.h>
namespace ReverseLight {
// CH422G pins in the ESP32_IO_Expander numbering: IO0-7 = 0-7, OC0-3 = 8-11.
// OC0 is OD0 on the schematic -> PC817 T1 -> power transistor T2 -> DOUT0.
static const uint8_t OC0_PIN = 8;
static const uint32_t POLL_MS = 100;
static const uint8_t CONFIRM = 2; // equal decisions before the output moves (200 ms)
static const uint8_t FAULT_AFTER = 3; // failed writes in a row before we say so
static const uint32_t FORCE_MAX_MS = 60000; // a forgotten `reverse force on` ends itself
enum force_t : uint8_t { FORCE_AUTO = 0, FORCE_ON, FORCE_OFF };
static esp_expander::Base* g_expander = nullptr;
static bool g_enabled = true;
static force_t g_force = FORCE_AUTO;
static uint32_t g_force_since = 0;
static bool g_output = false; // what the chip was last told successfully
static bool g_output_known = false; // false until the first successful write
static bool g_decided = false; // the current (confirmed) decision
static bool g_candidate = false; // the decision being confirmed
static uint8_t g_candidate_ticks = 0;
static uint8_t g_fail_run = 0;
static uint32_t g_writes = 0, g_fails = 0, g_switches = 0;
static uint32_t g_last_poll = 0;
static void print(const char* fmt, ...) {
char buf[160];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
/** One write to OC0. OC0 LOW lights the opto LED, which turns the output on. */
static bool drive(bool on) {
if (g_expander == nullptr) return false;
if (!lvgl_port_lock(100)) return false; // UI busy: retried next tick
bool ok = g_expander->digitalWrite(OC0_PIN, on ? 0 : 1);
lvgl_port_unlock();
g_writes++;
if (!ok) {
g_fails++;
if (g_fail_run < 255) g_fail_run++;
if (g_fail_run == FAULT_AFTER) print("[reverse] CH422G write failing - DO0 state unknown");
return false;
}
if (g_fail_run >= FAULT_AFTER) print("[reverse] CH422G writes OK again");
g_fail_run = 0;
g_output = on;
g_output_known = true;
return true;
}
void init(bool enabled, esp_expander::Base* expander) {
g_enabled = enabled;
g_expander = expander;
if (g_expander == nullptr) {
print("[reverse] no IO expander - DO0 cannot be driven");
return;
}
drive(false); // known state, whatever the chip held before this boot
print("[reverse] %s (DO0 follows the lever in R)%s", enabled ? "ON" : "OFF - 'reverse on' to enable",
g_output_known ? "" : " - first write failed, will retry");
}
void setEnabled(bool enabled) {
if (enabled == g_enabled) return;
g_enabled = enabled;
SettingsManager::saveReverseLightState(enabled);
}
bool isEnabled() { return g_enabled; }
bool isOn() { return g_output_known && g_output; }
/** The lights should be on: lever in R, on a live bus, key on. */
static bool wanted() {
if (g_force == FORCE_ON) return true;
if (g_force == FORCE_OFF) return false;
if (!g_enabled || !CANDriver::isActive()) return false;
driveline_t dl = CANDriver::getDriveline(); // cleared by the driver after 2 s of silence
return dl.ignition_on && dl.lever == GEAR_REVERSE;
}
void tick() {
if (millis() - g_last_poll < POLL_MS) return;
g_last_poll = millis();
if (g_force != FORCE_AUTO && millis() - g_force_since > FORCE_MAX_MS) {
g_force = FORCE_AUTO;
print("[reverse] force ended after 60 s - back to the lever");
}
bool want = wanted();
if (want != g_candidate) {
g_candidate = want;
g_candidate_ticks = 0;
}
if (g_candidate_ticks < 255) g_candidate_ticks++;
if (g_candidate_ticks >= CONFIRM && want != g_decided) {
g_decided = want;
g_switches++;
print("[reverse] lights %s (%s)", want ? "ON" : "off",
g_force == FORCE_ON ? "forced" : g_force == FORCE_OFF ? "forced off" : want ? "lever R" : "lever left R");
}
// Apply when the chip disagrees with the decision; a failed write is retried every tick.
if (!g_output_known || g_output != g_decided) drive(g_decided);
}
bool handleCommand(const char* line) {
if (strncmp(line, "reverse", 7) != 0 || (line[7] != 0 && line[7] != ' ')) return false;
const char* a = line + 7;
while (*a == ' ') a++;
if (!strcmp(a, "on")) { setEnabled(true); print("[reverse] ON (saved)"); return true; }
if (!strcmp(a, "off")) { setEnabled(false); print("[reverse] OFF (saved) - DO0 stays off"); return true; }
if (!strcmp(a, "force on")) { g_force = FORCE_ON; g_force_since = millis(); print("[reverse] FORCED ON for up to 60 s (not saved)"); return true; }
if (!strcmp(a, "force off")) { g_force = FORCE_OFF; g_force_since = millis(); print("[reverse] FORCED OFF for up to 60 s (not saved)"); return true; }
if (!strcmp(a, "force auto")) { g_force = FORCE_AUTO; print("[reverse] back to the lever"); return true; }
if (!*a || !strcmp(a, "status")) {
driveline_t dl = CANDriver::getDriveline();
print("[reverse] %s | DO0 %s | lever %c, ignition %s, CAN %s | force %s | %lu writes, %lu failed, %lu switches%s",
g_enabled ? "enabled" : "DISABLED",
!g_output_known ? "unknown" : g_output ? "ON (relay energised)" : "off",
gear_lever_char(dl.lever), dl.ignition_on ? "on" : "off", CANDriver::isActive() ? "on" : "off",
g_force == FORCE_ON ? "ON" : g_force == FORCE_OFF ? "OFF" : "auto",
(unsigned long)g_writes, (unsigned long)g_fails, (unsigned long)g_switches,
g_fail_run >= FAULT_AFTER ? " | WRITE FAULT" : "");
return true;
}
print("[reverse] usage: reverse status | on | off | force on|off|auto (DO0 = reverse-light relay)");
return true;
}
} // namespace ReverseLight
+50
View File
@@ -0,0 +1,50 @@
/*
* Reverse lights - the isolated output DO0 follows the gear lever in R
*
* The Patrol's reverse lamps are switched by a 12 V relay whose coil hangs
* between +12 V and the board's DO0 terminal (flyback diode across the coil).
* DO0 is the collector of an NPN power transistor (450 mA sink, emitter on the
* board's GND) driven through a PC817 optocoupler from the CH422G's OC0 pin
* (schematic: OC0 -> R24 100R -> PC817 LED, anode 510R to 3V3; so OC0 LOW =
* LED on = transistor on = relay on). The CH422G comes up with OC0 high and
* the panel library rewrites that default at every display init, so the
* lights are off from reset until this module says otherwise.
*
* Decision, every 100 ms: lever == R (0x1D2 byte 0) with CAN running and the
* ignition on - the same snapshot the Driveline screen shows, so the lights
* never disagree with the big letter. The CAN driver forgets the lever after
* 2 s of bus silence and on key-off, which turns the lights off as well. A
* change is applied after two equal decisions (200 ms) so a one-frame glitch
* cannot chatter the relay. `reverse force on|off` overrides for wiring tests
* (never saved, back to auto after 60 s or `reverse force auto`).
*
* The output is written through the panel library's expander object (not raw
* I2C like the diff-lock reads) so the library's cached OC register stays
* right: the backlight writes that cache back to the chip on every on/off.
*/
#pragma once
#include <Arduino.h>
namespace esp_expander { class Base; }
namespace ReverseLight {
/** Call once after DisplayInit (the expander belongs to the panel library). Drives DO0 off. */
void init(bool enabled, esp_expander::Base* expander);
/** `reverse on|off`, saved to NVS (SettingsManager). Default ON. */
void setEnabled(bool enabled);
bool isEnabled();
/** Decide + drive DO0 (10 Hz, two equal decisions before a change). Call from loop(). */
void tick();
/** What DO0 is being driven to right now (true = relay on). */
bool isOn();
/** `reverse status | on | off | force on|off|auto`. Returns true if the line was ours. */
bool handleCommand(const char* line);
} // namespace ReverseLight
+45
View File
@@ -19,6 +19,9 @@ static const char* NVS_KEY_WIFI_ENABLED = "wifi_en";
static const char* NVS_KEY_UART_ENABLED = "uart_en";
static const char* NVS_KEY_DEBUG_ENABLED = "debug_en";
static const char* NVS_KEY_CAN_ENABLED = "can_en";
static const char* NVS_KEY_DIFFLOCK_ENABLED = "difflock_en";
static const char* NVS_KEY_DIFFLOCK_INVERT = "difflock_inv";
static const char* NVS_KEY_REVLIGHT_ENABLED = "revlight_en";
// ============================================================================
// PUBLIC API IMPLEMENTATION
@@ -89,4 +92,46 @@ bool loadCANState() {
return enabled;
}
void saveDiffLockState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_DIFFLOCK_ENABLED, enabled);
preferences.end();
Serial.printf("[SettingsManager] Saved DiffLock state = %s\n", enabled ? "ON" : "OFF");
}
bool loadDiffLockState() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool enabled = preferences.getBool(NVS_KEY_DIFFLOCK_ENABLED, false); // default: OFF
preferences.end();
return enabled;
}
void saveDiffLockInvert(bool inverted) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_DIFFLOCK_INVERT, inverted);
preferences.end();
Serial.printf("[SettingsManager] Saved DiffLock polarity = %s\n", inverted ? "INVERTED" : "normal");
}
bool loadDiffLockInvert() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool inverted = preferences.getBool(NVS_KEY_DIFFLOCK_INVERT, false); // default: current = locked
preferences.end();
return inverted;
}
void saveReverseLightState(bool enabled) {
preferences.begin(NVS_NAMESPACE, false); // read-write mode
preferences.putBool(NVS_KEY_REVLIGHT_ENABLED, enabled);
preferences.end();
Serial.printf("[SettingsManager] Saved ReverseLight state = %s\n", enabled ? "ON" : "OFF");
}
bool loadReverseLightState() {
preferences.begin(NVS_NAMESPACE, true); // read-only mode
bool enabled = preferences.getBool(NVS_KEY_REVLIGHT_ENABLED, true); // default: ON (an unwired DO0 is harmless)
preferences.end();
return enabled;
}
} // namespace SettingsManager
+12
View File
@@ -66,4 +66,16 @@ void saveCANState(bool enabled);
*/
bool loadCANState();
/** Diff-lock inputs DI0/DI1 read (DiffLocks). Default OFF. */
void saveDiffLockState(bool enabled);
bool loadDiffLockState();
/** Diff-lock polarity: true = no current means locked. Default false. */
void saveDiffLockInvert(bool inverted);
bool loadDiffLockInvert();
/** Reverse-light relay on DO0 follows the lever in R (ReverseLight). Default ON. */
void saveReverseLightState(bool enabled);
bool loadReverseLightState();
} // namespace SettingsManager
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
/*
* Settings Screen Module
*
* Sidebar with three sections:
* Wi-Fi - switch, connection status, networks nearby, full-screen password
* entry; the joined network is remembered (WiFiManager)
* Updates - installed vs latest release, Check, Install behind a confirm
* dialog (Ota)
* System - CAN bus / link to Inst. Cluster / performance overlay switches,
* live link and memory figures
*
* Reached by swiping LEFT on the Driveline screen; swipe right or the
* Driveline button goes back. Built once and kept (never deleted), so nothing
* elsewhere ever holds a pointer into a destroyed screen.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
namespace SettingsScreen {
/** Build (idempotent), refresh and load. Caller holds the LVGL lock. */
void show();
/** Refresh live values while the screen is shown. Call from loop(); takes its own lock. */
void tick();
} // namespace SettingsScreen
+253
View File
@@ -0,0 +1,253 @@
/*
* Sport Screen Module Implementation - see sport_screen.h
*
* Drawn after the BMW iDrive "Sport displays" (user's photo, 2026-10-13):
* a wide dark-red band graded to bright orange at its inner edge, thin radial
* dividers cutting it into segments, white numbers inside the band, a thin red
* needle from the centre with no hub, the unit large in the middle and the
* gauge's name underneath. No digital readout in the original; a small one is
* kept under the unit because the bench has no other way to read the value.
*
* Each gauge is a dial-face IMAGE (assets/dial.png 420x420, rebuilt layer by
* layer in PhotoCraft from the photo, source assets/dial.pcraft: cells ring
* with a radial gradient and 15 dark gaps, dark ruler ring with 81 rungs, two
* bright lines, rim with a halo, 5 light spokes; sweep 230 degrees from 155)
* with an lv_meter on top that draws ONLY the numbers and the needle: its ticks
* are zero-width. The needle is an image
* (assets/needle.png, drawn in PhotoCraft 2026-10-13: tapered red body, lit
* orange-white tip with a soft glow, transparent for the first 70 px so it
* starts away from the pivot), rotated by lv_meter around its pivot at
* (0, 24): x = radius from the dial centre, the tip at 212 = the rim.
*/
#include "sport_screen.h"
#include "ui_kit.h"
#include "vehicle.h"
#include "bench_sim.h"
#include "driveline_screen.h"
#include "drivers/can_driver.h"
#include "display/lvgl_v8_port.h"
namespace SportScreen {
using namespace UiKit;
// ============================================================================
// GAUGE DEFINITIONS
// ============================================================================
// M57N (E60 530d donor): 500 Nm / 160 kW = 218 hp stock. The scales leave
// headroom for a remap; the label steps copy the photo's 5 labels per sweep.
static const int32_t TORQUE_MAX_NM = 600; // labels every 120 Nm, dividers every 12
static const int32_t POWER_MAX_HP = 320; // labels every 80 hp, dividers every 8
static const lv_coord_t GAUGE_SIZE = 420;
static const lv_coord_t GAUGE_Y = 72; // below the header / overlay band
// the dial image's geometry (assets/dial_geometry.json): rim r 210, cells 158..190
static const int32_t SWEEP_DEG = 230, START_DEG = 155; // open at the bottom, as the photo
static const lv_coord_t LABEL_R = 136; // numbers just inside the cells ring
extern "C" { LV_IMG_DECLARE(needle_img); LV_IMG_DECLARE(dial_img); } // src/assets/*.c (C linkage)
static const lv_coord_t NEEDLE_PIVOT_X = 0, NEEDLE_PIVOT_Y = 24;
#define COL_NUMBER lv_color_hex(0xF2F2F2)
typedef struct {
lv_obj_t* meter;
lv_meter_scale_t* scale;
lv_meter_indicator_t* needle;
lv_obj_t* value_lbl;
int32_t max;
int32_t shown; // needle position last written
} gauge_t;
// ============================================================================
// STATE
// ============================================================================
static lv_obj_t* g_screen = NULL;
static lv_obj_t* g_status = NULL;
static lv_obj_t* g_rpm_lbl = NULL;
static lv_obj_t* g_speed_lbl = NULL;
static gauge_t g_torque, g_power;
// ============================================================================
// BUILD
// ============================================================================
static void onBack(lv_event_t* e) {
(void)e;
DrivelineScreen::show();
}
static void onGesture(lv_event_t* e) {
(void)e;
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_RIGHT) {
lv_indev_wait_release(lv_indev_get_act());
DrivelineScreen::show();
}
}
/**
* One BMW-style gauge. `minor_ticks` dividers over the sweep (incl. both
* ends), a label every `major_every`-th divider.
*/
static void makeGauge(gauge_t& g, lv_coord_t x, const char* title, const char* unit,
int32_t max, uint16_t minor_ticks, uint16_t major_every) {
g.max = max;
g.shown = -1;
// the dial face, then the meter (numbers + needle) on top of it
lv_obj_t* face = lv_img_create(g_screen);
lv_img_set_src(face, &dial_img);
lv_obj_set_pos(face, x, GAUGE_Y);
lv_obj_clear_flag(face, LV_OBJ_FLAG_CLICKABLE);
lv_obj_t* m = lv_meter_create(g_screen);
g.meter = m;
lv_obj_set_size(m, GAUGE_SIZE, GAUGE_SIZE);
lv_obj_set_pos(m, x, GAUGE_Y);
lv_obj_set_style_bg_opa(m, LV_OPA_TRANSP, 0); // no dial face: the band floats on black
lv_obj_set_style_border_width(m, 0, 0);
lv_obj_set_style_shadow_width(m, 0, 0);
lv_obj_set_style_pad_all(m, 0, 0);
lv_obj_set_style_text_font(m, &lv_font_montserrat_24, LV_PART_TICKS);
lv_obj_set_style_text_color(m, COL_NUMBER, LV_PART_TICKS);
lv_obj_set_style_size(m, 0, LV_PART_INDICATOR); // no needle hub
lv_obj_clear_flag(m, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_clear_flag(m, LV_OBJ_FLAG_CLICKABLE); // swipes pass through to the screen
// same sweep as the image; the image carries the ticks, so the meter's are 0 px wide
// and only the major ticks' labels are drawn (placed r_out - len - gap from the centre)
g.scale = lv_meter_add_scale(m);
lv_meter_set_scale_range(m, g.scale, 0, max, SWEEP_DEG, START_DEG);
lv_meter_set_scale_ticks(m, g.scale, minor_ticks, 0, 1, lv_color_black());
lv_meter_set_scale_major_ticks(m, g.scale, major_every, 0, 1, lv_color_black(),
(GAUGE_SIZE / 2) - 1 - LABEL_R);
// the image needle: lv_meter rotates it about the pivot placed on the dial centre
g.needle = lv_meter_add_needle_img(m, g.scale, &needle_img, NEEDLE_PIVOT_X, NEEDLE_PIVOT_Y);
lv_meter_set_indicator_value(m, g.needle, 0);
// unit large in the middle, the live value small under it
lv_obj_t* u = label(m, unit, &lv_font_montserrat_48, COL_NUMBER);
lv_obj_align(u, LV_ALIGN_CENTER, 0, -14);
g.value_lbl = label(m, "--", &lv_font_montserrat_30, UI_COL_MUTED);
lv_obj_align(g.value_lbl, LV_ALIGN_CENTER, 0, 36);
// the gauge's name in the open bottom of the sweep
lv_obj_t* t = label(g_screen, title, &lv_font_montserrat_30, COL_NUMBER);
lv_obj_align_to(t, m, LV_ALIGN_BOTTOM_MID, 0, -8);
}
static void build() {
if (g_screen) return;
g_screen = screen();
lv_obj_set_style_bg_color(g_screen, lv_color_black(), 0); // the photo's black
lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL);
header(g_screen, "SPORT", onBack);
g_status = label(g_screen, "", &lv_font_montserrat_20, UI_COL_AMBER);
lv_obj_set_pos(g_status, 24, 64);
// two gauges, centred in their halves of the screen: Power left, Torque right (as in the photo)
const lv_coord_t gap = 96;
const lv_coord_t x0 = (1024 - 2 * GAUGE_SIZE - gap) / 2;
// 5 numbers per sweep (the image has 16 cells, 4 per number): 0 80 ... 320 hp, 0 120 ... 600 Nm
makeGauge(g_power, x0, "Power", "hp", POWER_MAX_HP, 5, 1);
makeGauge(g_torque, x0 + GAUGE_SIZE + gap, "Torque", "Nm", TORQUE_MAX_NM, 5, 1);
// rpm and road speed between the gauge names, bottom edge
lv_obj_t* row = box(g_screen, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_END, LV_FLEX_ALIGN_END);
lv_obj_set_style_pad_column(row, 14, 0);
lv_obj_align(row, LV_ALIGN_BOTTOM_MID, 0, -14);
label(row, "RPM", &lv_font_montserrat_14, UI_COL_MUTED);
g_rpm_lbl = label(row, "----", &lv_font_montserrat_24, UI_COL_TEXT);
lv_obj_t* sep = box(row, LV_FLEX_FLOW_ROW);
lv_obj_set_size(sep, 24, 1);
label(row, "SPEED", &lv_font_montserrat_14, UI_COL_MUTED);
g_speed_lbl = label(row, "--", &lv_font_montserrat_24, UI_COL_TEXT);
label(row, "~km/h", &lv_font_montserrat_14, UI_COL_MUTED);
}
// ============================================================================
// REFRESH
// ============================================================================
/** Move the needle only when the shown value changes (lv_meter invalidates just the needle). */
static void setGauge(gauge_t& g, int32_t v) {
if (v < 0) v = 0;
if (v > g.max) v = g.max;
if (v == g.shown) return;
g.shown = v;
lv_meter_set_indicator_value(g.meter, g.needle, v);
}
static void refresh() {
bool can_up = CANDriver::isActive() || BenchSim::isActive(); // `sim` console counts as a live bus
driveline_t dl = CANDriver::getDriveline();
bool live = can_up && dl.ignition_on;
const char* st = "";
if (BenchSim::isActive()) st = LV_SYMBOL_SETTINGS " SIMULATION - bench values from the console, not the car";
else if (!can_up) st = LV_SYMBOL_WARNING " CAN bus is off - turn it on in Settings > System";
else if (!dl.ignition_on) st = "Ignition off";
setText(g_status, st);
char buf[24];
if (!live) {
setGauge(g_torque, 0);
setGauge(g_power, 0);
setText(g_torque.value_lbl, "--");
setText(g_power.value_lbl, "--");
setText(g_rpm_lbl, "----");
setText(g_speed_lbl, "--");
return;
}
// torque: TORQ_AVL is signed (negative on overrun); the gauge floors at 0.
// Only while the engine runs: with the key on and the engine off the field
// holds a junk value (812 Nm on Patrol 2, 245 on Patrol 1 - captures 2026-10-18).
bool running = (dl.engine_run_state == ENGINE_RUN_RUNNING);
int32_t nm = running ? dl.engine_torque_x10 / 10 : 0;
setGauge(g_torque, nm);
if (running) snprintf(buf, sizeof(buf), "%ld", (long)(nm < 0 ? 0 : nm));
else snprintf(buf, sizeof(buf), "--");
setText(g_torque.value_lbl, buf);
uint16_t hp_x10 = running ? Vehicle::powerHpX10(dl.engine_torque_x10, dl.engine_rpm) : 0;
setGauge(g_power, hp_x10 / 10);
if (running) snprintf(buf, sizeof(buf), "%u", hp_x10 / 10);
else snprintf(buf, sizeof(buf), "--");
setText(g_power.value_lbl, buf);
snprintf(buf, sizeof(buf), "%u", dl.engine_rpm);
setText(g_rpm_lbl, buf);
uint16_t kmh_x10 = Vehicle::speedKmhX10(dl.output_shaft_raw);
snprintf(buf, sizeof(buf), "%u", kmh_x10 / 10);
setText(g_speed_lbl, buf);
}
// ============================================================================
// PUBLIC API
// ============================================================================
void show() {
build();
refresh();
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
}
void tick() {
if (g_screen == NULL || lv_scr_act() != g_screen) return;
static uint32_t last = 0;
if (millis() - last < 100) return; // 10 Hz, like the Driveline
last = millis();
lvgl_port_lock(-1);
refresh();
lvgl_port_unlock();
}
} // namespace SportScreen
+28
View File
@@ -0,0 +1,28 @@
/*
* Sport Screen Module
*
* BMW-style "Sport displays": two round gauges, engine torque (Nm, 0x0A8
* TORQ_AVL straight from the bus) and engine power (hp, computed:
* P(W) = Nm x rpm / 9.5488, hp = W / 745.70 - see Vehicle::powerHpX10()).
* Each gauge has an arc fill, a needle, a thin peak needle that holds for a
* few seconds, and the value in the gap at the bottom. Engine rpm and the
* computed road speed sit under the gauges.
*
* Opened from the "Sport" button on the Driveline screen; the Driveline button
* or a right swipe goes back. Built once and kept, like every screen.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
namespace SportScreen {
/** Build (idempotent) and load. Caller holds the LVGL lock. */
void show();
/** Refresh the gauges while shown (10 Hz). Call from loop(); takes its own lock. */
void tick();
} // namespace SportScreen
+147
View File
@@ -0,0 +1,147 @@
/*
* Status Overlay implementation. See status_overlay.h.
*/
#include "status_overlay.h"
#include "wifi_manager.h"
#include "uart_manager.h"
#include "ui_kit.h"
#include "drivers/can_driver.h"
#include "display/lvgl_v8_port.h"
#include "protocol/automotive_data.h"
#include <lvgl.h>
namespace StatusOverlay {
#define BLINK_MS 500
static lv_obj_t* g_wifi = NULL;
static lv_obj_t* g_banner = NULL;
static bool g_banner_shown = false;
static const lv_color_t COL_RED_HI = lv_color_hex(0xFF3B30);
static const lv_color_t COL_RED_LO = lv_color_hex(0x8F1A14);
static void setText(lv_obj_t* lbl, const char* text) {
const char* cur = lv_label_get_text(lbl);
if (cur != NULL && strcmp(cur, text) == 0) return;
lv_label_set_text(lbl, text);
}
static void setTextColour(lv_obj_t* o, lv_color_t c) {
if (lv_color_to32(lv_obj_get_style_text_color(o, 0)) != lv_color_to32(c)) lv_obj_set_style_text_color(o, c, 0);
}
static void setBgColour(lv_obj_t* o, lv_color_t c) {
if (lv_color_to32(lv_obj_get_style_bg_color(o, 0)) != lv_color_to32(c)) lv_obj_set_style_bg_color(o, c, 0);
}
void init() {
lvgl_port_lock(-1);
// Wi-Fi chip, fixed width so the header layout never moves
g_wifi = lv_label_create(lv_layer_top());
lv_obj_set_width(g_wifi, 150);
lv_label_set_long_mode(g_wifi, LV_LABEL_LONG_DOT);
lv_label_set_text(g_wifi, LV_SYMBOL_WIFI " --");
lv_obj_set_style_text_font(g_wifi, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_wifi, UI_COL_MUTED, 0);
lv_obj_set_style_bg_color(g_wifi, UI_COL_PANEL, 0);
lv_obj_set_style_bg_opa(g_wifi, LV_OPA_COVER, 0);
lv_obj_set_style_radius(g_wifi, 13, 0);
lv_obj_set_style_pad_hor(g_wifi, 10, 0);
lv_obj_set_style_pad_ver(g_wifi, 5, 0);
lv_obj_align(g_wifi, LV_ALIGN_TOP_RIGHT, -16, 25);
// Alert banner, top centre
g_banner = lv_label_create(lv_layer_top());
lv_label_set_text(g_banner, "");
lv_obj_set_style_text_font(g_banner, &lv_font_montserrat_20, 0);
lv_obj_set_style_text_color(g_banner, lv_color_white(), 0);
lv_obj_set_style_bg_color(g_banner, COL_RED_HI, 0);
lv_obj_set_style_bg_opa(g_banner, LV_OPA_COVER, 0);
lv_obj_set_style_radius(g_banner, 10, 0);
lv_obj_set_style_pad_hor(g_banner, 18, 0);
lv_obj_set_style_pad_ver(g_banner, 8, 0);
lv_obj_align(g_banner, LV_ALIGN_TOP_MID, -20, 10);
lv_obj_add_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
lvgl_port_unlock();
}
static void refreshWifi() {
WiFiManager::status_t w = WiFiManager::getStatus();
char txt[64];
lv_color_t col = UI_COL_MUTED;
switch (w.link) {
case WiFiManager::LINK_CONNECTED: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " %s", w.ssid); col = UI_COL_TEXT; break;
case WiFiManager::LINK_CONNECTING: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " joining..."); col = UI_COL_ACCENT; break;
case WiFiManager::LINK_FAILED: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " failed"); col = UI_COL_AMBER; break;
case WiFiManager::LINK_OFF: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " off"); break;
default: snprintf(txt, sizeof(txt), LV_SYMBOL_WIFI " not connected"); break;
}
setText(g_wifi, txt);
setTextColour(g_wifi, col);
}
static void refreshAlerts() {
bool can_up = CANDriver::isActive();
driveline_t dl = CANDriver::getDriveline();
uint16_t alerts = 0;
uint8_t flags = 0;
int16_t coolant = 0, gearbox = 0;
uint16_t batt = 0;
if (xSemaphoreTake(UARTManager::g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
alerts = UARTManager::g_automotive_data.alerts;
flags = UARTManager::g_automotive_data.valid_flags;
coolant = UARTManager::g_automotive_data.coolant_temp;
gearbox = UARTManager::g_automotive_data.gearbox_oil_temp;
batt = UARTManager::g_automotive_data.battery_voltage;
xSemaphoreGive(UARTManager::g_data_mutex);
} else {
return;
}
bool live = can_up && dl.ignition_on && (flags & VALID_FLAG_ALERTS);
bool red = live && (alerts & ALERTS_RED);
bool amber = live && !red && (alerts & ALERTS_AMBER);
bool show = red || amber;
if (show != g_banner_shown) {
g_banner_shown = show;
if (show) lv_obj_clear_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(g_banner, LV_OBJ_FLAG_HIDDEN);
}
if (!show) return;
char txt[64];
if (alerts & ALERT_COOLANT_HOT) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " COOLANT %d °C HOT", coolant / 10);
else if (alerts & ALERT_GEARBOX_HOT) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEARBOX OIL %d °C HOT", gearbox / 10);
else if (alerts & ALERT_GEAR_MISMATCH) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEAR MISMATCH");
else if (alerts & ALERT_BATTERY_LOW) snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " BATTERY %d.%02d V LOW", batt / 100, batt % 100);
else snprintf(txt, sizeof(txt), LV_SYMBOL_WARNING " GEARBOX COOLING");
setText(g_banner, txt);
if (red) {
bool hi = (millis() / BLINK_MS) & 1;
setBgColour(g_banner, hi ? COL_RED_HI : COL_RED_LO);
setTextColour(g_banner, lv_color_white());
} else {
setBgColour(g_banner, UI_COL_AMBER);
setTextColour(g_banner, lv_color_hex(0x1A1200));
}
}
void tick() {
if (g_wifi == NULL) return;
static uint32_t last = 0;
if (millis() - last < 250) return;
last = millis();
lvgl_port_lock(-1);
refreshWifi();
refreshAlerts();
lvgl_port_unlock();
}
} // namespace StatusOverlay
+26
View File
@@ -0,0 +1,26 @@
/*
* Status Overlay - what every screen shows, on lv_layer_top():
*
* top-right Wi-Fi chip: off / not connected / joining / <network>
* top-centre ALERT BANNER: red and blinking (2 Hz) while any red alert from
* Tunables' thresholds is on (coolant hot, gearbox oil hot,
* gear mismatch, battery low), steady amber while the gearbox
* asks for cooling. Hidden with CAN off or ignition off.
*
* Both are labels, so they never take touches from the screen below. tick()
* runs from loop() and only touches an object when its text/colour changes.
*/
#pragma once
#include <Arduino.h>
namespace StatusOverlay {
/** Build the two labels. Call after DisplayInit::init(), before the screens tick. */
void init();
/** Refresh from WiFiManager / the shared automotive data. Call from loop(). */
void tick();
} // namespace StatusOverlay
+32 -4
View File
@@ -43,6 +43,18 @@ static void save() {
prefs.end();
}
// Every flash write briefly stalls the PSRAM-fed RGB panel (flicker), so edits
// are applied + pushed to B at once but written to NVS only after the user
// stops tapping (SAVE_IDLE_MS), on leaving the Tuning screen, or before reboot.
static const uint32_t SAVE_IDLE_MS = 3000;
static bool g_dirty = false;
static uint32_t g_dirty_ms = 0;
static void markDirty() { // call with the mutex held
g_dirty = true;
g_dirty_ms = millis();
}
static bool load() {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, true);
@@ -90,6 +102,7 @@ static void help() {
print("cfg override off | rpm <n> | duty <n> | both <rpm> <duty>");
print("cfg reset back to defaults");
print("diag help OBD-II diagnostic probe (transmits on the bus)");
print("link help Inst. Cluster: pairing, credentials, its updates");
}
static bool setField(const char* name, long v) {
@@ -113,7 +126,7 @@ static bool setField(const char* name, long v) {
if (ok) {
g_cfg.cfg_version++;
if (g_cfg.cfg_version == 0) g_cfg.cfg_version = 1;
save();
markDirty();
}
unlock();
return ok;
@@ -159,7 +172,7 @@ void set(const link_config_t& cfg) {
uint8_t v = g_cfg.cfg_version + 1;
g_cfg = cfg;
g_cfg.cfg_version = v ? v : 1;
save();
markDirty();
unlock();
}
@@ -168,7 +181,7 @@ void resetDefaults() {
uint8_t v = g_cfg.cfg_version + 1;
link_config_defaults(&g_cfg);
g_cfg.cfg_version = v ? v : 1;
save();
markDirty();
unlock();
}
@@ -203,7 +216,7 @@ bool handleCommand(const char* line) {
if (!strcmp(argv[1], "set") && argc == 4) {
long v = strtol(argv[3], NULL, 0);
if (setField(argv[2], v)) {
print("[cfg] %s = %ld (version %u, saved)", argv[2], v, version());
print("[cfg] %s = %ld (version %u, saved to NVS in 3 s)", argv[2], v, version());
} else {
print("[cfg] unknown field '%s'", argv[2]);
help();
@@ -247,7 +260,22 @@ void setExtraCommandHandler(bool (*handler)(const char* line)) {
g_extra_handler = handler;
}
void flush() {
lock();
if (g_dirty) {
save();
g_dirty = false;
}
unlock();
}
bool isDirty() {
return g_dirty;
}
void pollSerial() {
if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush();
while (Serial.available()) {
char c = (char)Serial.read();
if (c == '\r' || c == '\n') {
+11 -1
View File
@@ -1,7 +1,7 @@
/*
* Tunables Module
*
* Owns the link_config_t that Controller A pushes to Controller B: Patrol gauge
* Owns the link_config_t that Main CTRL pushes to Inst. Cluster: Patrol gauge
* calibration (tach pulses/rev, coolant PWM law) and the alert thresholds A
* evaluates. Persisted in NVS. Editable at runtime over the USB serial console
* ("cfg help") until a settings-screen UI exists.
@@ -58,6 +58,16 @@ bool handleCommand(const char* line);
*/
void pollSerial();
/**
* Write pending edits to NVS now. Edits are otherwise saved SAVE_IDLE_MS after
* the last change (each flash write flickers the RGB panel). Call before a
* reboot or when leaving the Tuning screen.
*/
void flush();
/** True while edits are waiting for their deferred NVS write. */
bool isDirty();
/**
* Register a second console command handler (e.g. DiagProbe::handleCommand)
* that gets lines `cfg` does not recognise. Returns true if it consumed the line.
+342 -359
View File
@@ -1,35 +1,25 @@
/*
* Gauge Tuning Screen Module Implementation
*
* Four tabs (Tachometer / Coolant gauge / Alerts / Simulation), one value per
* row with a plain-language hint, car-sized -/+ buttons (hold to repeat,
* speeding up the longer you hold). Tabs are plain buttons + hidden panels:
* no sliding tabview animation, which re-renders the whole panel per frame.
*/
#include "tuning_screen.h"
#include "tunables.h"
#include "ui_kit.h"
#include "driveline_screen.h"
#include "display/lvgl_v8_port.h"
#include "esp_log.h"
extern "C"
{
#include "ui.h"
}
namespace TuningScreen
{
using namespace UiKit;
// ============================================================================
// THEME
// ============================================================================
#define COL_BG lv_color_hex(0x101418)
#define COL_PANEL lv_color_hex(0x1B2128)
#define COL_TEXT lv_color_hex(0xE8EDF2)
#define COL_MUTED lv_color_hex(0x6E7B88)
#define COL_ACCENT lv_color_hex(0x3DA9FC)
#define COL_OK lv_color_hex(0x3DD68C)
#define COL_WARN lv_color_hex(0xE5484D)
// ============================================================================
// FIELD TABLE — one row per numeric tunable
// FIELD TABLE - one row per numeric tunable
// ============================================================================
typedef enum
@@ -48,11 +38,14 @@ namespace TuningScreen
F_COUNT
} field_t;
typedef enum { TAB_TACH, TAB_COOLANT, TAB_ALERTS, TAB_SIM, TAB_COUNT } tab_t;
typedef struct
{
field_t id;
tab_t tab;
const char *name;
const char *unit;
const char *hint;
int32_t step;
int32_t min;
int32_t max;
@@ -60,47 +53,37 @@ namespace TuningScreen
} row_t;
static row_t g_rows[F_COUNT] = {
{F_TACH_PPR, "Pulses / rev", "", 1, 1, 32, NULL},
{F_TACH_TRIM, "Trim", "%", 1, -50, 50, NULL},
{F_TACH_MAX_HZ, "Max output", "Hz", 10, 0, 5000, NULL},
{F_TEMP_HZ, "PWM frequency", "Hz", 50, 20, 20000, NULL},
{F_TEMP_SLOPE, "Slope", "x100", 5, 0, 5000, NULL},
{F_TEMP_OFFSET, "Offset", "", 1, -1000, 1000, NULL},
{F_TEMP_MIN, "Min temp", "C", 1, -50, 200, NULL},
{F_TEMP_DUTY_MAX, "Duty clamp", "", 5, 0, 255, NULL},
{F_COOLANT_HOT, "Coolant hot", "C", 1, 0, 200, NULL},
{F_GEARBOX_HOT, "Gearbox hot", "C", 1, 0, 200, NULL},
{F_BATT_LOW, "Battery low", "x0.01V", 10, 0, 3000, NULL},
{F_TACH_PPR, TAB_TACH, "Pulses per revolution", "Pulses per engine revolution the Patrol tach expects", 1, 1, 32, NULL},
{F_TACH_TRIM, TAB_TACH, "Trim", "Fine correction if the needle reads high or low", 1, -50, 50, NULL},
{F_TACH_MAX_HZ, TAB_TACH, "Maximum output", "Highest tach frequency sent (0 = no limit)", 10, 0, 5000, NULL},
{F_TEMP_HZ, TAB_COOLANT, "PWM frequency", "Drive frequency of the coolant gauge signal", 50, 20, 20000, NULL},
{F_TEMP_SLOPE, TAB_COOLANT, "Slope", "Duty added per \xC2\xB0" "C of coolant", 5, 0, 5000, NULL},
{F_TEMP_OFFSET, TAB_COOLANT, "Offset", "Duty at 0 \xC2\xB0" "C (duty = slope x temp + offset)", 1, -1000, 1000, NULL},
{F_TEMP_MIN, TAB_COOLANT, "Minimum temperature", "Needle stays at rest below this", 1, -50, 200, NULL},
{F_TEMP_DUTY_MAX, TAB_COOLANT, "Duty limit", "Highest duty sent (255 = full scale)", 5, 0, 255, NULL},
{F_COOLANT_HOT, TAB_ALERTS, "Coolant too hot", "Alarm on Inst. Cluster at or above this temperature", 1, 0, 200, NULL},
{F_GEARBOX_HOT, TAB_ALERTS, "Gearbox oil too hot", "Alarm on Inst. Cluster at or above this temperature", 1, 0, 200, NULL},
{F_BATT_LOW, TAB_ALERTS, "Battery low", "Alarm on Inst. Cluster below this voltage", 10, 0, 3000, NULL},
};
static const char *TAB_NAMES[TAB_COUNT] = {"Tachometer", "Coolant gauge", "Alerts", "Simulation"};
static int32_t getField(const link_config_t &c, field_t f)
{
switch (f)
{
case F_TACH_PPR:
return c.tach_ppr;
case F_TACH_TRIM:
return c.tach_trim_pct;
case F_TACH_MAX_HZ:
return c.tach_max_hz;
case F_TEMP_HZ:
return c.temp_pwm_hz;
case F_TEMP_SLOPE:
return c.temp_slope_x100;
case F_TEMP_OFFSET:
return c.temp_offset;
case F_TEMP_MIN:
return c.temp_min_c;
case F_TEMP_DUTY_MAX:
return c.temp_duty_max;
case F_COOLANT_HOT:
return c.coolant_hot_c;
case F_GEARBOX_HOT:
return c.gearbox_hot_c;
case F_BATT_LOW:
return c.battery_low_x100;
default:
return 0;
case F_TACH_PPR: return c.tach_ppr;
case F_TACH_TRIM: return c.tach_trim_pct;
case F_TACH_MAX_HZ: return c.tach_max_hz;
case F_TEMP_HZ: return c.temp_pwm_hz;
case F_TEMP_SLOPE: return c.temp_slope_x100;
case F_TEMP_OFFSET: return c.temp_offset;
case F_TEMP_MIN: return c.temp_min_c;
case F_TEMP_DUTY_MAX: return c.temp_duty_max;
case F_COOLANT_HOT: return c.coolant_hot_c;
case F_GEARBOX_HOT: return c.gearbox_hot_c;
case F_BATT_LOW: return c.battery_low_x100;
default: return 0;
}
}
@@ -108,41 +91,36 @@ namespace TuningScreen
{
switch (f)
{
case F_TACH_PPR:
c.tach_ppr = (uint8_t)v;
break;
case F_TACH_TRIM:
c.tach_trim_pct = (int8_t)v;
break;
case F_TACH_MAX_HZ:
c.tach_max_hz = (uint16_t)v;
break;
case F_TEMP_HZ:
c.temp_pwm_hz = (uint16_t)v;
break;
case F_TEMP_SLOPE:
c.temp_slope_x100 = (uint16_t)v;
break;
case F_TEMP_OFFSET:
c.temp_offset = (int16_t)v;
break;
case F_TACH_PPR: c.tach_ppr = (uint8_t)v; break;
case F_TACH_TRIM: c.tach_trim_pct = (int8_t)v; break;
case F_TACH_MAX_HZ: c.tach_max_hz = (uint16_t)v; break;
case F_TEMP_HZ: c.temp_pwm_hz = (uint16_t)v; break;
case F_TEMP_SLOPE: c.temp_slope_x100 = (uint16_t)v; break;
case F_TEMP_OFFSET: c.temp_offset = (int16_t)v; break;
case F_TEMP_MIN: c.temp_min_c = (int16_t)v; break;
case F_TEMP_DUTY_MAX: c.temp_duty_max = (uint8_t)v; break;
case F_COOLANT_HOT: c.coolant_hot_c = (int16_t)v; break;
case F_GEARBOX_HOT: c.gearbox_hot_c = (int16_t)v; break;
case F_BATT_LOW: c.battery_low_x100 = (uint16_t)v; break;
default: break;
}
}
static void formatValue(field_t f, int32_t v, char *out, size_t n)
{
switch (f)
{
case F_TACH_TRIM: snprintf(out, n, "%+ld %%", (long)v); break;
case F_TACH_MAX_HZ: if (v == 0) snprintf(out, n, "no limit"); else snprintf(out, n, "%ld Hz", (long)v); break;
case F_TEMP_HZ: snprintf(out, n, "%ld Hz", (long)v); break;
case F_TEMP_SLOPE: snprintf(out, n, "%ld.%02ld", (long)(v / 100), (long)labs(v % 100)); break;
case F_TEMP_OFFSET: snprintf(out, n, "%+ld", (long)v); break;
case F_TEMP_MIN:
c.temp_min_c = (int16_t)v;
break;
case F_TEMP_DUTY_MAX:
c.temp_duty_max = (uint8_t)v;
break;
case F_COOLANT_HOT:
c.coolant_hot_c = (int16_t)v;
break;
case F_GEARBOX_HOT:
c.gearbox_hot_c = (int16_t)v;
break;
case F_BATT_LOW:
c.battery_low_x100 = (uint16_t)v;
break;
default:
break;
case F_GEARBOX_HOT: snprintf(out, n, "%ld \xC2\xB0" "C", (long)v); break;
case F_TEMP_DUTY_MAX: snprintf(out, n, "%ld / 255", (long)v); break;
case F_BATT_LOW: snprintf(out, n, "%ld.%02ld V", (long)(v / 100), (long)(v % 100)); break;
default: snprintf(out, n, "%ld", (long)v); break;
}
}
@@ -151,6 +129,12 @@ namespace TuningScreen
// ============================================================================
static lv_obj_t *g_screen = NULL;
static lv_obj_t *g_tab_btn[TAB_COUNT];
static lv_obj_t *g_tab_page[TAB_COUNT];
static tab_t g_tab = TAB_TACH;
static lv_obj_t *g_reset_btn = NULL;
static lv_obj_t *g_sim_chip = NULL;
static lv_obj_t *g_save_lbl = NULL;
static lv_obj_t *g_tach_en_sw = NULL;
static lv_obj_t *g_temp_en_sw = NULL;
static lv_obj_t *g_ovr_rpm_sw = NULL;
@@ -159,32 +143,34 @@ namespace TuningScreen
static lv_obj_t *g_ovr_duty_sl = NULL;
static lv_obj_t *g_ovr_rpm_lbl = NULL;
static lv_obj_t *g_ovr_duty_lbl = NULL;
static lv_obj_t *g_status_lbl = NULL;
static uint8_t g_shown_version = 0;
static bool g_refreshing = false; // suppress event handlers while we set widget values
static uint16_t g_repeats = 0; // long-press repeat count of the button being held
static const int32_t RPM_MAX = 6000, RPM_STEP = 100;
static const int32_t DUTY_MAX = 255, DUTY_STEP = 5;
// ============================================================================
// HELPERS
// REFRESH
// ============================================================================
static void formatValue(const row_t &r, int32_t v, char *out, size_t n)
static void refreshSaveState()
{
if (r.id == F_TEMP_SLOPE)
{
snprintf(out, n, "%ld.%02ld", (long)(v / 100), (long)labs(v % 100));
}
else if (r.id == F_BATT_LOW)
{
snprintf(out, n, "%ld.%02ld V", (long)(v / 100), (long)(v % 100));
}
else if (r.unit[0])
{
snprintf(out, n, "%ld %s", (long)v, r.unit);
}
link_config_t c = Tunables::get();
const char *txt;
lv_color_t col = UI_COL_MUTED;
if (g_tab == TAB_SIM)
txt = "Simulation values are never saved - a restart returns to live data";
else if (Tunables::isDirty())
txt = "Saving...";
else
{
snprintf(out, n, "%ld", (long)v);
txt = LV_SYMBOL_OK " All changes saved";
col = UI_COL_OK;
}
setText(g_save_lbl, txt);
setTextColor(g_save_lbl, col);
setVisible(g_sim_chip, c.override_mode != 0);
}
static void refreshFromTunables()
@@ -192,58 +178,38 @@ namespace TuningScreen
link_config_t c = Tunables::get();
g_refreshing = true;
char buf[24];
char buf[32];
for (int i = 0; i < F_COUNT; i++)
{
if (g_rows[i].value_lbl == NULL)
continue;
formatValue(g_rows[i], getField(c, g_rows[i].id), buf, sizeof(buf));
lv_label_set_text(g_rows[i].value_lbl, buf);
formatValue(g_rows[i].id, getField(c, g_rows[i].id), buf, sizeof(buf));
setText(g_rows[i].value_lbl, buf);
}
auto setSw = [](lv_obj_t *sw, bool on)
{
if (sw == NULL)
return;
if (on)
lv_obj_add_state(sw, LV_STATE_CHECKED);
else
lv_obj_clear_state(sw, LV_STATE_CHECKED);
};
setSw(g_tach_en_sw, c.out_enable & OUT_ENABLE_TACH);
setSw(g_temp_en_sw, c.out_enable & OUT_ENABLE_TEMP);
setSw(g_ovr_rpm_sw, c.override_mode & OVERRIDE_TACH);
setSw(g_ovr_duty_sw, c.override_mode & OVERRIDE_TEMP);
setChecked(g_tach_en_sw, c.out_enable & OUT_ENABLE_TACH);
setChecked(g_temp_en_sw, c.out_enable & OUT_ENABLE_TEMP);
setChecked(g_ovr_rpm_sw, c.override_mode & OVERRIDE_TACH);
setChecked(g_ovr_duty_sw, c.override_mode & OVERRIDE_TEMP);
if (g_ovr_rpm_sl)
if (g_ovr_rpm_sl && !lv_obj_has_state(g_ovr_rpm_sl, LV_STATE_PRESSED))
lv_slider_set_value(g_ovr_rpm_sl, c.override_rpm, LV_ANIM_OFF);
if (g_ovr_duty_sl)
if (g_ovr_duty_sl && !lv_obj_has_state(g_ovr_duty_sl, LV_STATE_PRESSED))
lv_slider_set_value(g_ovr_duty_sl, c.override_duty, LV_ANIM_OFF);
if (g_ovr_rpm_lbl)
{
snprintf(buf, sizeof(buf), "%u rpm", c.override_rpm);
lv_label_set_text(g_ovr_rpm_lbl, buf);
}
if (g_ovr_duty_lbl)
{
snprintf(buf, sizeof(buf), "%u / 255", c.override_duty);
lv_label_set_text(g_ovr_duty_lbl, buf);
}
if (g_status_lbl)
{
snprintf(buf, sizeof(buf), "config v%u", c.cfg_version);
lv_label_set_text(g_status_lbl, buf);
lv_obj_set_style_text_color(g_status_lbl, c.override_mode ? COL_WARN : COL_MUTED, 0);
}
snprintf(buf, sizeof(buf), "%u rpm", c.override_rpm);
setText(g_ovr_rpm_lbl, buf);
snprintf(buf, sizeof(buf), "%u / 255", c.override_duty);
setText(g_ovr_duty_lbl, buf);
refreshSaveState();
g_shown_version = c.cfg_version;
g_refreshing = false;
}
// ---- event handlers --------------------------------------------------------
// ============================================================================
// EVENT HANDLERS
// ============================================================================
// user_data = row pointer; the button's own user data (+1/-1) is in lv_event_get_user_data
typedef struct
{
row_t *row;
@@ -251,29 +217,44 @@ namespace TuningScreen
} step_ctx_t;
static step_ctx_t g_step_ctx[F_COUNT][2];
/** 1x for taps and the first second of a hold, then 5x, then 10x. */
static int32_t holdMultiplier(lv_event_code_t code)
{
if (code == LV_EVENT_PRESSED)
{
g_repeats = 0;
return 0;
}
if (code == LV_EVENT_LONG_PRESSED_REPEAT)
{
g_repeats++;
return g_repeats > 25 ? 10 : g_repeats > 10 ? 5 : 1;
}
return 1; // CLICKED
}
static void onStep(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
if (code != LV_EVENT_CLICKED && code != LV_EVENT_LONG_PRESSED_REPEAT)
int32_t mult = holdMultiplier(code);
if (mult == 0)
return;
if (code == LV_EVENT_CLICKED && g_repeats > 0)
return; // end of a hold, already applied
step_ctx_t *ctx = (step_ctx_t *)lv_event_get_user_data(e);
link_config_t c = Tunables::get();
int32_t v = getField(c, ctx->row->id) + ctx->dir * ctx->row->step;
if (v < ctx->row->min)
v = ctx->row->min;
if (v > ctx->row->max)
v = ctx->row->max;
int32_t v = getField(c, ctx->row->id) + ctx->dir * ctx->row->step * mult;
v = constrain(v, ctx->row->min, ctx->row->max);
setField(c, ctx->row->id, v);
Tunables::set(c); // saves + bumps version -> CONFIG frame goes out
Tunables::set(c); // bumps version -> CONFIG frame goes out; NVS write after 3 s idle
refreshFromTunables();
}
static void onEnableSwitch(lv_event_t *e)
{
if (g_refreshing || lv_event_get_code(e) != LV_EVENT_VALUE_CHANGED)
if (g_refreshing)
return;
lv_obj_t *sw = lv_event_get_target(e);
bool on = lv_obj_has_state(sw, LV_STATE_CHECKED);
bool on = lv_obj_has_state(lv_event_get_target(e), LV_STATE_CHECKED);
uint8_t bit = (uint8_t)(uintptr_t)lv_event_get_user_data(e);
link_config_t c = Tunables::get();
c.out_enable = on ? (c.out_enable | bit) : (c.out_enable & ~bit);
@@ -283,23 +264,21 @@ namespace TuningScreen
static void pushOverride()
{
link_config_t c = Tunables::get();
uint8_t mode = 0;
if (g_ovr_rpm_sw && lv_obj_has_state(g_ovr_rpm_sw, LV_STATE_CHECKED))
if (lv_obj_has_state(g_ovr_rpm_sw, LV_STATE_CHECKED))
mode |= OVERRIDE_TACH;
if (g_ovr_duty_sw && lv_obj_has_state(g_ovr_duty_sw, LV_STATE_CHECKED))
if (lv_obj_has_state(g_ovr_duty_sw, LV_STATE_CHECKED))
mode |= OVERRIDE_TEMP;
uint16_t rpm = g_ovr_rpm_sl ? (uint16_t)lv_slider_get_value(g_ovr_rpm_sl) : c.override_rpm;
uint8_t duty = g_ovr_duty_sl ? (uint8_t)lv_slider_get_value(g_ovr_duty_sl) : c.override_duty;
Tunables::setOverride(mode, rpm, duty); // pushed to B, never saved
Tunables::setOverride(mode, (uint16_t)lv_slider_get_value(g_ovr_rpm_sl),
(uint8_t)lv_slider_get_value(g_ovr_duty_sl)); // pushed to B, never saved
refreshFromTunables();
}
static void onOverrideSwitch(lv_event_t *e)
{
if (g_refreshing || lv_event_get_code(e) != LV_EVENT_VALUE_CHANGED)
return;
pushOverride();
(void)e;
if (!g_refreshing)
pushOverride();
}
static void onOverrideSlider(lv_event_t *e)
@@ -307,21 +286,21 @@ namespace TuningScreen
if (g_refreshing)
return;
lv_event_code_t code = lv_event_get_code(e);
// Update the readout while dragging; push to B on release so we don't
// flood the link with CONFIG frames at touch rate.
lv_obj_t *sl = lv_event_get_target(e);
// Readout follows the finger; push to B on release so we don't flood
// the link with CONFIG frames at touch rate.
if (code == LV_EVENT_VALUE_CHANGED)
{
char buf[24];
lv_obj_t *sl = lv_event_get_target(e);
if (sl == g_ovr_rpm_sl && g_ovr_rpm_lbl)
if (sl == g_ovr_rpm_sl)
{
snprintf(buf, sizeof(buf), "%d rpm", (int)lv_slider_get_value(sl));
lv_label_set_text(g_ovr_rpm_lbl, buf);
setText(g_ovr_rpm_lbl, buf);
}
else if (sl == g_ovr_duty_sl && g_ovr_duty_lbl)
else
{
snprintf(buf, sizeof(buf), "%d / 255", (int)lv_slider_get_value(sl));
lv_label_set_text(g_ovr_duty_lbl, buf);
setText(g_ovr_duty_lbl, buf);
}
}
else if (code == LV_EVENT_RELEASED)
@@ -330,249 +309,252 @@ namespace TuningScreen
}
}
/** Fine -/+ next to a slider; user data = +/-1, slider picked by the button's parent row. */
static void onSimStep(lv_event_t *e)
{
lv_event_code_t code = lv_event_get_code(e);
int32_t mult = holdMultiplier(code);
if (mult == 0 || (code == LV_EVENT_CLICKED && g_repeats > 0))
return;
int dir = (int)(intptr_t)lv_event_get_user_data(e);
lv_obj_t *btn = lv_event_get_target(e);
bool rpm = lv_obj_get_parent(btn) == lv_obj_get_parent(g_ovr_rpm_sl);
lv_obj_t *sl = rpm ? g_ovr_rpm_sl : g_ovr_duty_sl;
int32_t v = lv_slider_get_value(sl) + dir * (rpm ? RPM_STEP : DUTY_STEP) * mult;
lv_slider_set_value(sl, constrain(v, 0, rpm ? RPM_MAX : DUTY_MAX), LV_ANIM_OFF);
pushOverride();
}
static void onBack(lv_event_t *e)
{
if (lv_event_get_code(e) != LV_EVENT_CLICKED)
return;
(void)e;
Tunables::flush(); // write pending edits now rather than after the idle delay
DrivelineScreen::show();
}
static void onGesture(lv_event_t *e)
{
(void)e;
if (lv_indev_get_gesture_dir(lv_indev_get_act()) == LV_DIR_LEFT)
{
lv_indev_wait_release(lv_indev_get_act());
Tunables::flush();
DrivelineScreen::show();
}
}
static void onResetConfirmed(bool ok, void *user)
{
if (!ok)
return;
tab_t tab = (tab_t)(uintptr_t)user;
link_config_t d, c = Tunables::get();
link_config_defaults(&d);
for (int i = 0; i < F_COUNT; i++)
if (g_rows[i].tab == tab)
setField(c, g_rows[i].id, getField(d, g_rows[i].id));
uint8_t bit = tab == TAB_TACH ? OUT_ENABLE_TACH : tab == TAB_COOLANT ? OUT_ENABLE_TEMP : 0;
c.out_enable = (c.out_enable & ~bit) | (d.out_enable & bit);
Tunables::set(c);
refreshFromTunables();
}
static void onReset(lv_event_t *e)
{
if (lv_event_get_code(e) != LV_EVENT_CLICKED)
return;
Tunables::resetDefaults();
refreshFromTunables();
(void)e;
char title[64];
snprintf(title, sizeof(title), "Reset %s?", TAB_NAMES[g_tab]);
confirm(title, "Every value on this tab goes back to its default. The other tabs are not touched.",
"Reset", onResetConfirmed, (void *)(uintptr_t)g_tab);
}
// ---- builders --------------------------------------------------------------
static lv_obj_t *makePanel(lv_obj_t *parent, const char *title, lv_coord_t w)
static void selectTab(tab_t t)
{
lv_obj_t *p = lv_obj_create(parent);
lv_obj_set_size(p, w, LV_SIZE_CONTENT);
lv_obj_set_style_bg_color(p, COL_PANEL, 0);
lv_obj_set_style_border_width(p, 0, 0);
lv_obj_set_style_radius(p, 12, 0);
lv_obj_set_style_pad_all(p, 12, 0);
lv_obj_set_style_pad_row(p, 6, 0);
lv_obj_set_flex_flow(p, LV_FLEX_FLOW_COLUMN);
lv_obj_clear_flag(p, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *t = lv_label_create(p);
lv_label_set_text(t, title);
lv_obj_set_style_text_font(t, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(t, COL_ACCENT, 0);
lv_obj_set_style_pad_bottom(t, 4, 0);
return p;
g_tab = t;
for (int i = 0; i < TAB_COUNT; i++)
{
bool on = (i == t);
setVisible(g_tab_page[i], on);
lv_obj_set_style_bg_color(g_tab_btn[i], on ? UI_COL_ACCENT : UI_COL_PANEL, 0);
lv_obj_set_style_text_color(g_tab_btn[i], on ? lv_color_hex(0x0B1620) : UI_COL_TEXT, 0);
}
setVisible(g_reset_btn, t != TAB_SIM);
refreshSaveState();
}
static lv_obj_t *makeStepBtn(lv_obj_t *parent, const char *txt, step_ctx_t *ctx)
static void onTab(lv_event_t *e)
{
lv_obj_t *b = lv_btn_create(parent);
lv_obj_set_size(b, 44, 36);
lv_obj_set_style_bg_color(b, COL_BG, 0);
lv_obj_set_style_radius(b, 8, 0);
lv_obj_add_event_cb(b, onStep, LV_EVENT_CLICKED, ctx);
lv_obj_add_event_cb(b, onStep, LV_EVENT_LONG_PRESSED_REPEAT, ctx);
lv_obj_t *l = lv_label_create(b);
lv_label_set_text(l, txt);
lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0);
lv_obj_center(l);
selectTab((tab_t)(uintptr_t)lv_event_get_user_data(e));
}
// ============================================================================
// BUILDERS
// ============================================================================
static lv_obj_t *makeStepBtn(lv_obj_t *parent, const char *txt, lv_event_cb_t cb, void *ctx)
{
lv_obj_t *b = button(parent, txt, 76, 56, BTN_SECONDARY, NULL, NULL);
lv_obj_set_style_text_font(lv_obj_get_child(b, 0), &lv_font_montserrat_24, 0);
lv_obj_add_event_cb(b, cb, LV_EVENT_PRESSED, ctx);
lv_obj_add_event_cb(b, cb, LV_EVENT_CLICKED, ctx);
lv_obj_add_event_cb(b, cb, LV_EVENT_LONG_PRESSED_REPEAT, ctx);
return b;
}
static void makeRow(lv_obj_t *panel, field_t f)
/** [name / hint] ... [-] value [+] */
static void makeRow(lv_obj_t *page, field_t f)
{
row_t *r = &g_rows[f];
lv_obj_t *row = lv_obj_create(panel);
lv_obj_remove_style_all(row);
lv_obj_set_size(row, LV_PCT(100), 36);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_t *row = box(page, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_PCT(100), 62);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(row, 6, 0);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_set_style_pad_column(row, 12, 0);
lv_obj_t *name = lv_label_create(row);
lv_label_set_text(name, r->name);
lv_obj_set_style_text_font(name, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(name, COL_MUTED, 0);
lv_obj_set_width(name, 118);
lv_obj_t *txt = box(row, LV_FLEX_FLOW_COLUMN);
lv_obj_set_height(txt, LV_SIZE_CONTENT);
lv_obj_set_flex_grow(txt, 1);
lv_obj_set_style_pad_row(txt, 2, 0);
label(txt, r->name, &lv_font_montserrat_24, UI_COL_TEXT);
label(txt, r->hint, &lv_font_montserrat_14, UI_COL_MUTED);
g_step_ctx[f][0] = {r, -1};
g_step_ctx[f][1] = {r, +1};
makeStepBtn(row, LV_SYMBOL_MINUS, &g_step_ctx[f][0]);
r->value_lbl = lv_label_create(row);
lv_label_set_text(r->value_lbl, "--");
lv_obj_set_style_text_font(r->value_lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(r->value_lbl, COL_TEXT, 0);
makeStepBtn(row, LV_SYMBOL_MINUS, onStep, &g_step_ctx[f][0]);
r->value_lbl = label(row, "--", &lv_font_montserrat_30, UI_COL_TEXT);
lv_obj_set_style_text_align(r->value_lbl, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_width(r->value_lbl, 82);
makeStepBtn(row, LV_SYMBOL_PLUS, &g_step_ctx[f][1]);
lv_obj_set_width(r->value_lbl, 190);
makeStepBtn(row, LV_SYMBOL_PLUS, onStep, &g_step_ctx[f][1]);
}
static lv_obj_t *makeSwitchRow(lv_obj_t *panel, const char *text, lv_event_cb_t cb, void *user)
static lv_obj_t *makeSwitchRow(lv_obj_t *page, const char *name, const char *hint, lv_event_cb_t cb, void *user)
{
lv_obj_t *row = lv_obj_create(panel);
lv_obj_remove_style_all(row);
lv_obj_set_size(row, LV_PCT(100), 36);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_t *row = box(page, LV_FLEX_FLOW_ROW);
lv_obj_set_size(row, LV_PCT(100), 62);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *l = lv_label_create(row);
lv_label_set_text(l, text);
lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(l, COL_MUTED, 0);
lv_obj_t *sw = lv_switch_create(row);
lv_obj_set_style_bg_color(sw, COL_ACCENT, (lv_style_selector_t)LV_PART_INDICATOR | (lv_style_selector_t)LV_STATE_CHECKED);
lv_obj_add_event_cb(sw, cb, LV_EVENT_VALUE_CHANGED, user);
lv_obj_t *txt = box(row, LV_FLEX_FLOW_COLUMN);
lv_obj_set_size(txt, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_style_pad_row(txt, 2, 0);
label(txt, name, &lv_font_montserrat_24, UI_COL_TEXT);
label(txt, hint, &lv_font_montserrat_14, UI_COL_MUTED);
lv_obj_t *sw = toggle(row, cb, user);
lv_obj_set_style_pad_right(row, 70, 0); // line the switch up under the value column
return sw;
}
static lv_obj_t *makeSliderRow(lv_obj_t *panel, const char *text, int32_t max, lv_obj_t **readout)
/** Simulation card: title + readout + switch, then [-] slider [+]. */
static lv_obj_t *makeSimCard(lv_obj_t *page, const char *title, int32_t max, lv_obj_t **sw, lv_obj_t **readout)
{
lv_obj_t *head = lv_obj_create(panel);
lv_obj_remove_style_all(head);
lv_obj_set_size(head, LV_PCT(100), 20);
lv_obj_set_flex_flow(head, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(head, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_clear_flag(head, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_t *c = card(page);
lv_obj_set_size(c, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(c, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(c, 14, 0);
lv_obj_t *l = lv_label_create(head);
lv_label_set_text(l, text);
lv_obj_set_style_text_font(l, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(l, COL_MUTED, 0);
lv_obj_t *top = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(top, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(top, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_t *t = label(top, title, &lv_font_montserrat_24, UI_COL_TEXT);
lv_obj_set_flex_grow(t, 1);
*readout = label(top, "--", &lv_font_montserrat_30, UI_COL_TEXT);
lv_obj_set_style_pad_right(*readout, 24, 0);
*sw = toggle(top, onOverrideSwitch, NULL);
*readout = lv_label_create(head);
lv_label_set_text(*readout, "--");
lv_obj_set_style_text_font(*readout, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(*readout, COL_TEXT, 0);
lv_obj_t *sl = lv_slider_create(panel);
lv_obj_set_width(sl, LV_PCT(96));
lv_obj_t *bottom = box(c, LV_FLEX_FLOW_ROW);
lv_obj_set_size(bottom, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_align(bottom, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_column(bottom, 24, 0);
makeStepBtn(bottom, LV_SYMBOL_MINUS, onSimStep, (void *)(intptr_t)-1);
lv_obj_t *sl = lv_slider_create(bottom);
lv_obj_set_height(sl, 16);
lv_obj_set_flex_grow(sl, 1);
lv_slider_set_range(sl, 0, max);
lv_obj_set_style_bg_color(sl, COL_BG, 0);
lv_obj_set_style_bg_color(sl, COL_ACCENT, LV_PART_INDICATOR);
lv_obj_set_style_bg_color(sl, COL_TEXT, LV_PART_KNOB);
lv_obj_set_style_bg_color(sl, UI_COL_PANEL2, 0);
lv_obj_set_style_bg_color(sl, UI_COL_ACCENT, LV_PART_INDICATOR);
lv_obj_set_style_bg_color(sl, UI_COL_TEXT, LV_PART_KNOB);
lv_obj_set_style_pad_all(sl, 12, LV_PART_KNOB); // big knob
lv_obj_set_style_anim_time(sl, 0, 0);
lv_obj_clear_flag(sl, LV_OBJ_FLAG_GESTURE_BUBBLE); // dragging must not change screens
lv_obj_add_event_cb(sl, onOverrideSlider, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_add_event_cb(sl, onOverrideSlider, LV_EVENT_RELEASED, NULL);
lv_obj_set_style_pad_ver(bottom, 12, 0); // room for the knob
makeStepBtn(bottom, LV_SYMBOL_PLUS, onSimStep, (void *)(intptr_t)1);
return sl;
}
static lv_obj_t *makeTabPage()
{
lv_obj_t *p = box(g_screen, LV_FLEX_FLOW_COLUMN);
lv_obj_set_size(p, 1024 - 48, 600 - 150 - 36);
lv_obj_set_pos(p, 24, 150);
lv_obj_set_style_pad_row(p, 6, 0);
return p;
}
static void build()
{
if (g_screen != NULL)
return;
g_screen = lv_obj_create(NULL);
lv_obj_set_style_bg_color(g_screen, COL_BG, 0);
lv_obj_clear_flag(g_screen, LV_OBJ_FLAG_SCROLLABLE);
// No swipe gesture on this screen: dragging the override sliders would
// otherwise change screens. Leave via the Driveline button (top right).
g_screen = screen();
lv_obj_add_event_cb(g_screen, onGesture, LV_EVENT_GESTURE, NULL);
header(g_screen, "GAUGE TUNING", onBack);
lv_obj_t *title = lv_label_create(g_screen);
lv_label_set_text(title, "GAUGE TUNING");
lv_obj_set_style_text_font(title, &lv_font_montserrat_30, 0);
lv_obj_set_style_text_color(title, COL_TEXT, 0);
lv_obj_align(title, LV_ALIGN_TOP_LEFT, 24, 16);
g_sim_chip = label(g_screen, "SIMULATION ON", &lv_font_montserrat_20, UI_COL_TEXT);
lv_obj_set_style_bg_color(g_sim_chip, UI_COL_WARN, 0);
lv_obj_set_style_bg_opa(g_sim_chip, LV_OPA_COVER, 0);
lv_obj_set_style_radius(g_sim_chip, 8, 0);
lv_obj_set_style_pad_hor(g_sim_chip, 12, 0);
lv_obj_set_style_pad_ver(g_sim_chip, 6, 0);
lv_obj_align(g_sim_chip, LV_ALIGN_TOP_LEFT, 290, 22);
lv_obj_add_flag(g_sim_chip, LV_OBJ_FLAG_HIDDEN);
lv_obj_t *back = lv_btn_create(g_screen);
lv_obj_set_size(back, 150, 36);
lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -24, 18);
lv_obj_set_style_bg_color(back, COL_ACCENT, 0);
lv_obj_add_event_cb(back, onBack, LV_EVENT_CLICKED, NULL);
lv_obj_t *bl = lv_label_create(back);
lv_label_set_text(bl, LV_SYMBOL_HOME " Driveline");
lv_obj_set_style_text_font(bl, &lv_font_montserrat_14, 0);
lv_obj_center(bl);
g_reset_btn = button(g_screen, LV_SYMBOL_REFRESH " Reset tab", 190, 56, BTN_SECONDARY, onReset, NULL);
lv_obj_align(g_reset_btn, LV_ALIGN_TOP_RIGHT, -16 - 200 - 12, 10);
lv_obj_t *reset = lv_btn_create(g_screen);
lv_obj_set_size(reset, 150, 36);
lv_obj_align(reset, LV_ALIGN_TOP_RIGHT, -24 - 150 - 12, 18);
lv_obj_set_style_bg_color(reset, COL_PANEL, 0);
lv_obj_add_event_cb(reset, onReset, LV_EVENT_CLICKED, NULL);
lv_obj_t *rl = lv_label_create(reset);
lv_label_set_text(rl, LV_SYMBOL_REFRESH " Defaults");
lv_obj_set_style_text_font(rl, &lv_font_montserrat_14, 0);
lv_obj_center(rl);
// tab bar
for (int i = 0; i < TAB_COUNT; i++)
{
g_tab_btn[i] = button(g_screen, TAB_NAMES[i], 232, 58, BTN_SECONDARY, onTab, (void *)(uintptr_t)i);
lv_obj_set_pos(g_tab_btn[i], 24 + i * (232 + 12), 80);
g_tab_page[i] = makeTabPage();
}
// Three columns of panels
lv_obj_t *cols = lv_obj_create(g_screen);
lv_obj_remove_style_all(cols);
lv_obj_set_size(cols, 1024 - 48, 600 - 70 - 30);
lv_obj_align(cols, LV_ALIGN_TOP_LEFT, 24, 66);
lv_obj_set_flex_flow(cols, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(cols, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_START);
lv_obj_clear_flag(cols, LV_OBJ_FLAG_SCROLLABLE);
// ---- Tachometer ----
makeRow(g_tab_page[TAB_TACH], F_TACH_PPR);
makeRow(g_tab_page[TAB_TACH], F_TACH_TRIM);
makeRow(g_tab_page[TAB_TACH], F_TACH_MAX_HZ);
g_tach_en_sw = makeSwitchRow(g_tab_page[TAB_TACH], "Tachometer output", "IO7 on Inst. Cluster. Off = no signal",
onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH);
const lv_coord_t W = 320;
// ---- Coolant gauge ----
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_HZ);
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_SLOPE);
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_OFFSET);
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_MIN);
makeRow(g_tab_page[TAB_COOLANT], F_TEMP_DUTY_MAX);
g_temp_en_sw = makeSwitchRow(g_tab_page[TAB_COOLANT], "Coolant gauge output", "IO8 on Inst. Cluster. Off = no signal",
onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP);
// ---- column 1: tach + alerts ----
lv_obj_t *c1 = lv_obj_create(cols);
lv_obj_remove_style_all(c1);
lv_obj_set_size(c1, W, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(c1, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(c1, 12, 0);
lv_obj_clear_flag(c1, LV_OBJ_FLAG_SCROLLABLE);
// ---- Alerts ----
makeRow(g_tab_page[TAB_ALERTS], F_COOLANT_HOT);
makeRow(g_tab_page[TAB_ALERTS], F_GEARBOX_HOT);
makeRow(g_tab_page[TAB_ALERTS], F_BATT_LOW);
lv_obj_t *tach = makePanel(c1, "TACHOMETER(IO7)", W);
makeRow(tach, F_TACH_PPR);
makeRow(tach, F_TACH_TRIM);
makeRow(tach, F_TACH_MAX_HZ);
g_tach_en_sw = makeSwitchRow(tach, "Output enabled", onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TACH);
// ---- Simulation ----
lv_obj_t *sim = g_tab_page[TAB_SIM];
lv_obj_set_style_pad_row(sim, 14, 0);
lv_obj_t *intro = label(sim,
"Forces fixed values on the gauge outputs so the needles can be calibrated "
"against the cluster. Switch off when done.",
&lv_font_montserrat_20, UI_COL_MUTED);
lv_label_set_long_mode(intro, LV_LABEL_LONG_WRAP);
lv_obj_set_width(intro, LV_PCT(100));
g_ovr_rpm_sl = makeSimCard(sim, "Force tachometer", RPM_MAX, &g_ovr_rpm_sw, &g_ovr_rpm_lbl);
g_ovr_duty_sl = makeSimCard(sim, "Force coolant gauge", DUTY_MAX, &g_ovr_duty_sw, &g_ovr_duty_lbl);
lv_obj_t *alerts = makePanel(c1, "ALERT THRESHOLDS", W);
makeRow(alerts, F_COOLANT_HOT);
makeRow(alerts, F_GEARBOX_HOT);
makeRow(alerts, F_BATT_LOW);
// ---- column 2: coolant gauge ----
lv_obj_t *temp = makePanel(cols, "COOLANT GAUGE(IO8)", W);
makeRow(temp, F_TEMP_HZ);
makeRow(temp, F_TEMP_SLOPE);
makeRow(temp, F_TEMP_OFFSET);
makeRow(temp, F_TEMP_MIN);
makeRow(temp, F_TEMP_DUTY_MAX);
g_temp_en_sw = makeSwitchRow(temp, "Output enabled", onEnableSwitch, (void *)(uintptr_t)OUT_ENABLE_TEMP);
// lv_obj_t* note = lv_label_create(temp);
// lv_label_set_text(note, "duty = slope x T + offset\n(defaults: 1.5 x T + 50, from the\nCANNY program)");
// lv_obj_set_style_text_font(note, &lv_font_montserrat_14, 0);
// lv_obj_set_style_text_color(note, COL_MUTED, 0);
// ---- column 3: calibration override ----
lv_obj_t *ovr = makePanel(cols, "SIMULATION", 300);
g_ovr_rpm_sw = makeSwitchRow(ovr, "Force tach rpm", onOverrideSwitch, NULL);
g_ovr_rpm_sl = makeSliderRow(ovr, "RPM", 6000, &g_ovr_rpm_lbl);
g_ovr_duty_sw = makeSwitchRow(ovr, "Force coolant duty", onOverrideSwitch, NULL);
g_ovr_duty_sl = makeSliderRow(ovr, "Duty", 255, &g_ovr_duty_lbl);
// lv_obj_t* howto = lv_label_create(ovr);
// lv_label_set_text(howto,
// "Tach: force 1000 rpm, fix Pulses/rev until\n"
// "the needle reads 1000; force 3000, fix Trim.\n"
// "Temp: force a duty, note the needle, repeat;\n"
// "derive Slope/Offset from two marks.\n"
// "Switch overrides OFF when done.");
// lv_obj_set_style_text_font(howto, &lv_font_montserrat_14, 0);
// lv_obj_set_style_text_color(howto, COL_MUTED, 0);
// lv_obj_t *hint = lv_label_create(g_screen);
// lv_label_set_text(hint, LV_SYMBOL_LEFT " swipe left: back to Driveline");
// lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
// lv_obj_set_style_text_color(hint, COL_MUTED, 0);
// lv_obj_align(hint, LV_ALIGN_BOTTOM_RIGHT, -24, -10);
g_status_lbl = lv_label_create(g_screen);
lv_label_set_text(g_status_lbl, "config v-");
lv_obj_set_style_text_font(g_status_lbl, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(g_status_lbl, COL_MUTED, 0);
lv_obj_align(g_status_lbl, LV_ALIGN_BOTTOM_RIGHT, -24, -10);
g_save_lbl = label(g_screen, "", &lv_font_montserrat_20, UI_COL_MUTED);
lv_obj_align(g_save_lbl, LV_ALIGN_BOTTOM_LEFT, 24, -8);
selectTab(TAB_TACH);
ESP_LOGI("Tuning", "Gauge tuning screen built");
}
@@ -584,7 +566,7 @@ namespace TuningScreen
{
build();
refreshFromTunables();
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_FADE_ON, 100, 0, false);
lv_scr_load_anim(g_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, false); // instant: fades stutter at 1024x600
}
void tick()
@@ -595,10 +577,11 @@ namespace TuningScreen
if (millis() - last < 500)
return;
last = millis();
if (Tunables::version() == g_shown_version)
return; // nothing changed elsewhere
lvgl_port_lock(-1);
refreshFromTunables();
if (Tunables::version() != g_shown_version)
refreshFromTunables(); // changed from the console
else
refreshSaveState(); // "Saving..." -> "saved" after the deferred write
lvgl_port_unlock();
}
+5 -4
View File
@@ -6,11 +6,12 @@
* bench override (force an rpm / a duty) so the needles can be calibrated
* from the touchscreen while watching the cluster.
*
* Lives in src/ (never touched by SquareLine exports), like DrivelineScreen.
* Reached by swiping RIGHT on the Driveline screen; the Driveline button (top
* right) goes back. No swipe gesture on this screen (it would fight the sliders).
* Four tabs: Tachometer / Coolant gauge / Alerts / Simulation.
* Reached by swiping RIGHT on the Driveline screen; swipe left or the Driveline
* button (top right) goes back. The Simulation sliders don't bubble gestures,
* so dragging them never changes screens.
* Every change goes through Tunables, so it is saved to NVS (overrides
* excepted) and pushed to Controller B in the next CONFIG frame.
* excepted) and pushed to Inst. Cluster in the next CONFIG frame.
*/
#pragma once
+19 -31
View File
@@ -3,7 +3,7 @@
*
* Builds the v2 frames (DATA at 5 Hz, CONFIG on change + every CONFIG_RESEND_MS)
* and sends each one on BOTH transports: UART1 (GPIO 44 -> SP3485 -> 485_A/B)
* and ESP-NOW broadcast. Controller B dedupes on packet_id.
* and ESP-NOW broadcast. Inst. Cluster dedupes on packet_id.
*/
#include "uart_manager.h"
@@ -43,36 +43,24 @@ static uart_stats_t g_uart_stats = {0};
// CONFIG frame scheduling
static uint8_t g_last_cfg_version_sent = 0;
static uint32_t g_last_cfg_send_time = 0;
static volatile bool g_port_ready = false; // Serial1.begin() done (in the task)
// ============================================================================
// PRIVATE HELPER FUNCTIONS
// ============================================================================
/**
* @brief Seed the shared structure until CAN data arrives.
* @note The temperatures/voltage are marked valid so a bench without CAN still
* exercises B's display. RPM and gear nibbles are NOT marked valid: the
* tach output must never run on invented data.
* @brief Start from NOTHING valid. Until a CAN frame fills a field, its valid
* flag stays clear and B shows no value for it (user decision
* 2026-09-28: no invented numbers, ever - the old bench defaults of
* 89 / 85 degC and 12.45 V looked like real readings).
*/
static void initializeDefaultData() {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
g_automotive_data.gear_lever = DEFAULT_GEAR_LEVER;
g_automotive_data.gear_nibbles = 0;
g_automotive_data.engine_rpm = 0;
g_automotive_data.gearbox_oil_temp = DEFAULT_GEARBOX_TEMP;
g_automotive_data.engine_oil_temp = DEFAULT_ENGINE_OIL_TEMP;
g_automotive_data.coolant_temp = DEFAULT_COOLANT_TEMP;
g_automotive_data.battery_voltage = DEFAULT_BATTERY_VOLTAGE;
g_automotive_data.alerts = DEFAULT_ALERTS;
g_automotive_data.valid_flags = VALID_FLAG_GEAR_POS |
VALID_FLAG_GEARBOX_TEMP |
VALID_FLAG_ENGINE_TEMP |
VALID_FLAG_COOLANT_TEMP |
VALID_FLAG_BATTERY_VOLT |
VALID_FLAG_ALERTS;
g_automotive_data.debug_enabled = 0;
uint8_t dbg = g_automotive_data.debug_enabled;
memset(&g_automotive_data, 0, sizeof(g_automotive_data));
g_automotive_data.gear_lever = LEVER_UNKNOWN;
g_automotive_data.debug_enabled = dbg;
xSemaphoreGive(g_data_mutex);
}
}
@@ -173,6 +161,7 @@ static void uartTask(void* parameter) {
Serial1.setRxBufferSize(256);
Serial1.begin(UART_BAUD_RATE, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN);
g_port_ready = true;
ESP_LOGI("UARTTask", "UART1 initialized: %d baud, TX=GPIO%d (RS485 A/B), protocol v%u",
UART_BAUD_RATE, UART_TX_PIN, PACKET_VERSION);
@@ -302,7 +291,7 @@ void setDebugEnabled(bool enabled) {
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
g_automotive_data.debug_enabled = enabled ? 1 : 0;
xSemaphoreGive(g_data_mutex);
ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Controller B)",
ESP_LOGI("UARTMgr", "Debug flag set to %s (will be transmitted to Inst. Cluster)",
enabled ? "ENABLED" : "DISABLED");
}
}
@@ -323,15 +312,8 @@ void linkToCANState(bool can_active) {
// EVENT HANDLERS
// ============================================================================
void onUARTToggle(lv_event_t *e)
void setEnabled(bool state)
{
lv_obj_t *target = lv_event_get_target(e);
if (target == NULL) {
ESP_LOGE("UARTMgr", "ERROR: UART toggle target is NULL!");
return;
}
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
ESP_LOGI("UARTMgr", "===== UART Toggle Event =====");
ESP_LOGI("UARTMgr", "UART Toggle State: %s", state ? "ON" : "OFF");
@@ -362,4 +344,10 @@ void onUARTToggle(lv_event_t *e)
ESP_LOGI("UARTMgr", "=============================");
}
bool sendWire(const uint8_t* frame, size_t len) {
if (!g_port_ready || len == 0) return false;
return Serial1.write(frame, len) == len;
}
} // namespace UARTManager
+10 -7
View File
@@ -116,15 +116,18 @@ void setDebugEnabled(bool enabled);
*/
void linkToCANState(bool can_active);
// ============================================================================
// EVENT HANDLERS (Called from SquareLine Studio UI)
// ============================================================================
/**
* @brief Settings-screen switch: start/stop sending to Inst. Cluster (UART1 +
* ESP-NOW) and remember the choice in NVS.
*/
void setEnabled(bool enabled);
/**
* @brief UART toggle event handler
* @param e LVGL event object
* @note This function is registered in SquareLine Studio UI
* @brief Send one complete frame on the UART wire ONLY (never ESP-NOW).
* Used for the PAIR frame, which must not go over the air. One write
* call, so it cannot interleave with the task's own frames.
* @return true if the port is up and every byte was written
*/
void onUARTToggle(lv_event_t *e);
bool sendWire(const uint8_t* frame, size_t len);
} // namespace UARTManager
+178
View File
@@ -0,0 +1,178 @@
/*
* UI kit implementation - see ui_kit.h
*/
#include "ui_kit.h"
namespace UiKit {
lv_obj_t* screen() {
lv_obj_t* s = lv_obj_create(NULL);
lv_obj_set_style_bg_color(s, UI_COL_BG, 0);
lv_obj_set_style_bg_opa(s, LV_OPA_COVER, 0);
lv_obj_clear_flag(s, LV_OBJ_FLAG_SCROLLABLE);
return s;
}
void header(lv_obj_t* scr, const char* title, lv_event_cb_t back_cb) {
lv_obj_t* t = label(scr, title, &lv_font_montserrat_30, UI_COL_TEXT);
lv_obj_align(t, LV_ALIGN_TOP_LEFT, 24, 18);
// -176: the StatusOverlay Wi-Fi chip owns the last 150 px of the top-right corner
lv_obj_t* back = button(scr, LV_SYMBOL_LEFT " Driveline", 200, 56, BTN_SECONDARY, back_cb, NULL);
lv_obj_align(back, LV_ALIGN_TOP_RIGHT, -176, 10);
}
lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color) {
lv_obj_t* l = lv_label_create(parent);
lv_label_set_text(l, text);
lv_obj_set_style_text_font(l, font, 0);
lv_obj_set_style_text_color(l, color, 0);
return l;
}
static void styleButton(lv_obj_t* b, btn_style_t style) {
lv_color_t bg = UI_COL_PANEL2, fg = UI_COL_TEXT;
switch (style) {
case BTN_PRIMARY: bg = UI_COL_ACCENT; fg = lv_color_hex(0x0B1620); break;
case BTN_SECONDARY: bg = UI_COL_PANEL2; fg = UI_COL_TEXT; break;
case BTN_DANGER: bg = UI_COL_WARN; fg = UI_COL_TEXT; break;
case BTN_SUCCESS: bg = UI_COL_OK; fg = lv_color_hex(0x0B1620); break;
}
lv_obj_set_style_bg_color(b, bg, 0);
lv_obj_set_style_bg_opa(b, LV_OPA_COVER, 0);
lv_obj_set_style_text_color(b, fg, 0);
lv_obj_set_style_radius(b, 10, 0);
lv_obj_set_style_shadow_width(b, 0, 0);
lv_obj_set_style_bg_color(b, lv_color_hex(0x3A4450), LV_STATE_DISABLED);
lv_obj_set_style_text_color(b, UI_COL_MUTED, LV_STATE_DISABLED);
}
lv_obj_t* button(lv_obj_t* parent, const char* text, lv_coord_t w, lv_coord_t h,
btn_style_t style, lv_event_cb_t cb, void* user) {
lv_obj_t* b = lv_btn_create(parent);
lv_obj_set_size(b, w, h);
styleButton(b, style);
if (cb) lv_obj_add_event_cb(b, cb, LV_EVENT_CLICKED, user);
lv_obj_t* l = lv_label_create(b);
lv_label_set_text(l, text);
lv_obj_set_style_text_font(l, &lv_font_montserrat_20, 0);
lv_obj_center(l);
return b;
}
void setButtonText(lv_obj_t* btn, const char* text) {
setText(lv_obj_get_child(btn, 0), text);
}
lv_obj_t* toggle(lv_obj_t* parent, lv_event_cb_t cb, void* user) {
lv_obj_t* sw = lv_switch_create(parent);
lv_obj_set_size(sw, 92, 48);
lv_obj_set_style_bg_color(sw, UI_COL_PANEL2, 0);
lv_obj_set_style_bg_color(sw, UI_COL_ACCENT, (lv_style_selector_t)LV_PART_INDICATOR | (lv_style_selector_t)LV_STATE_CHECKED);
lv_obj_set_style_anim_time(sw, 0, 0); // no knob slide animation: one redraw per flip
if (cb) lv_obj_add_event_cb(sw, cb, LV_EVENT_VALUE_CHANGED, user);
return sw;
}
void setChecked(lv_obj_t* obj, bool on) {
if (obj == NULL || lv_obj_has_state(obj, LV_STATE_CHECKED) == on) return;
if (on) lv_obj_add_state(obj, LV_STATE_CHECKED);
else lv_obj_clear_state(obj, LV_STATE_CHECKED);
}
lv_obj_t* box(lv_obj_t* parent, lv_flex_flow_t flow) {
lv_obj_t* b = lv_obj_create(parent);
lv_obj_remove_style_all(b);
lv_obj_set_flex_flow(b, flow);
lv_obj_clear_flag(b, LV_OBJ_FLAG_SCROLLABLE);
return b;
}
lv_obj_t* card(lv_obj_t* parent) {
lv_obj_t* c = lv_obj_create(parent);
lv_obj_set_style_bg_color(c, UI_COL_PANEL, 0);
lv_obj_set_style_border_width(c, 0, 0);
lv_obj_set_style_radius(c, 12, 0);
lv_obj_set_style_pad_all(c, 16, 0);
lv_obj_set_style_shadow_width(c, 0, 0);
lv_obj_clear_flag(c, LV_OBJ_FLAG_SCROLLABLE);
return c;
}
void setText(lv_obj_t* lbl, const char* text) {
if (lbl == NULL) return;
const char* cur = lv_label_get_text(lbl);
if (cur && strcmp(cur, text) == 0) return;
lv_label_set_text(lbl, text);
}
void setTextColor(lv_obj_t* lbl, lv_color_t c) {
if (lbl == NULL) return;
if (lv_obj_get_style_text_color(lbl, LV_PART_MAIN).full == c.full) return;
lv_obj_set_style_text_color(lbl, c, 0);
}
void setVisible(lv_obj_t* obj, bool visible) {
if (obj == NULL || lv_obj_has_flag(obj, LV_OBJ_FLAG_HIDDEN) == !visible) return;
if (visible) lv_obj_clear_flag(obj, LV_OBJ_FLAG_HIDDEN);
else lv_obj_add_flag(obj, LV_OBJ_FLAG_HIDDEN);
}
// ---- confirm dialog --------------------------------------------------------
static const char* g_btn_map[3] = {"Cancel", "OK", ""};
static char g_ok_text[32];
static void (*g_confirm_cb)(bool, void*) = NULL;
static void* g_confirm_user = NULL;
static void onConfirm(lv_event_t* e) {
lv_obj_t* mb = lv_event_get_current_target(e);
uint16_t id = lv_msgbox_get_active_btn(mb);
if (id == LV_BTNMATRIX_BTN_NONE) return;
lv_msgbox_close_async(mb);
void (*cb)(bool, void*) = g_confirm_cb;
g_confirm_cb = NULL;
if (cb) cb(id == 1, g_confirm_user);
}
void confirm(const char* title, const char* text, const char* ok_text,
void (*cb)(bool ok, void* user), void* user) {
snprintf(g_ok_text, sizeof(g_ok_text), "%s", ok_text);
g_btn_map[1] = g_ok_text;
g_confirm_cb = cb;
g_confirm_user = user;
lv_obj_t* mb = lv_msgbox_create(NULL, title, text, g_btn_map, false);
lv_obj_set_width(mb, 640);
lv_obj_set_style_bg_color(mb, UI_COL_PANEL, 0);
lv_obj_set_style_border_width(mb, 0, 0);
lv_obj_set_style_shadow_width(mb, 0, 0);
lv_obj_set_style_radius(mb, 14, 0);
lv_obj_set_style_pad_all(mb, 24, 0);
lv_obj_set_style_pad_row(mb, 16, 0);
lv_obj_set_style_text_color(mb, UI_COL_TEXT, 0);
lv_obj_set_style_text_font(lv_msgbox_get_title(mb), &lv_font_montserrat_24, 0);
lv_obj_set_style_text_font(lv_msgbox_get_text(mb), &lv_font_montserrat_20, 0);
lv_obj_t* btns = lv_msgbox_get_btns(mb);
lv_obj_set_size(btns, LV_PCT(100), 64);
lv_obj_set_style_text_font(btns, &lv_font_montserrat_20, 0);
lv_obj_set_style_pad_column(btns, 16, 0);
lv_obj_set_style_bg_color(btns, UI_COL_PANEL2, LV_PART_ITEMS);
lv_obj_set_style_text_color(btns, UI_COL_TEXT, LV_PART_ITEMS);
lv_obj_set_style_radius(btns, 10, LV_PART_ITEMS);
lv_obj_set_style_shadow_width(btns, 0, LV_PART_ITEMS);
lv_btnmatrix_set_btn_ctrl(btns, 1, LV_BTNMATRIX_CTRL_CHECKED); // highlight the action
lv_obj_set_style_bg_color(btns, UI_COL_ACCENT, (lv_style_selector_t)LV_PART_ITEMS | (lv_style_selector_t)LV_STATE_CHECKED);
lv_obj_set_style_text_color(btns, lv_color_hex(0x0B1620), (lv_style_selector_t)LV_PART_ITEMS | (lv_style_selector_t)LV_STATE_CHECKED);
lv_obj_t* backdrop = lv_obj_get_parent(mb);
lv_obj_set_style_bg_color(backdrop, lv_color_black(), 0);
lv_obj_set_style_bg_opa(backdrop, LV_OPA_70, 0);
lv_obj_center(mb);
lv_obj_add_event_cb(mb, onConfirm, LV_EVENT_VALUE_CHANGED, NULL);
}
} // namespace UiKit
+59
View File
@@ -0,0 +1,59 @@
/*
* UI kit - shared look for the hand-coded screens (Settings, Gauge Tuning).
*
* Car-sized touch targets (>= 56 px), 20/24 px body text, no shadows or
* animated transitions (every extra redraw of this 1024x600 PSRAM framebuffer
* costs frame time). All functions need the LVGL lock, like any LVGL call.
*/
#pragma once
#include <Arduino.h>
#include <lvgl.h>
#define UI_COL_BG lv_color_hex(0x101418)
#define UI_COL_PANEL lv_color_hex(0x1B2128)
#define UI_COL_PANEL2 lv_color_hex(0x252D36) // pressed / selected rows
#define UI_COL_TEXT lv_color_hex(0xE8EDF2)
#define UI_COL_MUTED lv_color_hex(0x8894A0)
#define UI_COL_ACCENT lv_color_hex(0x3DA9FC)
#define UI_COL_OK lv_color_hex(0x3DD68C)
#define UI_COL_WARN lv_color_hex(0xE5484D)
#define UI_COL_AMBER lv_color_hex(0xF5A524)
namespace UiKit {
typedef enum { BTN_PRIMARY, BTN_SECONDARY, BTN_DANGER, BTN_SUCCESS } btn_style_t;
/** Plain full-screen background object. */
lv_obj_t* screen();
/** Title top-left and a "< Driveline" button top-right that calls back_cb. */
void header(lv_obj_t* scr, const char* title, lv_event_cb_t back_cb);
lv_obj_t* label(lv_obj_t* parent, const char* text, const lv_font_t* font, lv_color_t color);
/** Button with a centred label; the label is the button's first child. */
lv_obj_t* button(lv_obj_t* parent, const char* text, lv_coord_t w, lv_coord_t h,
btn_style_t style, lv_event_cb_t cb, void* user);
void setButtonText(lv_obj_t* btn, const char* text);
lv_obj_t* toggle(lv_obj_t* parent, lv_event_cb_t cb, void* user);
void setChecked(lv_obj_t* obj, bool on);
/** Transparent flex row/column container without padding or scrolling. */
lv_obj_t* box(lv_obj_t* parent, lv_flex_flow_t flow);
/** Rounded panel (card). */
lv_obj_t* card(lv_obj_t* parent);
/** lv_label_set_text only when the text changed - avoids needless redraws. */
void setText(lv_obj_t* lbl, const char* text);
void setTextColor(lv_obj_t* lbl, lv_color_t c);
void setVisible(lv_obj_t* obj, bool visible);
/** Modal Cancel / OK dialog; cb(true, user) on OK, cb(false, user) on Cancel. */
void confirm(const char* title, const char* text, const char* ok_text,
void (*cb)(bool ok, void* user), void* user);
} // namespace UiKit
-118
View File
@@ -4,19 +4,7 @@
#include "ui_state_manager.h"
#include "display/lvgl_v8_port.h"
#include "settings_manager.h"
#include "wifi_manager.h"
#include "uart_manager.h"
#include "drivers/can_driver.h"
// External UI element references (from ui_Settings_Screen.c)
extern "C" {
extern lv_obj_t *uic_Main_Container;
extern lv_obj_t *uic_Toggle_Wifi_Switch;
extern lv_obj_t *uic_Toggle_UART_Switch;
extern lv_obj_t *uic_Toggle_CAN_Bus_Switch;
extern lv_obj_t *uic_Toggle_Debug_Switch;
}
namespace UIStateManager {
@@ -24,9 +12,6 @@ namespace UIStateManager {
// PRIVATE MODULE STATE
// ============================================================================
// Track which screen instance we synced (to prevent redundant syncing)
static lv_obj_t* g_last_synced_screen = NULL;
// Debug mode state
static bool g_debug_enabled = false;
@@ -36,85 +21,9 @@ static bool g_debug_enabled = false;
void init() {
Serial.println("[UIStateManager] Initialized");
g_last_synced_screen = NULL;
g_debug_enabled = false;
}
void applySavedStatesToUI() {
// Wait for UI widgets to be created
if (uic_Toggle_Wifi_Switch == NULL || uic_Toggle_UART_Switch == NULL || uic_Toggle_CAN_Bus_Switch == NULL) {
// Reset last synced screen when widgets are NULL (screen unloaded)
g_last_synced_screen = NULL;
return; // Settings screen not loaded yet
}
if (uic_Main_Container == NULL) {
return; // UI not ready
}
// Get the Settings screen pointer (parent of Main Container)
lv_obj_t* settings_screen = lv_obj_get_parent(uic_Main_Container);
if (settings_screen == NULL) {
return;
}
// Check if we've already synced this screen instance
if (g_last_synced_screen == settings_screen) {
return; // Already synced this instance
}
Serial.println("Settings screen detected - syncing toggle states with services...");
// Sync UI with the actual running state of services
bool current_wifi_state = WiFiManager::getState() != WiFiManager::WIFI_STATE_OFF;
bool current_uart_state = UARTManager::getState() != UARTManager::UART_STATE_OFF;
bool current_can_state = CANDriver::isActive();
bool current_debug_state = g_debug_enabled;
lvgl_port_lock(-1);
// Apply WiFi state
if (current_wifi_state) {
lv_obj_add_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
} else {
lv_obj_clear_state(uic_Toggle_Wifi_Switch, LV_STATE_CHECKED);
}
// Apply UART state
if (current_uart_state) {
lv_obj_add_state(uic_Toggle_UART_Switch, LV_STATE_CHECKED);
} else {
lv_obj_clear_state(uic_Toggle_UART_Switch, LV_STATE_CHECKED);
}
// Apply CAN Bus state
if (current_can_state) {
lv_obj_add_state(uic_Toggle_CAN_Bus_Switch, LV_STATE_CHECKED);
} else {
lv_obj_clear_state(uic_Toggle_CAN_Bus_Switch, LV_STATE_CHECKED);
}
// Apply Debug state
if (uic_Toggle_Debug_Switch != NULL) {
if (current_debug_state) {
lv_obj_add_state(uic_Toggle_Debug_Switch, LV_STATE_CHECKED);
} else {
lv_obj_clear_state(uic_Toggle_Debug_Switch, LV_STATE_CHECKED);
}
}
lvgl_port_unlock();
// Mark this screen instance as synced
g_last_synced_screen = settings_screen;
Serial.printf("Toggle states synced: WiFi=%s, UART=%s, CAN=%s, Debug=%s\n",
current_wifi_state ? "ON" : "OFF",
current_uart_state ? "ON" : "OFF",
current_can_state ? "ON" : "OFF",
current_debug_state ? "ON" : "OFF");
}
void setDebugEnabled(bool enabled) {
g_debug_enabled = enabled;
@@ -149,31 +58,4 @@ bool isDebugEnabled() {
return g_debug_enabled;
}
// ============================================================================
// EVENT HANDLERS
// ============================================================================
void onDebugToggle(lv_event_t *e)
{
lv_obj_t *target = lv_event_get_target(e);
if (target == NULL) {
Serial.println("ERROR: Debug toggle target is NULL!");
return;
}
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
Serial.printf("===== Debug Toggle Event =====\n");
Serial.printf("Debug Mode: %s\n", state ? "ON" : "OFF");
// Save state to NVS
SettingsManager::saveDebugState(state);
// Update global state and enable/disable monitors
setDebugEnabled(state);
Serial.printf("==============================\n");
}
} // namespace UIStateManager
+1 -26
View File
@@ -1,9 +1,7 @@
/*
* UI State Manager Module
*
* Handles UI state synchronization:
* - Syncs toggle switches with actual service states when screens change
* - Handles SquareLine Studio screen lifecycle (destroy/recreate)
* Holds the debug flag (sent to Inst. Cluster, shows LVGL's performance overlay).
*/
#pragma once
@@ -25,18 +23,6 @@ namespace UIStateManager {
*/
void init();
/**
* @brief Apply saved states to UI switches
*
* This function is called continuously in loop() to sync UI toggle switches
* with the actual running state of services when the Settings screen loads.
* It handles the SquareLine Studio screen lifecycle where screens get
* destroyed/recreated when swiping between screens.
*
* @note This function is thread-safe and uses LVGL locks internally
*/
void applySavedStatesToUI();
/**
* @brief Enable or disable debug mode (LVGL performance and memory monitors)
* @param enabled True to enable debug monitors, false to disable
@@ -49,15 +35,4 @@ void setDebugEnabled(bool enabled);
*/
bool isDebugEnabled();
// ============================================================================
// EVENT HANDLERS (Called from SquareLine Studio UI)
// ============================================================================
/**
* @brief Debug toggle event handler
* @param e LVGL event object
* @note This function is registered in SquareLine Studio UI
*/
void onDebugToggle(lv_event_t *e);
} // namespace UIStateManager
+194
View File
@@ -0,0 +1,194 @@
/*
* Vehicle Module Implementation - see vehicle.h
*/
#include "vehicle.h"
#include "serial_lock.h"
#include "protocol/automotive_data.h"
#include <Preferences.h>
namespace Vehicle {
// ============================================================================
// PRIVATE MODULE STATE
// ============================================================================
static const char* NVS_NAMESPACE = "settings";
static const char* NVS_KEY_FINAL = "final_x100";
static const char* NVS_KEY_TYRE = "tyre_mm";
// Defaults: the Patrol's 4.11:1 final drive (user, 2026-10-13); 2440 mm is a
// 265/70 R16 (overall diameter ~777 mm), a common Patrol tyre - adjust on the screen.
static const uint16_t DEFAULT_FINAL_X100 = 411;
static const uint16_t DEFAULT_TYRE_MM = 2440;
static volatile uint16_t g_final_x100 = DEFAULT_FINAL_X100;
static volatile uint16_t g_tyre_mm = DEFAULT_TYRE_MM;
static const uint32_t SAVE_IDLE_MS = 3000;
static bool g_dirty = false;
static uint32_t g_dirty_ms = 0;
// ============================================================================
// PRIVATE HELPERS
// ============================================================================
static void print(const char* fmt, ...) {
char buf[160];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
SerialLock::lock();
Serial.println(buf);
SerialLock::unlock();
}
static void markDirty() {
g_dirty = true;
g_dirty_ms = millis();
}
static void save() {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, false);
prefs.putUShort(NVS_KEY_FINAL, g_final_x100);
prefs.putUShort(NVS_KEY_TYRE, g_tyre_mm);
prefs.end();
print("[vehicle] saved final drive %u.%02u:1, tyre %u mm",
g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm);
}
static void show() {
print("[vehicle] final drive %u.%02u:1, tyre circumference %u mm%s",
g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm, g_dirty ? " (saving...)" : "");
// a worked example so the numbers can be sanity-checked without driving
uint16_t v = speedKmhX10FromRpm(1000);
print("[vehicle] 1000 shaft rpm = %u.%u km/h (shaft rpm itself is the provisional 0x0BA x 0.1074)",
v / 10, v % 10);
}
static void help() {
print("vehicle show final drive ratio, tyre circumference");
print("vehicle set final <x.xx> final drive (differential) ratio, 2.00..8.00");
print("vehicle set tyre <mm> tyre rolling circumference, 1500..3500 mm");
print("vehicle reset back to 4.11:1 and 2440 mm");
}
// ============================================================================
// PUBLIC API
// ============================================================================
void init() {
Preferences prefs;
prefs.begin(NVS_NAMESPACE, true);
g_final_x100 = prefs.getUShort(NVS_KEY_FINAL, DEFAULT_FINAL_X100);
g_tyre_mm = prefs.getUShort(NVS_KEY_TYRE, DEFAULT_TYRE_MM);
prefs.end();
g_final_x100 = constrain(g_final_x100, FINAL_DRIVE_MIN_X100, FINAL_DRIVE_MAX_X100);
g_tyre_mm = constrain(g_tyre_mm, TYRE_MM_MIN, TYRE_MM_MAX);
print("[vehicle] final drive %u.%02u:1, tyre %u mm", g_final_x100 / 100, g_final_x100 % 100, g_tyre_mm);
}
uint16_t finalDriveX100() { return g_final_x100; }
uint16_t tyreMm() { return g_tyre_mm; }
void setFinalDriveX100(uint16_t v) {
v = constrain(v, FINAL_DRIVE_MIN_X100, FINAL_DRIVE_MAX_X100);
if (v == g_final_x100) return;
g_final_x100 = v;
markDirty();
}
void setTyreMm(uint16_t v) {
v = constrain(v, TYRE_MM_MIN, TYRE_MM_MAX);
if (v == g_tyre_mm) return;
g_tyre_mm = v;
markDirty();
}
uint16_t speedKmhX10FromRpm(uint16_t shaft_rpm) {
// km/h = shaft_rpm / ratio * circumference_m * 60 / 1000
// = shaft_rpm * tyre_mm * 6 / (final_x100 * 1000)
// (tyre_mm / 1000 -> m, ratio = final_x100 / 100, * 60 min/h, / 1000 m/km)
// km/h x10 = shaft_rpm * tyre_mm * 3 / (final_x100 * 50)
// Integer only: 65535 * 3500 * 3 fits a 32-bit value with room.
// Checked on the bench 2026-10-13: 1199 rpm, 4.11:1, 2440 mm -> 42.7 km/h.
uint32_t num = (uint32_t)shaft_rpm * g_tyre_mm * 3;
uint32_t den = (uint32_t)g_final_x100 * 50;
uint32_t v = (num + den / 2) / den;
return v > 0xFFFF ? 0xFFFF : (uint16_t)v;
}
uint16_t speedKmhX10(uint16_t output_shaft_raw) {
return speedKmhX10FromRpm(can_output_shaft_rpm(output_shaft_raw));
}
uint16_t powerHpX10(int16_t torque_x10, uint16_t rpm) {
if (torque_x10 <= 0 || rpm == 0) return 0;
// P(W) = T * rpm / 9.5488 ; hp = P / 745.70 ; x10 and T in 0.1 Nm:
// hp_x10 = (T_x10 / 10) * rpm / 9.5488 / 745.70 * 10 = T_x10 * rpm / 7120.55
float hp_x10 = (float)torque_x10 * (float)rpm / 7120.55f;
if (hp_x10 > 65535.0f) return 0xFFFF;
return (uint16_t)(hp_x10 + 0.5f);
}
void resetDefaults() {
g_final_x100 = DEFAULT_FINAL_X100;
g_tyre_mm = DEFAULT_TYRE_MM;
markDirty();
flush();
}
void flush() {
if (!g_dirty) return;
g_dirty = false;
save();
}
bool isDirty() { return g_dirty; }
void tick() {
if (g_dirty && millis() - g_dirty_ms > SAVE_IDLE_MS) flush();
}
bool handleCommand(const char* line) {
if (strncmp(line, "vehicle", 7) != 0 || (line[7] != 0 && line[7] != ' ')) return false;
char buf[96];
snprintf(buf, sizeof(buf), "%s", line);
char* argv[5];
int argc = 0;
for (char* t = strtok(buf, " \t"); t && argc < 5; t = strtok(NULL, " \t")) argv[argc++] = t;
if (argc == 1 || !strcmp(argv[1], "help")) { help(); return true; }
if (!strcmp(argv[1], "show")) { show(); return true; }
if (!strcmp(argv[1], "reset")) { resetDefaults(); show(); return true; }
if (!strcmp(argv[1], "set") && argc == 4) {
if (!strcmp(argv[2], "final")) {
float r = atof(argv[3]);
long x100 = lroundf(r * 100.0f);
if (x100 < FINAL_DRIVE_MIN_X100 || x100 > FINAL_DRIVE_MAX_X100) {
print("[vehicle] final drive must be %u.%02u..%u.%02u", FINAL_DRIVE_MIN_X100 / 100, FINAL_DRIVE_MIN_X100 % 100,
FINAL_DRIVE_MAX_X100 / 100, FINAL_DRIVE_MAX_X100 % 100);
return true;
}
setFinalDriveX100((uint16_t)x100);
show();
return true;
}
if (!strcmp(argv[2], "tyre")) {
long mm = atol(argv[3]);
if (mm < TYRE_MM_MIN || mm > TYRE_MM_MAX) {
print("[vehicle] tyre circumference must be %u..%u mm", TYRE_MM_MIN, TYRE_MM_MAX);
return true;
}
setTyreMm((uint16_t)mm);
show();
return true;
}
}
help();
return true;
}
} // namespace Vehicle
+71
View File
@@ -0,0 +1,71 @@
/*
* Vehicle Module
*
* The two numbers that turn the gearbox output shaft speed (0x0BA, the only
* road-speed signal on this bus - there is no DSC) into road speed, plus the
* maths that uses them:
*
* wheel rpm = output shaft rpm / final drive ratio
* speed (km/h) = wheel rpm * tyre circumference (m) * 60 / 1000
*
* and the engine power the Sport screen shows:
*
* power (W) = torque (Nm) * rpm / 9.5488
* power (hp) = power (W) / 745.70
*
* Final drive ratio and tyre circumference are the user's (Settings > Vehicle,
* `vehicle` console), saved in NVS (namespace "settings", keys `final_x100`,
* `tyre_mm`). Writes are deferred like the tunables: every flash write flickers
* the RGB panel, so edits are written SAVE_IDLE_MS after the last tap, or on
* flush() when the Settings screen is left.
*
* NB the output shaft factor itself (raw counts -> rpm) is still provisional
* (wiki driveline-speed-signals), so the speed carries the same "~".
*/
#pragma once
#include <Arduino.h>
namespace Vehicle {
/** Load the saved values (defaults if absent). Call after SettingsManager::init(). */
void init();
/** Final drive (differential) ratio x100, e.g. 411 = 4.11:1. */
uint16_t finalDriveX100();
void setFinalDriveX100(uint16_t v);
/** Tyre rolling circumference in mm. */
uint16_t tyreMm();
void setTyreMm(uint16_t v);
/** Limits for the editors. */
static const uint16_t FINAL_DRIVE_MIN_X100 = 200, FINAL_DRIVE_MAX_X100 = 800;
static const uint16_t TYRE_MM_MIN = 1500, TYRE_MM_MAX = 3500;
/** Road speed in km/h x10 from the raw 0x0BA output shaft field. */
uint16_t speedKmhX10(uint16_t output_shaft_raw);
/** Road speed in km/h x10 from an output shaft speed in rpm. */
uint16_t speedKmhX10FromRpm(uint16_t shaft_rpm);
/** Engine power in hp x10 from torque (0.1 Nm, signed) and engine speed. Negative torque gives 0. */
uint16_t powerHpX10(int16_t torque_x10, uint16_t rpm);
/** Back to the defaults (4.11:1, 2440 mm) and save. */
void resetDefaults();
/** Write pending edits to NVS now (call when leaving the Settings screen). */
void flush();
/** True while an edit is waiting for its deferred NVS write. */
bool isDirty();
/** Deferred-save timer. Call from loop(). */
void tick();
/** `vehicle show | set final <x.xx> | set tyre <mm> | reset`. */
bool handleCommand(const char* line);
} // namespace Vehicle
File diff suppressed because it is too large Load Diff
+66 -128
View File
@@ -1,154 +1,92 @@
/*
* WiFi Manager Module
*
* Handles WiFi functionality for the Waveshare ESP32-S3-Touch-LCD-5B:
* - WiFi scanning and network discovery
* - Connection management with password entry
* - Dynamic SSID button generation
* - FreeRTOS task on Core 0 for async WiFi operations
* - Thread-safe UI updates via LVGL lock
* - Auto-restore WiFi state from NVS
* Joins one remembered network (for OTA updates) and scans on request. Owns no
* LVGL objects: the Settings screen polls getStatus()/getNetworks() and calls
* the request functions, so screen lifetimes can never leave dangling pointers
* here.
*
* Radio rules (the ESP-NOW link to Inst. Cluster shares the radio):
* - the radio stays in STA mode forever; "off" only stops association/scans.
* Never WiFi.disconnect(true) / WiFi.mode(WIFI_OFF) - that kills ESP-NOW.
* - scans only when asked (each one hops every channel);
* - no endless auto-reconnect: one attempt at boot, one after a drop, then
* idle on ESPNOW_CHANNEL until the user asks again.
*
* The network is remembered in NVS (namespace "wifi") after a successful join.
* The password is never printed.
*/
#pragma once
#include <Arduino.h>
#include <WiFi.h>
#include <lvgl.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
namespace WiFiManager {
// ============================================================================
// CONFIGURATION
// ============================================================================
#define WIFI_SCAN_MAX_NETWORKS 20
#define WIFI_SCAN_INTERVAL_MS 10000 // Rescan every 10 seconds when WiFi is ON
#define WIFI_CONNECT_TIMEOUT_MS 15000
#define WIFI_TASK_STACK_SIZE 4096
#define WIFI_TASK_PRIORITY 1
#define WIFI_TASK_CORE 0 // Run WiFi task on Core 0 (LVGL runs on Core 1)
#define WIFI_TASK_CORE 0
// ============================================================================
// PUBLIC TYPES
// ============================================================================
/**
* @brief WiFi state machine states
*/
typedef enum {
WIFI_STATE_OFF = 0,
WIFI_STATE_SCANNING,
WIFI_STATE_SCAN_COMPLETE,
WIFI_STATE_CONNECTED,
WIFI_STATE_CONNECTING,
WIFI_STATE_ERROR
} wifi_state_t;
LINK_OFF = 0, // Wi-Fi switched off
LINK_IDLE, // on, not connected, not trying
LINK_CONNECTING,
LINK_CONNECTED,
LINK_FAILED // last attempt failed; see status_t::error
} link_t;
/**
* @brief WiFi scan result structure
*/
typedef struct {
String ssid;
int32_t rssi;
wifi_auth_mode_t auth;
} wifi_network_t;
link_t link;
char ssid[33]; // network being joined / joined / that failed
char ip[16];
int rssi; // dBm, when connected
char error[48]; // human-readable reason when LINK_FAILED
char saved_ssid[33]; // remembered network ("" = none)
bool scanning;
uint32_t scan_gen; // bumps each time a scan completes
} status_t;
/**
* @brief WiFi connection credentials
*/
typedef struct {
char ssid[32];
char password[64];
} wifi_credentials_t;
char ssid[33];
int8_t rssi;
bool secured;
} network_t;
/** Start the Wi-Fi task. If enabled and a network is saved, joins it. */
void init(bool enabled);
/** Wi-Fi switch: persisted. On joins the saved network; off disconnects. */
void setEnabled(bool on);
bool isEnabled();
/** Scan once (ignored while off or already scanning). */
void requestScan();
/** Join a network; remembered if it works. pass may be NULL/"" for open networks. */
void connect(const char* ssid, const char* pass);
/** Join the remembered network again. */
void connectSaved();
/** Drop the remembered network and disconnect. */
void forget();
status_t getStatus();
/** Copy of the last scan (strongest first, one row per SSID). Returns the count. */
uint8_t getNetworks(network_t* out, uint8_t max);
/** Console: `wifi status | join <ssid> [pass] | forget | on | off`. */
bool handleCommand(const char* line);
/**
* @brief WiFi event types for FreeRTOS queue
* The remembered network, password included - for LinkPeer, which hands it to
* Inst. Cluster inside an encrypted frame. Never print the password.
* @return false if no network is saved
*/
typedef enum {
WIFI_UI_EVENT_TOGGLE_ON,
WIFI_UI_EVENT_TOGGLE_OFF,
WIFI_UI_EVENT_SCAN_START,
WIFI_UI_EVENT_SCAN_DONE,
WIFI_UI_EVENT_UPDATE_UI,
WIFI_UI_EVENT_CONNECT,
WIFI_UI_EVENT_DISCONNECT
} wifi_ui_event_type_t;
/**
* @brief WiFi queue event structure
*/
typedef struct {
wifi_ui_event_type_t type;
void* data;
} wifi_queue_event_t;
// ============================================================================
// PUBLIC API
// ============================================================================
/**
* @brief Initialize the WiFi manager subsystem
*
* This function:
* - Creates FreeRTOS mutex and queue
* - Spawns WiFi task on Core 0
* - Optionally auto-starts WiFi based on saved state
*
* @param auto_start If true, automatically start WiFi based on NVS saved state
*/
void init(bool auto_start);
/**
* @brief Get current WiFi state
* @return Current wifi_state_t value
*/
wifi_state_t getState();
/**
* @brief Get WiFi network count from last scan
* @return Number of networks found
*/
uint8_t getNetworkCount();
// ============================================================================
// EVENT HANDLERS (Called from SquareLine Studio UI)
// ============================================================================
/**
* @brief WiFi toggle event handler
* @param e LVGL event object
* @note This function is registered in SquareLine Studio UI
*/
void onWifiToggle(lv_event_t *e);
/**
* @brief SSID button click handler
* @param e LVGL event object
* @note Shows password entry for secured networks
*/
void onSSIDButtonClick(lv_event_t *e);
/**
* @brief Keyboard event handler for password entry
* @param e LVGL event object
* @note Handles READY (connect) and CANCEL events
*/
void onKeyboardEvent(lv_event_t *e);
/**
* @brief Manual rescan request handler
* @param e LVGL event object
*/
void onRescanRequest(lv_event_t *e);
/**
* @brief Legacy SquareLine Studio compatibility function
* @param e LVGL event object
* @note Kept for compatibility, but dynamic buttons handle clicks now
*/
void onSelectSSID(lv_event_t *e);
bool getSavedCredentials(char* ssid, size_t ssid_n, char* pass, size_t pass_n);
} // namespace WiFiManager
+98
View File
@@ -0,0 +1,98 @@
"""Scan a BMW KWP identifier space via A's `diag bmw` console command.
Sends one read-only request per identifier value (00..FF), waits for the
probe's reply line, and prints a summary of everything that answered
positively. Full console stream goes to wiki/raw/diagscan-<timestamp>.log.
Usage:
python tools/diag_scan.py COM10 21 # scan `21 xx` (readDataByLocalIdentifier)
python tools/diag_scan.py COM10 22D1 # scan `22 D1 xx` (readDataByCommonIdentifier)
python tools/diag_scan.py COM10 22D1 40 60 # optional sub-range [0x40..0x60)
"""
import os
import re
import sys
import time
import serial
port = sys.argv[1]
space = sys.argv[2].upper() # "21" or "22D1"
lo = int(sys.argv[3], 16) if len(sys.argv) > 3 else 0x00
hi = int(sys.argv[4], 16) if len(sys.argv) > 4 else 0x100
raw_dir = os.path.join(os.path.dirname(__file__), "..", "wiki", "raw")
log_path = os.path.join(raw_dir, time.strftime("diagscan-%%s-%Y%m%d-%H%M%S.log") % space)
log = open(log_path, "wb")
s = serial.Serial(port, 115200, timeout=0.05)
print("port open, waiting for boot...")
time.sleep(4)
s.reset_input_buffer()
hits = []
def txn(cmd, wait_s=1.5):
"""Send one diag command, return the probe's reply lines."""
s.write((cmd + "\n").encode())
s.flush()
log.write(("\n>>> %s\n" % cmd).encode())
end = time.time() + wait_s
pending = b""
replies = []
done = False
while time.time() < end and not done:
chunk = s.read(4096)
if not chunk:
continue
log.write(chunk)
pending += chunk
while b"\n" in pending:
line, pending = pending.split(b"\n", 1)
text = line.decode("utf-8", "replace").rstrip()
if "[diag]" in text:
replies.append(text)
if "<- 0x" in text or "no reply within" in text or "refused" in text:
done = True
return replies
try:
txn("diag raw off", wait_s=1.0)
for v in range(lo, hi):
if space == "21":
cmd = "diag bmw 12 21 %02X" % v
label = "21 %02X" % v
else:
cmd = "diag bmw 12 22 %s %02X" % (space[2:], v)
label = "22 %s %02X" % (space[2:], v)
replies = txn(cmd)
got = [r for r in replies if "<- 0x" in r]
if not got:
replies = txn(cmd) # one retry if the line got mangled
got = [r for r in replies if "<- 0x" in r]
if not got:
print("%s (no reply)" % label)
continue
r = got[-1]
if "7F" in r and "negative" not in r.lower() and "NRC" not in r:
pass
if re.search(r"7F \d\d [0-9A-F]{2}", r) or "NRC" in r or "negative" in r:
# negative response - only note interesting NRCs (not 0x12)
if "0x12" not in r and "NRC 0x12" not in r:
print("%s NEG: %s" % (label, r))
else:
print("%s HIT: %s" % (label, r))
hits.append((label, replies))
time.sleep(0.15)
finally:
txn("diag raw on", wait_s=1.0)
log.close()
s.close()
print("\n%d positive hits" % len(hits))
for label, replies in hits:
print("== " + label)
for r in replies:
print(" " + r)
print("log saved: " + os.path.abspath(log_path))
+70
View File
@@ -0,0 +1,70 @@
"""Run the Route A OBD-II diag probe sequence on Main CTRL and log everything.
Opens the port once (one reboot), waits for boot, then sends each diag command
with a generous wait, echoing replies and saving the full console stream
(CANRAW + CANTX + diag output) to wiki/raw/diag-<timestamp>.log.
Usage: python tools/diag_session.py COM10 [cmd [cmd ...]]
Default sequence: pids, pid 0C, pid 05, pid 0B, pid 70, vin, ecu, status.
"""
import os
import sys
import time
import serial
port = sys.argv[1] if len(sys.argv) > 1 else "COM10"
cmds = ["diag " + c for c in sys.argv[2:]] if len(sys.argv) > 2 else [
"diag pids",
"diag pid 0C",
"diag pid 05",
"diag pid 0B",
"diag pid 70",
"diag vin",
"diag ecu",
"diag status",
]
# pids walks up to 8 blocks with 500 ms timeouts each; give it room.
WAITS = {"diag pids": 15.0, "diag vin": 6.0, "diag ecu": 6.0}
DEFAULT_WAIT = 4.0
raw_dir = os.path.join(os.path.dirname(__file__), "..", "wiki", "raw")
log_path = os.path.join(raw_dir, time.strftime("diag-%Y%m%d-%H%M%S.log"))
log = open(log_path, "wb")
s = serial.Serial(port, 115200, timeout=0.1)
print("port open, waiting for boot...")
time.sleep(4)
def pump(seconds, echo_all=False):
"""Read for `seconds`, log everything, echo non-CANRAW lines."""
end = time.time() + seconds
pending = b""
while time.time() < end:
chunk = s.read(4096)
if not chunk:
continue
log.write(chunk)
pending += chunk
while b"\n" in pending:
line, pending = pending.split(b"\n", 1)
text = line.decode("utf-8", "replace").rstrip()
if echo_all or not text.startswith("CANRAW,"):
print(text)
log.flush()
try:
pump(2) # drain boot output
for cmd in cmds:
print("\n>>> " + cmd)
log.write(("\n>>> %s\n" % cmd).encode())
s.write((cmd + "\n").encode())
s.flush()
pump(WAITS.get(cmd, DEFAULT_WAIT))
finally:
log.close()
s.close()
print("\nlog saved: " + os.path.abspath(log_path))
+40
View File
@@ -0,0 +1,40 @@
"""Capture N seconds from two serial ports in parallel and print what arrived."""
import sys
import time
import threading
import serial
PORTS = sys.argv[1].split(",") if len(sys.argv) > 1 else ["COM8", "COM9"]
SECONDS = float(sys.argv[2]) if len(sys.argv) > 2 else 6.0
MAX_LINES = 40
def cap(port, out):
try:
s = serial.Serial(port, 115200, timeout=0.5)
end = time.time() + SECONDS
buf = b""
while time.time() < end:
buf += s.read(4096)
s.close()
out[port] = buf
except Exception as e:
out[port] = ("ERR: %s" % e).encode()
out = {}
threads = [threading.Thread(target=cap, args=(p, out)) for p in PORTS]
for t in threads:
t.start()
for t in threads:
t.join()
for p in PORTS:
data = out.get(p, b"")
print("=" * 20, p, "bytes:", len(data), "=" * 20)
lines = data.decode("utf-8", "replace").splitlines()
for ln in lines[:MAX_LINES]:
print(ln)
if len(lines) > MAX_LINES:
print("... (%d more lines)" % (len(lines) - MAX_LINES))
+4
View File
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE496tys+NeIrdDLNaGHLzr6L4oGmF
Y9brIfDTgn8IOWBm8J4nmLUef7zU4ydPM5BKXqUrTshJEpLd74GJIIOtkg==
-----END PUBLIC KEY-----
+103
View File
@@ -0,0 +1,103 @@
"""Display-performance session: stream PERF lines from Main CTRL to a log
while you provoke symptoms on the touchscreen (wiki open question #13).
Opens the port WITHOUT resetting the board (DTR/RTS low), turns on `perf on 1`,
then logs everything to wiki/raw/perf-<timestamp>.log until Ctrl+C. PERF lines
are echoed to the terminal. Anything you type is sent to the console, except
lines starting with '#', which are written into the log as markers - use them
to timestamp what you did on the screen:
# opened wifi page, scan running - dots visible
# tuning save
# ota install started
Usage: python tools/perf_session.py COM14 [period_seconds]
"""
import os
import sys
import threading
import time
from datetime import datetime
import serial
port = sys.argv[1] if len(sys.argv) > 1 else "COM14"
period = sys.argv[2] if len(sys.argv) > 2 else "1"
out_dir = os.path.join("wiki", "raw")
os.makedirs(out_dir, exist_ok=True)
path = os.path.join(out_dir, f"perf-{datetime.now():%Y%m%d-%H%M%S}.log")
s = serial.Serial()
s.port = port
s.baudrate = 115200
s.timeout = 0.2
s.dtr = False
s.rts = False
s.open()
stop = threading.Event()
lock = threading.Lock()
log = open(path, "w", encoding="utf-8", newline="\n")
def stamp():
return datetime.now().strftime("%H:%M:%S.%f")[:-3]
def write_log(line):
with lock:
log.write(f"{stamp()} {line}\n")
log.flush()
def reader():
while not stop.is_set():
raw = s.readline()
if not raw:
continue
line = raw.decode("utf-8", "replace").rstrip("\r\n")
write_log(line)
if line.startswith("PERF,") or "[perf]" in line or "[ota]" in line or "[wifi]" in line:
print(line)
def send(cmd):
write_log(f">>> {cmd}")
s.write((cmd + "\n").encode())
s.flush()
t = threading.Thread(target=reader, daemon=True)
t.start()
time.sleep(0.5)
send(f"perf on {period}")
print(f"logging to {path} (type console commands, '# note' for a marker, Ctrl+C to stop)")
print("columns: ts,fps,avg_ms,max_ms,kpx/frame,flush_ms/s,lvgl_idle%,idle0%,idle1%,int_free,int_largest,psram_free")
try:
while True:
line = sys.stdin.readline()
if not line:
time.sleep(0.2)
continue
line = line.rstrip("\r\n")
if not line:
continue
if line.startswith("#"):
write_log(f"### {line[1:].strip()}")
print(f"marker: {line[1:].strip()}")
else:
send(line)
except KeyboardInterrupt:
pass
finally:
try:
send("perf off")
time.sleep(0.3)
except Exception:
pass
stop.set()
s.close()
log.close()
print(f"\nsaved {path}")

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