63367f5490
- Delete .docs/CAN_BUS_INTEGRATION.md (placeholder CAN IDs, external transceiver wiring the board does not need); superseded by wiki/pages/can-id-candidates.md - Move UART_PROTOCOL.md to docs/ as the single copy of the packet spec - Move the annotated board photo into wiki/raw/ and add a source page for it - CLAUDE.md: verified 11-bit CAN ID list replaces the placeholders, TWAI_MODE_NORMAL replaces LISTEN_ONLY, UART TX is GPIO 44, dummy-data references removed - Wiki index/log updated; note the schematic PDF is missing from disk Co-Authored-By: Claude <noreply@anthropic.com>
389 lines
17 KiB
Markdown
389 lines
17 KiB
Markdown
# CLAUDE.md
|
||
|
||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||
|
||
## 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).
|
||
|
||
**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)
|
||
|
||
## Build & Development Commands
|
||
|
||
### PlatformIO CLI
|
||
|
||
```bash
|
||
# Build project (first build takes ~5-10 min, downloads libraries)
|
||
pio run
|
||
|
||
# Upload to board
|
||
pio run --target upload
|
||
|
||
# Monitor serial output (115200 baud)
|
||
pio device monitor
|
||
|
||
# Combined upload + monitor
|
||
pio run --target upload && pio device monitor
|
||
|
||
# Clean build
|
||
pio run --target clean
|
||
|
||
# Update libraries
|
||
pio lib update
|
||
|
||
# List available serial ports
|
||
pio device list
|
||
|
||
# Upload with manual port specification
|
||
pio run --target upload --upload-port /dev/ttyUSB0
|
||
```
|
||
|
||
### VS Code
|
||
|
||
Use PlatformIO extension toolbar:
|
||
- **Build**: Checkmark icon
|
||
- **Upload**: Arrow icon
|
||
- **Serial Monitor**: Plug icon
|
||
|
||
## Architecture
|
||
|
||
### Multi-Core FreeRTOS Design
|
||
|
||
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
|
||
- Touch input handling
|
||
- CPU load ~80% under normal operation
|
||
|
||
- **Core 0**: WiFi, UART, and CAN tasks (Priority 1)
|
||
- WiFi scanning task: Async network scanning every 10 seconds
|
||
- UART transmission task: 5Hz automotive data transmission
|
||
- CAN Bus task: Real-time CAN message reception and parsing
|
||
- All tasks use FreeRTOS queues for event communication
|
||
|
||
**Thread-Safety**: All UI updates from background tasks MUST acquire `lvgl_port_lock(-1)` before touching LVGL objects, and call `lvgl_port_unlock()` after.
|
||
|
||
### Component Structure
|
||
|
||
The project follows a clean, organized structure with logical separation of concerns:
|
||
|
||
```
|
||
src/
|
||
main.cpp # Main application logic only
|
||
modules/
|
||
wifi_manager.cpp # WiFi scanning and connection
|
||
uart_manager.cpp # UART transmission (5Hz)
|
||
settings_manager.cpp # NVS persistent storage
|
||
ui_state_manager.cpp # UI synchronization logic
|
||
display_init.cpp # Display initialization
|
||
drivers/
|
||
can_driver.cpp # CAN Bus driver (TWAI)
|
||
|
||
include/
|
||
config/
|
||
lv_conf.h # LVGL configuration
|
||
display/
|
||
lvgl_v8_port.h/cpp # LVGL porting layer for ESP32-S3
|
||
drivers/
|
||
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()`
|
||
|
||
**include/protocol/automotive_data.h**
|
||
- Defines `automotive_data_t` structure (6 sensor values: gear position, 3 temperatures, battery voltage, fault codes)
|
||
- UART packet framing protocol: `uart_packet_t` with start/end markers (0xAA/0x55), version byte, XOR checksum
|
||
- Helper functions: `calculate_checksum()`, `validate_packet()`, temperature/voltage formatters
|
||
- **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
|
||
|
||
**include/drivers/can_driver.h/cpp**
|
||
- CAN Bus driver using ESP32 TWAI (Two-Wire Automotive Interface)
|
||
- Hardware: GPIO 15 (TX), GPIO 16 (RX) - 500 Kbps baud rate
|
||
- Mode: TWAI_MODE_NORMAL (ACKs frames; LISTEN_ONLY caused transmitter retry-flooding). Firmware never sends data frames
|
||
- Parses BMW-specific CAN messages and updates shared automotive data structure
|
||
- Task runs on Core 0 with FreeRTOS queue for start/stop commands
|
||
|
||
**include/display/lvgl_v8_port.h/cpp**
|
||
- LVGL 8.4.0 porting layer for ESP32-S3
|
||
- Display buffer config: 60-line height single buffer in DMA-capable SRAM for performance
|
||
- Task config: 6KB stack, Priority 2, pinned to Core 1
|
||
- **Critical**: `lvgl_port_lock()` / `unlock()` for thread-safe LVGL calls from non-LVGL tasks
|
||
|
||
**include/config/lv_conf.h**
|
||
- LVGL 8.4.0 configuration file
|
||
- Memory settings, theme configuration, widget enables
|
||
|
||
**include/ui/** directory (SquareLine Studio exports)
|
||
- `ui_Home_Screen.c/h`: Main display screen
|
||
- `ui_Settings_Screen.c/h`: WiFi, UART, CAN Bus, Debug toggle switches and containers
|
||
- 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/`
|
||
|
||
### 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)
|
||
- Functions: `saveWiFiState()`, `loadWiFiState()`, `saveUARTState()`, `loadUARTState()`, `saveCANState()`, `loadCANState()`, `saveDebugState()`, `loadDebugState()`
|
||
|
||
### WiFi Architecture
|
||
|
||
**State Machine**: `WIFI_STATE_OFF` → `WIFI_STATE_SCANNING` → `WIFI_STATE_SCAN_COMPLETE` → `WIFI_STATE_CONNECTED`
|
||
|
||
**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
|
||
|
||
### UART Architecture
|
||
|
||
**Transmission Protocol**:
|
||
- Packet structure: `uart_packet_t` = Start(0xAA) + Version + Length + `automotive_data_t` + Checksum(XOR) + End(0x55)
|
||
- Transmission rate: 5Hz (every 200ms) when enabled
|
||
- Hardware: Serial1 TX GPIO 44 / RX GPIO 43 (RS485 terminal block on board)
|
||
|
||
**Task Flow**:
|
||
- `uartTask()` runs on Core 0
|
||
- Events via `g_uart_event_queue`: `UART_EVENT_START`, `UART_EVENT_STOP`, `UART_EVENT_SEND_DATA`
|
||
- Default data: `initializeDefaultData()` seeds the structure until CAN updates it; the dummy generator was removed
|
||
- Actual transmission: `sendUARTPacket()` builds packet, calculates checksum, sends via `Serial1.write()`
|
||
- Mutex protection: `g_data_mutex` guards `g_automotive_data` structure
|
||
|
||
**CAN Bus Integration**:
|
||
- CAN driver reads BMW-specific messages and updates `g_automotive_data`
|
||
- UART auto-starts/stops with the CAN task (`linkToCANState()`); no dummy simulation remains
|
||
- Shared data structure (`g_automotive_data`) is mutex-protected for thread safety
|
||
|
||
### CAN Bus Architecture
|
||
|
||
**Hardware Configuration**:
|
||
- Controller: ESP32-S3 TWAI (Two-Wire Automotive Interface)
|
||
- Pins: GPIO 15 (TX), GPIO 16 (RX)
|
||
- Baud Rate: 500 Kbps (BMW standard)
|
||
- Mode: TWAI_MODE_NORMAL (ACKs frames; never transmits data frames)
|
||
|
||
**BMW CAN Message IDs** (all 11-bit standard frames, verified live; full decode in `wiki/pages/can-id-candidates.md`):
|
||
- `0x1D0` [byte 0] → Coolant temperature (raw − 48 °C); [byte 1] engine oil temp (reads 0xFF on this M57N); [byte 2 bits 4-5] engine run state
|
||
- `0x0B5` [byte 7] → Gearbox oil temperature (raw − 40 °C); [byte 4 bits 6-7] cooling demand
|
||
- `0x1D2` [byte 0] → Gear lever (E1=P D2=R B4=N 78=D/S/M); [byte 1] engaged gear; [byte 4] drive/sport/manual mode
|
||
- `0x0BA` [byte 0 low nibble] → Gearbox target gear incl. reverse; [bits 6-7] converter lockup; [bytes 3-4] output shaft speed (scaling open)
|
||
- `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
|
||
|
||
**Task Flow**:
|
||
- `canTask()` runs on Core 0 with Priority 1
|
||
- Events via `g_can_event_queue`: `CAN_EVENT_START`, `CAN_EVENT_STOP`
|
||
- Message parsing: `parseCANMessage()` extracts data from specific CAN IDs
|
||
- Data updates: Acquires `g_data_mutex`, updates `g_automotive_data`, releases mutex
|
||
- Statistics tracking: Messages received, parsed, errors
|
||
|
||
**Safety Features**:
|
||
- NORMAL mode: the controller ACKs received frames; the firmware has no transmit path for data frames
|
||
- Error detection: Bus errors, queue overflow, passive errors
|
||
|
||
**See Also**: `wiki/pages/can-id-candidates.md` for the verified CAN ID map and evidence, `wiki/pages/can-bus-integration.md` for integration notes
|
||
|
||
### UI State Synchronization
|
||
|
||
**Problem**: SquareLine Studio screens get destroyed/recreated when swiping between screens, losing runtime state.
|
||
|
||
**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
|
||
|
||
**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()`
|
||
|
||
## Configuration Files
|
||
|
||
**platformio.ini**
|
||
- 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
|
||
- Debug level: `CORE_DEBUG_LEVEL=1` (1=Error, 5=Verbose)
|
||
- Libraries: ESP32_Display_Panel v1.0.4, LVGL 8.4.0 (from GitHub)
|
||
|
||
**boards/esp32-s3-wroom-1-n16r8.json** (Custom Board Definition)
|
||
- Flash: 16MB QIO mode @ 80MHz
|
||
- PSRAM: 8MB OPI mode
|
||
- CPU: 240MHz
|
||
- Partition table: `partition_table.csv`
|
||
- 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)
|
||
- Coredump: 64KB @ 0xFF0000 (crash debugging)
|
||
|
||
**include/lv_conf.h**
|
||
- LVGL 8.4.0 configuration
|
||
- Memory: Uses PSRAM for large objects
|
||
- Theme: Material theme enabled
|
||
|
||
## Common Patterns
|
||
|
||
### Adding a New Toggle Switch
|
||
|
||
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
|
||
|
||
### Thread-Safe UI Update from Background Task
|
||
|
||
```cpp
|
||
void myBackgroundTask(void* param) {
|
||
while (true) {
|
||
// Do background work...
|
||
|
||
// Update UI (MUST use LVGL lock!)
|
||
lvgl_port_lock(-1); // Wait indefinitely for lock
|
||
lv_label_set_text(my_label, "Updated from task");
|
||
lvgl_port_unlock();
|
||
|
||
vTaskDelay(pdMS_TO_TICKS(100));
|
||
}
|
||
}
|
||
```
|
||
|
||
### Creating FreeRTOS Task on Specific Core
|
||
|
||
```cpp
|
||
TaskHandle_t task_handle = NULL;
|
||
QueueHandle_t event_queue = xQueueCreate(10, sizeof(my_event_t));
|
||
|
||
xTaskCreatePinnedToCore(
|
||
myTaskFunction, // Task function
|
||
"MyTask", // Task name (for debugging)
|
||
4096, // Stack size (bytes)
|
||
NULL, // Parameters
|
||
1, // Priority (1=normal, 2=high)
|
||
&task_handle, // Task handle output
|
||
0 // Core (0 or 1)
|
||
);
|
||
```
|
||
|
||
## Hardware-Specific Details
|
||
|
||
### GPIO Assignments
|
||
|
||
- **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
|
||
- **USB Serial**: UART0 (default Serial) - 115200 baud for debug output
|
||
|
||
### Display Panel
|
||
|
||
- Resolution: 1024x600 RGB888
|
||
- Driver: ESP32_Display_Panel library (v1.0.4)
|
||
- Backlight control: Manual on/off to prevent white flash during boot (see setup() steps 9, 14)
|
||
- Buffer: 60-line height (1024 * 60 * 2 bytes) in DMA-capable SRAM
|
||
|
||
### Memory Management
|
||
|
||
- **PSRAM**: Required for LVGL framebuffers and large objects (8MB OPI PSRAM)
|
||
- **Flash**: 16MB total (3MB app partition allows large UI assets)
|
||
- **Heap**: Monitor with `ESP.getFreeHeap()` if adding features
|
||
|
||
## Troubleshooting
|
||
|
||
### Build Errors
|
||
|
||
- **Missing libraries**: Run `pio lib update` then `pio run --target clean`
|
||
- **Partition table not found**: Ensure `partition_table.csv` exists in project root
|
||
- **Out of memory**: Check PSRAM enabled (`board_build.psram_type = opi` in platformio.ini)
|
||
|
||
### Upload Issues
|
||
|
||
- **Port not detected**: Run `pio device list`, manually specify with `--upload-port`
|
||
- **Permission denied (Linux)**: Add user to dialout group: `sudo usermod -a -G dialout $USER` (log out/in required)
|
||
|
||
### Runtime Issues
|
||
|
||
- **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
|
||
- **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:
|
||
1. Creating custom board definition `boards/esp32-s3-wroom-1-n16r8.json` with correct PSRAM settings (`qio_opi` memory type)
|
||
2. Updating partition table `partition_table.csv` to use full 16MB flash (12.5MB app, 3.375MB SPIFFS)
|
||
3. Adjusting LCD timing in board header (16MHz pixel clock, correct PCLK polarity)
|
||
4. Removing unnecessary loading spinner delay from `applySavedStatesToUI()` function
|
||
|
||
**Important**: The original ESP32_Display_Panel library works perfectly without modifications when the board configuration and partition table are correct!
|
||
|
||
## Performance Metrics
|
||
|
||
- **FPS**: ~50 FPS @ 1024x600 resolution
|
||
- **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
|
||
- **Build Time**: First build ~5-10 min (library downloads), incremental ~10-30 sec
|
||
|
||
## 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`
|
||
- **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`
|
||
- **Security**: Password field (`uic_Wifi_Passkey_TB`) is cleared after connection attempt for security (line 1015, 1029)
|