Link protocol v2, ESP-NOW leg, gauge tunables + tuning screen; remove Home screen

Protocol v2 (shared header, byte-identical with the 1.3 repo):
- typed DATA/CONFIG frames: 0xAA | ver | type | len | payload | XOR | 0x55
- gear split into lever (P/R/N/D/S/M) + target/engaged nibbles, engine rpm,
  alert bitmap decided here from tunable thresholds, link_config_t tunables
- docs/UART_PROTOCOL.md rewritten for v2

Controller A modules:
- tunables: gauge calibration + alert thresholds in NVS, 'cfg' serial console,
  bench override (never persisted)
- espnow_link: every frame also broadcast on ESP-NOW ch 1; radio stays in STA
  (WiFiManager no longer powers it off)
- uart_manager: DATA at 5 Hz + CONFIG on change/5 s on both transports
- can_driver: publishes gear pieces and rpm, evaluates alerts
- tuning_screen: hand-coded Gauge Tuning page (swipe right from Driveline),
  -/+ rows, enable switches, override sliders, Driveline/Defaults buttons

UI: SquareLine Home screen (3 meters + battery) and meters_manager removed;
Driveline is the boot screen; Settings back-gesture calls app_show_driveline().

tools/fix_penv_deps.ps1: repairs the shared PlatformIO penv after a 1.3 build.
Bench-verified with Controller B: both transports alive, dedupe, override
rpm 2000 -> 133.3 Hz tach output.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-21 19:12:31 +02:00
parent a8f68ebc27
commit f60bdac268
33 changed files with 1743 additions and 2266 deletions
+90 -611
View File
@@ -1,656 +1,135 @@
# UART Protocol Specification
# Link Protocol Specification (v2)
**Version:** 1.0
**Last Updated:** 2025-11-09
**Author:** BMW Patrol Project
**Target Hardware:** ESP32-S3-Touch-LCD-5B → ESP32-S3-Touch-LCD-1.3
**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.
---
## Overview
## Transports
This document describes the UART communication protocol used to transmit automotive sensor data from **Controller A** (ESP32-S3-Touch-LCD-5B, 5-inch display) to **Controller B** (ESP32-S3-Touch-LCD-1.3, 1.3-inch display).
The same frames are sent on two paths at once. B accepts either and deduplicates DATA frames on `packet_id` + `timestamp_ms`.
Controller A receives BMW CAN bus messages, parses the vehicle sensor data, and forwards it via UART to Controller B for display on the smaller dashboard screen.
| Path | A side | B side | Notes |
|---|---|---|---|
| UART1 | GPIO 44 TX → SP3485 → terminal `485_A` / `485_B` | IO1 RX (left header pin 4) | 115200 8N1. Bench: `485_A` straight into IO1 + GND works (unterminated, biased high). Car: RS485 transceiver on B, or rely on ESP-NOW. |
| ESP-NOW | broadcast, Wi-Fi channel `ESPNOW_CHANNEL` (1) | listens; hops channels 1–13 while silent, locks when frames arrive | A's radio stays in STA mode permanently. If A joins an access point the channel follows the AP; B finds it by hopping. |
---
## Physical Layer
### Hardware Configuration
| Parameter | Value | Notes |
|-----------|-------|-------|
| **Baud Rate** | 115200 bps | Standard UART speed |
| **Data Bits** | 8 | No parity |
| **Stop Bits** | 1 | Standard framing |
| **Flow Control** | None | Simple 2-wire TX/RX |
| **Voltage Level** | 3.3V TTL | ESP32 GPIO levels |
| **Connector** | GPIO Headers | Direct GPIO-to-GPIO connection |
### Pin Mapping
**Controller A (Transmitter - 5B):**
- TX: GPIO 44
- RX: GPIO 43 (unused - transmit-only mode)
**Controller B (Receiver - 1.3):**
- RX: GPIO 1 (IO1)
- TX: Not used (receive-only mode)
### Wiring
Simple 3-wire connection:
- Controller A GPIO 44 → Controller B GPIO 1 (data line)
- GND → GND (common ground required)
- VCC: Both powered independently (no power sharing)
---
## Protocol Layer
### Transmission Characteristics
| Parameter | Value | Notes |
|-----------|-------|-------|
| **Transmission Rate** | 5 Hz (200ms intervals) | Periodic updates |
| **Packet Format** | Binary framed packet | Fixed-length structure |
| **Error Detection** | XOR checksum | Single-byte validation |
| **Start Marker** | 0xAA | Packet synchronization |
| **End Marker** | 0x55 | Packet boundary detection |
| **Total Packet Size** | 23 bytes | Fixed length |
### State Machine
**Controller A (Transmitter):**
1. UART OFF → CAN disabled
2. CAN Toggle ON → CAN starts → UART auto-starts
3. UART transmits real-time CAN data at 5 Hz
4. CAN Toggle OFF → CAN stops → UART auto-stops
**Controller B (Receiver):**
- Continuously listens on UART RX
- Validates packet markers and checksum
- Parses automotive data structure
- Updates display with latest values
---
## Packet Structure
### Binary Frame Format
Total packet size: **23 bytes**
## Frame format (both transports)
```
┌─────────┬─────────┬────────┬──────────────────┬──────────┬─────────┐
│ START │ VERSION │ LENGTH │ PAYLOAD (DATA) │ CHECKSUM │ END │
├─────────┼─────────┼────────┼──────────────────┼──────────┼─────────┤
│ 0xAA │ 0x01 │ 0x12 │ 18 bytes │ 1 byte │ 0x55 │
│ 1 byte │ 1 byte │ 1 byte │ │ (XOR) │ 1 byte │
└─────────┴─────────┴────────┴──────────────────┴──────────┴─────────┘
0xAA | version | type | length | payload[length] | checksum | 0x55
```
### Field Descriptions
| Field | Size | Value |
|---|---|---|
| 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) |
| payload | length | see below, little-endian, packed |
| checksum | 1 | XOR of version, type, length and every payload byte |
| end | 1 | `0x55` |
#### Header (3 bytes)
| Offset | Size | Name | Value | Description |
|--------|------|------|-------|-------------|
| 0 | 1 | Start Marker | 0xAA | Fixed synchronization byte |
| 1 | 1 | Protocol Version | 0x01 | Current protocol version |
| 2 | 1 | Payload Length | 0x12 (18 decimal) | Data section size in bytes |
#### Payload - Automotive Data (18 bytes)
| Offset | Size | Name | Data Type | Unit | Range | Description |
|--------|------|------|-----------|------|-------|-------------|
| 3 | 4 | Timestamp | uint32_t (LE) | milliseconds | 0 - 4,294,967,295 | System uptime when packet created |
| 7 | 1 | Packet ID | uint8_t | counter | 0 - 255 | Rolling packet counter (wraps at 255) |
| 8 | 1 | Gear Position | uint8_t | enum | 0 - 14 | Current transmission gear/mode |
| 9 | 2 | Coolant Temp | int16_t (LE) | 0.1°C | -400 to 2150 | Engine coolant temperature × 10 |
| 11 | 2 | Engine Oil Temp | int16_t (LE) | 0.1°C | -400 to 2150 | Engine oil temperature × 10 |
| 13 | 2 | Gearbox Temp | int16_t (LE) | 0.1°C | -400 to 2150 | Transmission fluid temperature × 10 |
| 15 | 2 | Battery Voltage | uint16_t (LE) | 0.01V | 0 - 655.35 | Battery voltage × 100 |
| 17 | 2 | Fault Codes | uint16_t (LE) | bitfield | 0 - 65535 | Active diagnostic fault codes |
| 19 | 1 | Valid Flags | uint8_t | bitfield | 0 - 255 | Data validity indicators |
| 20 | 1 | Debug Enabled | uint8_t | boolean | 0 or 1 | Debug mode flag (0=OFF, 1=ON) |
**Note:** LE = Little-Endian byte order (least significant byte first)
#### Trailer (2 bytes)
| Offset | Size | Name | Description |
|--------|------|------|-------------|
| 21 | 1 | Checksum | XOR of all bytes from offset 1 to 20 (inclusive) |
| 22 | 1 | End Marker | Fixed value 0x55 for packet boundary |
DATA frame = 27 bytes, CONFIG frame = 33 bytes. Helpers: `frame_build()`, `frame_parse()` in the header.
---
## Data Encoding Details
## DATA payload — `automotive_data_t` (21 bytes, every 200 ms)
### Temperature Fields
| Offset | Size | Field | Unit / encoding |
|---|---|---|---|
| 0 | 1 | `packet_id` | rolling counter |
| 1 | 4 | `timestamp_ms` | A's `millis()` |
| 5 | 1 | `gear_lever` | `gear_lever_t`: 0 P, 1 R, 2 N, 3 D, 4 S, 5 M, 0xFF unknown |
| 6 | 1 | `gear_nibbles` | high nibble = gearbox **target** gear (CAN 0x0BA), low nibble = **engaged** gear (CAN 0x1D2 byte 1); 0 = none/P/R/N, 1–6 forward gears. `target != engaged` ⇒ shift in progress |
| 7 | 2 | `engine_rpm` | 1/min (CAN 0x0AA) |
| 9 | 2 | `gearbox_oil_temp` | 0.1 °C signed |
| 11 | 2 | `engine_oil_temp` | 0.1 °C signed — no sensor on this M57N, never valid |
| 13 | 2 | `coolant_temp` | 0.1 °C signed |
| 15 | 2 | `battery_voltage` | 0.01 V |
| 17 | 2 | `alerts` | bitmap, decided on A (below) |
| 19 | 1 | `valid_flags` | bitmap (below) |
| 20 | 1 | `debug_enabled` | 0/1, B mirrors A's debug overlay toggle |
**Format:** Signed 16-bit integer (int16_t), little-endian
**Units:** Tenths of degrees Celsius (0.1°C precision)
**Encoding:** `raw_value = actual_temperature × 10`
`valid_flags`: bit0 gear, bit1 gearbox temp, bit2 engine oil temp, bit3 coolant, bit4 battery, bit5 alerts, bit6 rpm. A field is meaningful only when its bit is set. On the bench without CAN, A sends default temperatures/voltage marked valid but **never** marks rpm or gear nibbles valid.
**Examples:**
- 85.0°C → Transmitted as: 850 (0x52 0x03 in little-endian)
- 104.7°C → Transmitted as: 1047 (0x17 0x04 in little-endian)
- -12.5°C → Transmitted as: -125 (0x83 0xFF in little-endian, two's complement)
`alerts` (thresholds come from A's tunables):
**Typical Range:**
- Coolant: 60°C to 110°C (600 to 1100)
- Engine Oil: 80°C to 140°C (800 to 1400)
- Gearbox: 60°C to 120°C (600 to 1200)
| Bit | Name | Condition |
|---|---|---|
| 0 | `ALERT_GEAR_MISMATCH` | lever (0x1D2) and gearbox target (0x0BA) disagree beyond the debounce |
| 1 | `ALERT_COOLANT_HOT` | coolant ≥ `coolant_hot_c` |
| 2 | `ALERT_GEARBOX_HOT` | gearbox oil ≥ `gearbox_hot_c` |
| 3 | `ALERT_GEARBOX_COOLING` | gearbox's own cooling demand (0x0B5 ST_OTMP_GRB ≥ 1) |
| 4 | `ALERT_BATTERY_LOW` | battery < `battery_low_x100` |
**Special Values:**
- -400 (0xFF70): Sensor error or not available
- 2150 (0x086E): Over-temperature fault
### Battery Voltage
**Format:** Unsigned 16-bit integer (uint16_t), little-endian
**Units:** Hundredths of volts (0.01V precision)
**Encoding:** `raw_value = actual_voltage × 100`
**Examples:**
- 12.45V → Transmitted as: 1245 (0xDD 0x04 in little-endian)
- 14.23V → Transmitted as: 1423 (0x8F 0x05 in little-endian)
- 11.80V → Transmitted as: 1180 (0x9C 0x04 in little-endian)
**Typical Range:**
- Normal operation: 12.0V to 14.5V (1200 to 1450)
- Engine off: 12.3V to 12.8V (1230 to 1280)
- Charging: 13.8V to 14.4V (1380 to 1440)
**Warning Thresholds:**
- Low voltage: < 12.0V (1200)
- High voltage: > 15.0V (1500)
### Gear Position Enumeration
**Format:** Unsigned 8-bit integer (uint8_t)
**Encoding:** Single byte representing transmission state
| Value | Name | Display | Description |
|-------|------|---------|-------------|
| 0 | GEAR_PARK | P | Park - transmission locked |
| 1 | GEAR_REVERSE | R | Reverse gear |
| 2 | GEAR_NEUTRAL | N | Neutral - no gear engaged |
| 3 | GEAR_DRIVE | D | Drive - automatic mode |
| 4 | GEAR_SPORT | S | Sport mode |
| 5 | GEAR_MANUAL | M | Manual/Sequential mode |
| 6 | GEAR_MANUAL_1 | 1 | Manual 1st gear |
| 7 | GEAR_MANUAL_2 | 2 | Manual 2nd gear |
| 8 | GEAR_MANUAL_3 | 3 | Manual 3rd gear |
| 9 | GEAR_MANUAL_4 | 4 | Manual 4th gear |
| 10 | GEAR_MANUAL_5 | 5 | Manual 5th gear |
| 11 | GEAR_MANUAL_6 | 6 | Manual 6th gear |
| 12 | GEAR_MANUAL_7 | 7 | Manual 7th gear |
| 13 | GEAR_MANUAL_8 | 8 | Manual 8th gear |
| 14 | GEAR_ERROR | ? | Transmission fault/unknown |
**Note:** BMW automatic transmissions typically use P/R/N/D/S modes. Manual mode (M) with sequential shifting shows the current selected gear (1-8).
### Fault Codes Bitfield
**Format:** Unsigned 16-bit integer (uint16_t), little-endian
**Encoding:** Each bit represents a specific fault condition
| Bit | Mask | Fault Name | Description |
|-----|------|------------|-------------|
| 0 | 0x0001 | ENGINE_FAULT | Check engine light / MIL |
| 1 | 0x0002 | TRANSMISSION_FAULT | Transmission system error |
| 2 | 0x0004 | ABS_FAULT | Anti-lock braking system fault |
| 3 | 0x0008 | AIRBAG_FAULT | SRS airbag system fault |
| 4 | 0x0010 | BATTERY_FAULT | Charging system fault |
| 5 | 0x0020 | COOLANT_FAULT | Coolant temperature warning |
| 6 | 0x0040 | OIL_PRESSURE_FAULT | Low oil pressure warning |
| 7 | 0x0080 | BRAKE_FAULT | Brake system warning |
| 8-15 | 0xFF00 | RESERVED | Reserved for future use |
**Examples:**
- 0x0000: No faults
- 0x0001: Engine fault only
- 0x0003: Engine + Transmission faults (bits 0 and 1 set)
- 0x0021: Engine + Coolant faults (bits 0 and 5 set)
**Note:** Multiple faults can be active simultaneously. Check each bit independently.
### Valid Flags Bitfield
**Format:** Unsigned 8-bit integer (uint8_t)
**Encoding:** Each bit indicates if corresponding data field is valid
| Bit | Mask | Field Name | Description |
|-----|------|------------|-------------|
| 0 | 0x01 | VALID_GEAR_POS | Gear position data is valid |
| 1 | 0x02 | VALID_GEARBOX_TEMP | Gearbox temperature is valid |
| 2 | 0x04 | VALID_ENGINE_TEMP | Engine oil temperature is valid |
| 3 | 0x08 | VALID_COOLANT_TEMP | Coolant temperature is valid |
| 4 | 0x10 | VALID_BATTERY_VOLT | Battery voltage is valid |
| 5 | 0x20 | VALID_FAULT_CODES | Fault codes are valid |
| 6-7 | 0xC0 | RESERVED | Reserved for future use |
**Usage:**
- **All bits set (0x3F):** All data fields contain valid readings from CAN bus
- **Bit cleared (0):** Corresponding field may contain stale/default/invalid data
- **Example (0x1F):** All fields valid except fault codes (bit 5 cleared)
**Important:** Receivers should check validity flags before using sensor data. Invalid data should be ignored or displayed with a warning indicator.
### Debug Flag
**Format:** Unsigned 8-bit integer (uint8_t)
**Values:**
- 0x00: Debug mode OFF (normal operation)
- 0x01: Debug mode ON (verbose logging enabled on Controller B)
**Purpose:** Controls diagnostic logging and performance monitoring on the receiver. When enabled, Controller B may display:
- FPS (frames per second)
- CPU usage statistics
- Packet reception statistics
- Parse error counts
Severity for display: bits 0, 1, 2, 4 are red alarms; bit 3 is amber.
---
## Checksum Algorithm
## CONFIG payload — `link_config_t` (27 bytes; on start, on every change, and every 5 s)
### XOR Checksum Calculation
Tunables edited on A (serial console `cfg ...`, NVS-backed), executed on B's gauge outputs.
**Algorithm:** Simple XOR of all bytes in the packet (excluding start marker and checksum itself)
| Field | Size | Default | Meaning |
|---|---|---|---|
| `cfg_version` | 1 | 1 | bumped on every change; B applies when it changes |
| `tach_ppr` | 1 | 4 | tach pulses per engine revolution |
| `tach_trim_pct` | 1 | 0 | fine trim −50…+50 % |
| `tach_min_hz` | 2 | 0 | 0 = no clamp |
| `tach_max_hz` | 2 | 600 | 0 = no clamp |
| `temp_pwm_hz` | 2 | 1000 | coolant PWM frequency |
| `temp_slope_x100` | 2 | 150 | duty per °C ×100 |
| `temp_offset` | 2 | 50 | duty at 0 °C |
| `temp_min_c` | 2 | 40 | output off below this coolant temperature |
| `temp_duty_max` | 1 | 255 | clamp |
| `out_enable` | 1 | 0x03 | bit0 tach, bit1 temp |
| `override_mode` | 1 | 0 | bit0 force tach rpm, bit1 force temp duty (bench tool, never persisted) |
| `override_rpm` | 2 | 0 | |
| `override_duty` | 1 | 0 | |
| `coolant_hot_c` | 2 | 100 | alert threshold |
| `gearbox_hot_c` | 2 | 130 | alert threshold |
| `battery_low_x100` | 2 | 1100 | alert threshold (0.01 V) |
**Range:** Bytes from offset 1 to 20 (inclusive)
**Fields included:**
- Protocol version (offset 1)
- Length (offset 2)
- All payload data (offsets 3-20)
Coolant duty law: `duty = temp_slope_x100 × T°C / 100 + temp_offset`, clamped to `0…temp_duty_max`, 0 while `T < temp_min_c`. Defaults reproduce the user's earlier CANNY program (`1.5·T + 50`).
**Fields excluded:**
- Start marker (offset 0) - not included
- Checksum itself (offset 21) - calculated result
- End marker (offset 22) - not included
**Process:**
1. Initialize checksum to 0x00
2. XOR with version byte
3. XOR with length byte
4. XOR with all 18 payload bytes in sequence
5. Result is the checksum value
**Validation:**
Receiver must recalculate checksum using the same algorithm and compare with received checksum byte. If mismatch occurs, the packet is corrupted and must be discarded.
Tach: `f = rpm × tach_ppr / 60 × (1 + trim/100)`, clamped, 50 % duty. Output low when rpm is invalid, zero, the link is down, or the output is disabled.
---
## Error Handling
### Packet Validation Rules
A valid packet MUST satisfy ALL of the following conditions:
1. **Start Marker Check:** First byte == 0xAA
2. **End Marker Check:** Last byte (offset 22) == 0x55
3. **Version Check:** Protocol version == 0x01
4. **Length Check:** Payload length == 0x12 (18 bytes)
5. **Checksum Validation:** Calculated checksum matches received checksum
### Error Recovery
**On Validation Failure:**
1. Discard the corrupted packet
2. Increment error counter (for diagnostics)
3. Continue listening for next valid start marker (0xAA)
4. Do NOT update display with invalid data
**On Missing Packets:**
- If no valid packet received within 1 second:
- Display last known valid data
- Show "STALE DATA" warning indicator
- Continue using cached values
**On Checksum Error:**
- Common cause: Noise on UART line or baud rate mismatch
- Check physical wiring (crosstalk, EMI)
- Verify both devices configured for 115200 baud
**On Continuous Errors (>10 consecutive failures):**
- Display "UART FAULT" error
- Consider communication link broken
- May indicate hardware failure or disconnection
---
## Data Source
### CAN Bus Origin
All automotive sensor data originates from BMW CAN bus messages received by Controller A:
| Data Field | CAN Message ID | Byte Position | Notes |
|------------|----------------|---------------|-------|
| Coolant Temperature | 0x4F | Byte 0 | Standard 11-bit ID |
| Engine Oil Temperature | 0x55 | Byte 7 | Standard 11-bit ID |
| Gearbox Temperature | 0x201 | Byte 3 | Standard 11-bit ID |
| Gear Position | 0x1001 | Byte 0 | Extended 29-bit ID |
| Current Gear (1-8) | 0x1001 | Byte 1 | Same message as position |
| Battery Voltage | 0x101F | Bytes 0-1 (16-bit) | Extended 29-bit ID |
**CAN Bus Configuration:**
- Speed: 500 Kbps (BMW K-CAN standard)
- Mode: NORMAL (can send ACK bits)
- GPIOs: TX=GPIO15, RX=GPIO16
- Reception rate: ~25 messages/second (5 unique IDs at 5 Hz)
**Data Flow:**
```
BMW Vehicle CAN Bus
↓
Controller A (ESP32-S3-LCD-5B)
- CAN driver receives messages
- Parses BMW protocol
- Updates shared data structure
↓
UART Transmitter (5 Hz)
- Reads shared data (mutex protected)
- Builds binary packet
- Transmits via GPIO 44
↓
Controller B (ESP32-S3-LCD-1.3)
- Receives on GPIO 1
- Validates packet
- Updates 1.3-inch display
```
### Data Freshness
**Timestamp Field:**
- Represents Controller A system uptime when packet was created
- Updates every 200ms (5 Hz rate)
- Used to detect communication delays or stale data
- Wraps around every ~49.7 days (uint32_t milliseconds)
**Receiver Freshness Check:**
Compare consecutive packet timestamps. If delta != ~200ms, possible issues:
- Delta < 150ms: Duplicate packet or clock skew
- Delta > 300ms: Missed packet(s) or transmission delay
- Delta > 1000ms: Communication interrupted
---
## Timing Specifications
### Transmission Schedule
| Parameter | Value | Tolerance | Notes |
|-----------|-------|-----------|-------|
| **Update Rate** | 200ms (5 Hz) | ±10ms | Periodic transmission |
| **Packet Duration** | ~2ms | - | At 115200 baud, 23 bytes |
| **Inter-Packet Gap** | ~198ms | - | Time between end and next start |
| **Startup Delay** | < 100ms | - | From CAN toggle to first packet |
### Receiver Requirements
**Minimum Buffer Size:** 32 bytes recommended
- Allows buffering of 1 complete packet plus margin
- Prevents overflow during processing
**Processing Time:** < 50ms per packet
- Parse and validate packet
- Update display data
- Must complete before next packet arrives
**Synchronization:**
- Listen for 0xAA start marker continuously
- No strict timing requirement (asynchronous)
- Packet boundaries defined by markers, not timing
---
## Interoperability
### Protocol Versioning
**Current Version:** 0x01 (version byte at offset 1)
**Future Version Changes:**
If protocol structure changes, version byte will increment:
- Version 0x02: May add new fields or change packet size
- Receivers MUST check version byte
- Unknown versions should be rejected
**Backward Compatibility:**
This specification (v1.0) guarantees:
- Packet structure fixed at 23 bytes
- Field offsets will not change
- New versions will use different version byte
### Multi-Language Support
This protocol is binary and language-agnostic. Compatible with:
- C/C++ (native on ESP32)
- Python (struct module for packing/unpacking)
- Rust (byteorder crate)
- Any language with binary I/O support
**Endianness Requirement:**
All multi-byte fields use **little-endian** byte order to match ESP32 native format. Non-ESP32 receivers must handle endianness conversion if needed.
---
## Security Considerations
### Protocol Limitations
**This protocol does NOT provide:**
- Encryption (data transmitted in plaintext)
- Authentication (no sender verification)
- Integrity protection beyond simple checksum
- Replay attack prevention
**Assumptions:**
- Physical security: Direct wired connection between trusted devices
- Closed system: No external access to UART lines
- Point-to-point: Single transmitter → single receiver
### Checksum Strength
**XOR checksum provides:**
- Detection of single-bit errors: ✓
- Detection of burst errors: Partial
- Detection of intentional tampering: ✗
**Known Weaknesses:**
- Two identical errors cancel out (XOR property)
- Does not detect byte reordering
- Cryptographically insecure
**Recommendation:** For safety-critical applications requiring higher integrity, consider upgrading to CRC-16 or CRC-32 checksums in future protocol versions.
---
## Example Packet Analysis
### Sample Packet (Hexadecimal)
## Controller A console commands (USB serial)
```
AA 01 12 | E8 03 00 00 | 1A | 04 | 4E 03 | 17 04 | 7F 03 | DD 04 | 00 00 | 3F | 01 | 9C | 55
cfg show
cfg set <name> <value> tach_ppr tach_trim tach_min_hz tach_max_hz
temp_hz temp_slope temp_offset temp_min temp_duty_max
tach_en temp_en coolant_hot gearbox_hot batt_low
cfg override off | rpm <n> | duty <n> | both <rpm> <duty>
cfg reset
```
### Field-by-Field Breakdown
`set` values are saved to NVS and pushed to B immediately. `override` is pushed but not saved on either side.
| Offset | Hex Bytes | Field | Decoded Value | Notes |
|--------|-----------|-------|---------------|-------|
| 0 | AA | Start Marker | 0xAA | Valid sync byte |
| 1 | 01 | Version | 1 | Protocol v1.0 |
| 2 | 12 | Length | 18 bytes | Payload size |
| **PAYLOAD START** |
| 3-6 | E8 03 00 00 | Timestamp | 1000ms | Little-endian uint32 |
| 7 | 1A | Packet ID | 26 | Rolling counter |
| 8 | 04 | Gear Position | 4 (GEAR_SPORT) | Sport mode |
| 9-10 | 4E 03 | Coolant Temp | 846 = 84.6°C | int16_t LE |
| 11-12 | 17 04 | Engine Oil Temp | 1047 = 104.7°C | int16_t LE |
| 13-14 | 7F 03 | Gearbox Temp | 895 = 89.5°C | int16_t LE |
| 15-16 | DD 04 | Battery Voltage | 1245 = 12.45V | uint16_t LE |
| 17-18 | 00 00 | Fault Codes | 0x0000 | No faults |
| 19 | 3F | Valid Flags | 0x3F (0b00111111) | All fields valid |
| 20 | 01 | Debug Enabled | 1 (ON) | Debug mode active |
| **PAYLOAD END** |
| 21 | 9C | Checksum | 0x9C | XOR validation |
| 22 | 55 | End Marker | 0x55 | Valid packet boundary |
### Interpretation
**System Status:**
- Uptime: 1.0 seconds since boot
- Transmission in Sport mode
- Engine warmed up (coolant 84.6°C, oil 104.7°C)
- Normal battery voltage (12.45V)
- No fault codes active
- All sensor data valid
- Debug logging enabled
**Validity Check:**
- Start marker: ✓ (0xAA found)
- End marker: ✓ (0x55 found)
- Version: ✓ (0x01 matches)
- Length: ✓ (0x12 = 18 bytes)
- Checksum: ✓ (recalculate to verify 0x9C)
**Display Output:**
```
Gear: S
Temps: 84.6 / 104.7 / 89.5 °C
Battery: 12.45V
Faults: None
Debug: ON
```
The same tunables are editable on A's touchscreen: Home → swipe right → Driveline → swipe right → **Gauge Tuning** (−/+ per field, enable switches, override sliders).
---
## Implementation Guidelines
## Receiver behaviour (B)
### Receiver Best Practices
**Synchronization Strategy:**
1. Search for start marker (0xAA) in incoming byte stream
2. Read next 22 bytes as potential packet
3. Validate end marker (0x55) at expected offset
4. Verify version and length fields
5. Calculate and compare checksum
6. Parse payload only if all checks pass
**Buffer Management:**
- Use circular/ring buffer for incoming bytes
- Handle partial packets gracefully
- Clear buffer on validation failure to resync
**Data Extraction:**
- Use bitwise operations for multi-byte fields
- Handle little-endian conversion if needed
- Apply scaling factors (×10 for temps, ×100 for voltage)
- Check valid flags before using each field
**Display Updates:**
- Update display only on valid packet
- Maintain last known good values for each field
- Show warning if packet age > 1 second
- Indicate invalid fields with "---" or similar
### Transmitter Considerations
**Timing Accuracy:**
- Use hardware timer for 200ms interval
- Avoid blocking operations in transmission loop
- Keep packet assembly time < 10ms
**Data Consistency:**
- Use mutex when reading shared CAN data
- Snapshot all values atomically
- Update timestamp last (after data read)
**Error Handling:**
- If UART transmit fails, log error but continue
- Don't block CAN reception on UART errors
- Auto-restart UART if failures exceed threshold
- Link considered lost after 1000 ms without an applied DATA frame on any transport; display shows N/A and both gauge outputs go low.
- Gear label: letter from `gear_lever`; digit = engaged gear, or the target gear (pulsing) while target ≠ engaged.
- Icons turn red from the `alerts` bits, never from local thresholds.
- Last CONFIG is cached in B's NVS so a B reboot drives the gauges before A resends.
---
## Troubleshooting
## Changing the protocol
### Common Issues
**No Packets Received:**
- Check physical wiring (TX→RX connection, common ground)
- Verify baud rate match (115200 on both sides)
- Confirm Controller A CAN bus is active and receiving data
- Check GPIO pin assignments match specification
**Checksum Errors:**
- Intermittent errors: Likely EMI/noise on wire
- Consistent errors: Baud rate mismatch or endianness issue
- Add shielding to UART wires if noise suspected
**Stale Data (Timestamp Not Updating):**
- Controller A may have crashed (check serial log)
- CAN bus disconnected (no vehicle data)
- UART transmitter disabled (check CAN toggle state)
**Invalid Temperature Readings:**
- Value -400: CAN message not received or sensor fault
- Value > 2000: Overflow or parsing error
- Check CAN bus connection and message IDs
**Gear Position Shows Error (14):**
- Transmission CAN message (0x1001) not received
- Check CAN wiring and bus termination
- Verify vehicle is in accessory mode (CAN active)
### Debug Checklist
**Controller A (Transmitter):**
1. CAN toggle ON in Settings screen?
2. CAN messages being received? (check serial: "✓ Parsed CAN ID=...")
3. UART auto-started? (check serial: "UART STARTED (triggered by CAN state)")
4. Packets being sent? (check serial: "TX Packet #N (...)")
**Controller B (Receiver):**
1. UART initialized on correct GPIO (RX = GPIO 1)?
2. Baud rate set to 115200?
3. Start marker (0xAA) being detected?
4. Checksum validation passing?
5. Valid flags checked before using data?
---
## Revision History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0 | 2025-11-09 | BMW Patrol Team | Initial release - CAN-to-UART integration complete |
---
## References
**Related Documentation:**
- `CLAUDE.md` - Project architecture and build instructions
- `CAN_BUS_INTEGRATION.md` - CAN bus configuration and BMW message IDs
- `src/protocol/automotive_data.h` - C structure definitions
- `src/modules/uart_manager.cpp` - Transmitter implementation
- `src/drivers/can_driver.cpp` - CAN receiver implementation
**Hardware Specifications:**
- ESP32-S3-Touch-LCD-5B: https://www.waveshare.com/esp32-s3-touch-lcd-5.htm
- ESP32-S3-Touch-LCD-1.3: https://www.waveshare.com/esp32-s3-touch-lcd-1.3.htm
- ESP32-S3 Technical Reference Manual: https://www.espressif.com/en/products/socs/esp32-s3
**Standards:**
- BMW K-CAN Bus: 500 Kbps, ISO 11898 compliant
- UART: RS-232 compatible (TTL voltage levels)
---
**End of Document**
1. Edit `automotive_data.h` on A, bump `PACKET_VERSION`.
2. Copy the header to B unchanged.
3. Update this document.
4. Flash both. A stale B logs version errors and applies nothing.