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
+242 -79
View File
@@ -1,44 +1,83 @@
/**
* automotive_data.h
*
* Shared data structure and protocol definitions for automotive monitoring system
* ESP32-S3-LCD-5B (Controller A) -> ESP32-S3-LCD-1.3 (Controller B) communication
* Shared wire contract between Controller A (ESP32-S3-Touch-LCD-5B) and
* Controller B (ESP32-S3-LCD-1.3).
*
* This header defines the data structure for 6 automotive sensor values and the
* simple packet framing protocol for UART transmission at 115200 baud.
* 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.
*
* v2 (2026-09-21):
* - typed frames: DATA (sensor snapshot, 5 Hz) and CONFIG (tunables, on
* change + every CONFIG_RESEND_MS)
* - gear split into lever (P/R/N/D/S/M) + target/engaged gear nibbles
* - engine RPM
* - alert bitmap decided on A (thresholds live on A, B only renders)
* - 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
*/
#ifndef _AUTOMOTIVE_DATA_H
#define _AUTOMOTIVE_DATA_H
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// ============================================================================
// UART PROTOCOL CONFIGURATION
// LINK CONFIGURATION
// ============================================================================
// Communication parameters (hardware-independent)
#define UART_BAUD_RATE 115200 // Reliable automotive-grade baud rate
#define UART_UPDATE_RATE_MS 200 // 5Hz transmission rate
#define UART_BAUD_RATE 115200 // UART1 on both ends
#define UART_UPDATE_RATE_MS 200 // DATA frame period (5 Hz)
#define CONFIG_RESEND_MS 5000 // CONFIG frame re-broadcast period
#define ESPNOW_CHANNEL 1 // Wi-Fi channel A transmits ESP-NOW on
// (B hops until it hears A, then locks)
// NOTE: UART pin assignments (TX/RX) are controller-specific and defined in:
// - Controller A (5B): uart_manager.cpp
// - Controller B (1.3): uart_receiver.cpp
// Packet framing bytes
#define PACKET_START_BYTE 0xAA // Start of packet marker
#define PACKET_END_BYTE 0x55 // End of packet marker
#define PACKET_VERSION 0x01 // Protocol version for future compatibility
// Packet structure offsets
#define PACKET_MIN_SIZE 8 // Start(1) + Version(1) + Length(1) + Data(min 1) + Checksum(1) + End(1)
#define PACKET_MAX_SIZE 64 // Maximum packet size to prevent buffer overruns
// 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)
// ============================================================================
// AUTOMOTIVE DATA STRUCTURE
// FRAME FORMAT (identical on UART and ESP-NOW)
// ============================================================================
//
// 0xAA | version | type | length | payload[length] | checksum | 0x55
//
// checksum = XOR of version, type, length and every payload byte.
//
#define PACKET_START_BYTE 0xAA
#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_HEADER_SIZE 4 // start, version, type, length
#define PACKET_TRAILER_SIZE 2 // checksum, end
#define PACKET_MAX_PAYLOAD 64
#define PACKET_MAX_SIZE (PACKET_HEADER_SIZE + PACKET_MAX_PAYLOAD + PACKET_TRAILER_SIZE)
// ============================================================================
// GEAR
// ============================================================================
// Gear position enumeration
// What the driver selected (0x1D2 byte 0 + byte 4 mode). This is the wire enum.
typedef enum {
LEVER_PARK = 0,
LEVER_REVERSE = 1,
LEVER_NEUTRAL = 2,
LEVER_DRIVE = 3, // D detent, automatic mode
LEVER_SPORT = 4, // D detent, Sport mode
LEVER_MANUAL = 5, // D detent, Manual mode
LEVER_UNKNOWN = 0xFF
} gear_lever_t;
// Controller A'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,
GEAR_REVERSE = 1,
@@ -53,43 +92,114 @@ typedef enum {
GEAR_UNKNOWN = 0xFF
} gear_position_t;
// Main automotive data structure (packed for efficient transmission)
// ============================================================================
// DATA FRAME PAYLOAD
// ============================================================================
typedef struct __attribute__((packed)) {
// Identification and versioning
uint8_t packet_id; // Incremental packet ID for debugging
uint32_t timestamp_ms; // Milliseconds since boot
// Sensor data (6 monitored values)
uint8_t gear_position; // Current gear (see gear_position_t enum)
int16_t gearbox_oil_temp; // Gearbox oil temperature in 0.1°C (-3276.8 to +3276.7°C)
int16_t engine_oil_temp; // Engine oil temperature in 0.1°C
int16_t coolant_temp; // Engine coolant temperature in 0.1°C
uint16_t battery_voltage; // Battery voltage in 0.01V (0 to 655.35V)
uint16_t fault_codes; // Bitmap of active fault codes (16 possible codes)
// Data validity flags (1 bit per sensor)
uint8_t valid_flags; // Bit 0: gear, Bit 1: gearbox temp, etc.
// Debug mode flag (for Controller B to enable/disable monitors)
uint8_t debug_enabled; // 0 = debug off, 1 = debug on
uint8_t packet_id; // rolling counter; B dedupes UART vs ESP-NOW copies on it
uint32_t timestamp_ms; // A's millis() when the frame was built
uint8_t gear_lever; // gear_lever_t
uint8_t gear_nibbles; // high nibble = gearbox TARGET gear (0x0BA),
// low nibble = ENGAGED gear (0x1D2 byte 1);
// 0 = none / P / R / N, 1..6 = forward gear.
// target != engaged => a shift is in progress
uint16_t engine_rpm; // 1/min (0x0AA)
int16_t gearbox_oil_temp; // 0.1 degC
int16_t engine_oil_temp; // 0.1 degC (no source on this M57N; stays invalid)
int16_t coolant_temp; // 0.1 degC
uint16_t battery_voltage; // 0.01 V
uint16_t alerts; // ALERT_* bitmap, decided on A
uint8_t valid_flags; // VALID_FLAG_* bitmap
uint8_t debug_enabled; // 0/1: B mirrors A's debug overlay toggle
} automotive_data_t;
// Size of the data structure
#define AUTOMOTIVE_DATA_SIZE sizeof(automotive_data_t)
// Valid flags bit positions
// valid_flags
#define VALID_FLAG_GEAR_POS (1 << 0)
#define VALID_FLAG_GEARBOX_TEMP (1 << 1)
#define VALID_FLAG_ENGINE_TEMP (1 << 2)
#define VALID_FLAG_COOLANT_TEMP (1 << 3)
#define VALID_FLAG_BATTERY_VOLT (1 << 4)
#define VALID_FLAG_FAULT_CODES (1 << 5)
#define VALID_FLAG_ALERTS (1 << 5)
#define VALID_FLAG_RPM (1 << 6)
// Fault code bitmap (fault_codes field). NOTE: these are OUR derived faults, not
// DDE DTCs — real fault codes are not broadcast on this bus and would require
// diagnostic request/response (see wiki/pages/can-id-candidates.md).
#define FAULT_GEAR_MISMATCH (1 << 0) // lever (0x1D2) and gearbox (0x0BA) disagree
// alerts - set by A from its thresholds (link_config_t) and CAN status bits.
// These are OUR derived alerts, not DDE DTCs (fault codes are not broadcast on
// this bus; see wiki/pages/can-id-candidates.md).
#define ALERT_GEAR_MISMATCH (1 << 0) // lever (0x1D2) vs gearbox target (0x0BA) disagree
#define ALERT_COOLANT_HOT (1 << 1) // coolant_temp >= coolant_hot_c
#define ALERT_GEARBOX_HOT (1 << 2) // gearbox_oil_temp >= gearbox_hot_c
#define ALERT_GEARBOX_COOLING (1 << 3) // the box's own cooling demand (0x0B5 ST_OTMP_GRB >= 1)
#define ALERT_BATTERY_LOW (1 << 4) // battery_voltage < battery_low_x100
// Severity ranking for B's display (highest wins): red alarms first.
#define ALERTS_RED (ALERT_COOLANT_HOT | ALERT_GEARBOX_HOT | ALERT_GEAR_MISMATCH | ALERT_BATTERY_LOW)
#define ALERTS_AMBER (ALERT_GEARBOX_COOLING)
// ============================================================================
// CONFIG FRAME PAYLOAD - tunables edited on A, executed on B
// ============================================================================
typedef struct __attribute__((packed)) {
uint8_t cfg_version; // bumped by A on every change; B applies when it changes
// --- tachometer output (B: IO7, LEDC) ---
uint8_t tach_ppr; // pulses per engine revolution the cluster expects
int8_t tach_trim_pct; // fine trim, -50..+50 %
uint16_t tach_min_hz; // 0 = no lower clamp
uint16_t tach_max_hz; // 0 = no upper clamp
// --- coolant gauge output (B: IO8, LEDC, 8-bit duty) ---
uint16_t temp_pwm_hz; // PWM frequency
uint16_t temp_slope_x100; // duty per degC x100 (150 = 1.5 duty/degC)
int16_t temp_offset; // duty at 0 degC (may be negative)
int16_t temp_min_c; // output held OFF below this coolant temperature
uint8_t temp_duty_max; // clamp (255 = full scale)
// --- enables / calibration override ---
uint8_t out_enable; // OUT_ENABLE_* bits
uint8_t override_mode; // OVERRIDE_* bits: force fixed outputs from A's console
uint16_t override_rpm; // used when OVERRIDE_TACH set
uint8_t override_duty; // used when OVERRIDE_TEMP set
// --- alert thresholds (evaluated on A; sent so B can show them) ---
int16_t coolant_hot_c; // degC
int16_t gearbox_hot_c; // degC
uint16_t battery_low_x100; // 0.01 V
} link_config_t;
#define OUT_ENABLE_TACH (1 << 0)
#define OUT_ENABLE_TEMP (1 << 1)
#define OVERRIDE_TACH (1 << 0)
#define OVERRIDE_TEMP (1 << 1)
// Defaults. Tach: user's figure for the Patrol cluster. Temp: the duty law
// recovered from the user's earlier CANNY program (duty = 1.5*T + 50 on 0..255,
// off below 40 degC); 1 kHz is a placeholder until the old unit is measured.
// See ESP32-S3-LCD-1.3/wiki/pages/patrol-gauge-outputs.md
static inline void link_config_defaults(link_config_t* c) {
memset(c, 0, sizeof(*c));
c->cfg_version = 1;
c->tach_ppr = 4;
c->tach_trim_pct = 0;
c->tach_min_hz = 0;
c->tach_max_hz = 600;
c->temp_pwm_hz = 1000;
c->temp_slope_x100 = 150;
c->temp_offset = 50;
c->temp_min_c = 40;
c->temp_duty_max = 255;
c->out_enable = OUT_ENABLE_TACH | OUT_ENABLE_TEMP;
c->override_mode = 0;
c->override_rpm = 0;
c->override_duty = 0;
c->coolant_hot_c = 100;
c->gearbox_hot_c = 130;
c->battery_low_x100 = 1100;
}
// ============================================================================
// CAN BUS ID MAPPINGS (BMW-Specific)
@@ -248,27 +358,11 @@ static inline uint16_t can_output_shaft_rpm(uint16_t raw) {
#define USE_EXTENDED_CAN_IDS false
// ============================================================================
// PACKET STRUCTURE FOR UART TRANSMISSION
// ============================================================================
typedef struct __attribute__((packed)) {
uint8_t start_byte; // PACKET_START_BYTE (0xAA)
uint8_t version; // Protocol version
uint8_t length; // Length of data payload
automotive_data_t data; // Actual sensor data
uint8_t checksum; // XOR checksum of all bytes except start/end
uint8_t end_byte; // PACKET_END_BYTE (0x55)
} uart_packet_t;
// ============================================================================
// HELPER FUNCTIONS
// FRAME HELPERS
// ============================================================================
/**
* Calculate XOR checksum for data buffer
* @param data Pointer to data buffer
* @param length Length of data to checksum
* @return XOR checksum value
* XOR checksum over a byte range.
*/
static inline uint8_t calculate_checksum(const uint8_t* data, size_t length) {
uint8_t checksum = 0;
@@ -279,21 +373,89 @@ static inline uint8_t calculate_checksum(const uint8_t* data, size_t length) {
}
/**
* Validate packet checksum
* @param packet Pointer to complete packet
* @return true if checksum is valid, false otherwise
* Build a complete frame (start..end) into out, which must hold PACKET_MAX_SIZE.
* @return total frame length, or 0 if the payload is too large.
*/
static inline bool validate_packet(const uart_packet_t* packet) {
if (packet->start_byte != PACKET_START_BYTE ||
packet->end_byte != PACKET_END_BYTE) {
return false;
static inline size_t frame_build(uint8_t type, const void* payload, uint8_t len, uint8_t* out) {
if (len > PACKET_MAX_PAYLOAD) return 0;
out[0] = PACKET_START_BYTE;
out[1] = PACKET_VERSION;
out[2] = type;
out[3] = len;
memcpy(&out[PACKET_HEADER_SIZE], payload, len);
out[PACKET_HEADER_SIZE + len] = calculate_checksum(&out[1], 3 + len);
out[PACKET_HEADER_SIZE + len + 1] = PACKET_END_BYTE;
return PACKET_HEADER_SIZE + len + PACKET_TRAILER_SIZE;
}
typedef enum {
FRAME_OK = 0,
FRAME_ERR_SIZE, // shorter than a minimal frame, or length field disagrees
FRAME_ERR_MARKERS, // start/end byte wrong
FRAME_ERR_VERSION, // other side runs a different PACKET_VERSION
FRAME_ERR_CHECKSUM,
FRAME_ERR_TYPE // unknown type, or length doesn't match the type's payload
} frame_status_t;
/**
* Validate a complete frame and locate its payload.
*/
static inline frame_status_t frame_parse(const uint8_t* f, size_t n,
uint8_t* type, const uint8_t** payload, uint8_t* len) {
if (n < PACKET_HEADER_SIZE + PACKET_TRAILER_SIZE) return FRAME_ERR_SIZE;
if (f[0] != PACKET_START_BYTE || f[n - 1] != PACKET_END_BYTE) return FRAME_ERR_MARKERS;
uint8_t l = f[3];
if (n != (size_t)(PACKET_HEADER_SIZE + l + PACKET_TRAILER_SIZE)) return FRAME_ERR_SIZE;
if (f[1] != PACKET_VERSION) return FRAME_ERR_VERSION;
if (calculate_checksum(&f[1], 3 + l) != f[PACKET_HEADER_SIZE + l]) return FRAME_ERR_CHECKSUM;
uint8_t t = f[2];
if (t == PACKET_TYPE_DATA) {
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 {
return FRAME_ERR_TYPE;
}
*type = t;
*payload = &f[PACKET_HEADER_SIZE];
*len = l;
return FRAME_OK;
}
// Calculate checksum over version, length, and data
size_t checksum_size = 2 + packet->length; // version(1) + length(1) + data(length)
uint8_t calculated = calculate_checksum((uint8_t*)&packet->version, checksum_size);
// ============================================================================
// GEAR HELPERS (wire enum)
// ============================================================================
return (calculated == packet->checksum);
static inline char gear_lever_char(uint8_t lever) {
switch (lever) {
case LEVER_PARK: return 'P';
case LEVER_REVERSE: return 'R';
case LEVER_NEUTRAL: return 'N';
case LEVER_DRIVE: return 'D';
case LEVER_SPORT: return 'S';
case LEVER_MANUAL: return 'M';
default: return '-';
}
}
static inline uint8_t gear_target(uint8_t nibbles) { return (uint8_t)(nibbles >> 4); }
static inline uint8_t gear_engaged(uint8_t nibbles) { return (uint8_t)(nibbles & 0x0F); }
static inline bool gear_shifting(uint8_t nibbles) {
uint8_t t = gear_target(nibbles), e = gear_engaged(nibbles);
return (t != 0 && e != 0 && t != e);
}
/**
* "P" / "R" / "N", or letter + gear number in the D detent ("D3", "S4", "M2").
* @param number gear number to show (caller picks engaged or target)
*/
static inline void gear_compose(uint8_t lever, uint8_t number, char* out, size_t n) {
char c = gear_lever_char(lever);
if ((lever == LEVER_DRIVE || lever == LEVER_SPORT || lever == LEVER_MANUAL) && number >= 1 && number <= 6) {
snprintf(out, n, "%c%u", c, number);
} else {
snprintf(out, n, "%c", c);
}
}
/**
@@ -492,7 +654,8 @@ 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) {
sprintf(buffer, "%d.%d°C", temp_x10 / 10, abs(temp_x10 % 10));
// Plain "C": Controller B's UI font has no degree-sign glyph.
sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10));
return buffer;
}
@@ -512,11 +675,11 @@ static inline char* format_voltage(uint16_t voltage_x100, char* buffer) {
// ============================================================================
// Default values for testing (before CAN data is available)
#define DEFAULT_GEAR_POS GEAR_PARK
#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_FAULT_CODES 0x0000 // No faults
#define DEFAULT_ALERTS 0x0000 // No alerts
#endif // _AUTOMOTIVE_DATA_H