/** * automotive_data.h * * Shared wire contract between Controller A (ESP32-S3-Touch-LCD-5B) and * Controller B (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. * * 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 * * 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 #define _AUTOMOTIVE_DATA_H #include #include #include #include #include // ============================================================================ // LINK CONFIGURATION // ============================================================================ #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 are controller-specific: // - Controller A (5B): uart_manager.cpp (TX GPIO 44 -> SP3485 -> 485_A/B) // - Controller B (1.3): platformio.ini (RX IO1) // ============================================================================ // 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 // 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 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) // ============================================================================ // GEAR // ============================================================================ // 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, GEAR_NEUTRAL = 2, GEAR_DRIVE = 3, GEAR_MANUAL_1 = 4, GEAR_MANUAL_2 = 5, GEAR_MANUAL_3 = 6, GEAR_MANUAL_4 = 7, GEAR_MANUAL_5 = 8, GEAR_MANUAL_6 = 9, GEAR_UNKNOWN = 0xFF } gear_position_t; // ============================================================================ // DATA FRAME PAYLOAD // ============================================================================ typedef struct __attribute__((packed)) { 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; #define AUTOMOTIVE_DATA_SIZE sizeof(automotive_data_t) // 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_ALERTS (1 << 5) #define VALID_FLAG_RPM (1 << 6) // 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; } // ============================================================================ // LINK MAINTENANCE FRAMES (2026-09-27) - Controller B 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 Controller A'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) // ============================================================================ // BMW E60/E65 PT-CAN, 500 kbps. Every ID below is an 11-bit STANDARD frame and // has been seen live on the actual swap bus. Decodes cross-checked against // HeinrichG-V12/E65_ReverseEngineering (per-ID DBC docs) AND our own captures. // Full evidence + confidence labels: wiki/pages/can-id-candidates.md // // The original map (0x4F/0x55/0x201/0x1001/0x101F) was placeholder junk — those // IDs were verified ABSENT from the bus 2026-07-15. Do not resurrect them. // --- 0x1D0 "Engine Data" (DME/DDE, DLC 8, 100 ms) -------------------------- #define CAN_ID_ENGINE_DATA 0x1D0 #define CAN_BYTE_COOLANT_TEMP 0 // TEMP_ENG: °C = raw - 48 (verified) #define CAN_BYTE_ENGINE_OIL_TEMP 1 // TEMP_EOI: °C = raw - 48 (reads 0xFF here — sensor not populated on this M57N) #define CAN_BYTE_ENGINE_STATUS 2 // bits 4-5 = ST_ENGINE_RUN #define ENGINE_TEMP_OFFSET 48 // subtract from raw // ST_ENGINE_RUN (byte 2, bits 4-5) #define ENGINE_RUN_OFF 0 #define ENGINE_RUN_STARTING 1 #define ENGINE_RUN_RUNNING 2 #define ENGINE_RUN_INVALID 3 // --- 0x0B5 "Torque Request EGS" (EGS, DLC 8, 10 ms) ------------------------ #define CAN_ID_TORQUE_EGS 0x0B5 #define CAN_BYTE_GEARBOX_TEMP 7 // TEMP_GRB: °C = raw - 40 (verified two ways) #define GEARBOX_TEMP_OFFSET 40 // NOT 0, NOT +40 — see wiki; a 40 °C error either way #define CAN_BYTE_GEARBOX_COOL 4 // bits 38-39 = ST_OTMP_GRB (cooling demand) // ST_OTMP_GRB — the box's own overheat opinion (better than thresholding temp) #define GEARBOX_COOL_NONE 0 #define GEARBOX_COOL_STAGE1 1 #define GEARBOX_COOL_STAGE2 2 #define GEARBOX_COOL_INVALID 3 // --- 0x1D2 "Display Gearbox Data" (EGS, DLC 6, 200 ms) --------------------- // Our decode is AHEAD of the published source here: the E65 repo lists this ID // with an empty signal table. Byte 1 and byte 4 are our own work. #define CAN_ID_GEAR_DISPLAY 0x1D2 #define CAN_BYTE_GEAR_LEVER 0 // whole-byte lever code #define CAN_BYTE_GEAR_ENGAGED 1 // (raw >> 4) - 4 = gear 1..6; 0x0F = none #define CAN_BYTE_GEAR_MODE 4 // 0xF0 auto / 0xF1 Sport / 0xF2 Manual // Byte 0 lever codes (verified — every code matches the documented table) #define GEAR_CODE_PARK 0xE1 #define GEAR_CODE_REVERSE 0xD2 #define GEAR_CODE_NEUTRAL 0xB4 #define GEAR_CODE_DRIVE 0x78 // D *and* S/M — the side-gate is physically the same detent // Byte 4 mode codes. NOTE: 0xF2 is a PERSISTENT mode, not a downshift event — // it holds across gears 2..6. The +/- nudges have no distinct code; the first // tap simply promotes Sport -> Manual. #define GEAR_MODE_DRIVE_AUTO 0xF0 #define GEAR_MODE_SPORT 0xF1 #define GEAR_MODE_MANUAL 0xF2 #define GEAR_ENGAGED_NONE 0x0F // byte 1 value in P/R/N — and in R even when engaged // --- 0x0BA gearbox state (EGS, DLC 8, 20 ms) ------------------------------- // The ONLY source of engaged reverse: 0x1D2 byte 1 stays 0x0F in R. #define CAN_ID_GEARBOX_STATE 0x0BA #define CAN_BYTE_GEARBOX_TARGET 0 // low nibble = ST_GR_GRB // ST_GR_GRB (byte 0, low nibble). Every value 1/2/3/5..0xA observed live in the // 2026-07-17 drive capture. Value 4 remains unaccounted for. // This nibble alone is a COMPLETE gear source: P/R/N plus 1st..6th, reverse // included. 0x1D2 is still needed for the lever and the D/S/M mode, which this // message does not carry. #define GRB_TARGET_NEUTRAL 1 #define GRB_TARGET_REVERSE 2 #define GRB_TARGET_PARK 3 #define GRB_TARGET_GEAR1 5 // ..0xA = 6th #define GRB_TARGET_GEAR6 0xA #define GRB_TARGET_INVALID 0xF // Byte 0 bits 6-7: ST_CCLT, torque converter lockup clutch. Relevant to any // turbine-vs-engine ratio test: a CLOSED clutch makes turbine == engine exactly, // so ratio ~1.0 at road speed means "locked up", not "not engaged". #define CAN_BYTE_CONVERTER_CLUTCH 0 #define CCLT_DISENGAGED 0 #define CCLT_CONTROLLED 1 #define CCLT_CLOSED 2 #define CCLT_INVALID 3 // Bytes 3-4: output shaft speed, 16-bit little-endian. UNDOCUMENTED in every // source. Identification is verified (rises monotonically 1st->6th under drive, // zero whenever the output is held, including engaged-in-D). This is the // project's only road-speed signal — there is no DSC/wheel-speed module on this // bus. // // SCALING IS UNSETTLED. The upshift-schedule test earlier suggested raw * 0.125 // = rpm, but a direct Launch reference reading (128 rpm at raw 1192, 2026-07-17) // points to ~0.107 instead and contradicts 0.125. One eyeballed point isn't a // calibration, so this stays RAW COUNTS until a multi-point Launch sweep fixes // the factor. Do not convert to a physical unit here. // See wiki/pages/driveline-speed-signals.md #define CAN_BYTE_OUTPUT_SHAFT_L 3 #define CAN_BYTE_OUTPUT_SHAFT_H 4 // PROVISIONAL output-shaft factor, from a SINGLE Launch reference reading // (128 rpm at raw 1192, 2026-07-17) taken through a known zero. Good enough to // put an approximate rpm on the display (±~10%), NOT good enough to trust for // anything computed. Replace once a multi-point Launch sweep gives a real fit. // rpm ~= raw * 1074 / 10000 #define OUTPUT_SHAFT_RPM_NUM 1074 #define OUTPUT_SHAFT_RPM_DEN 10000 static inline uint16_t can_output_shaft_rpm(uint16_t raw) { return (uint16_t)(((uint32_t)raw * OUTPUT_SHAFT_RPM_NUM) / OUTPUT_SHAFT_RPM_DEN); } // --- 0x1A2 turbine speed (EGS, DLC 4, 20 ms) ------------------------------- // Gearbox INPUT speed. Physically proves engagement: free-spins at ~engine // speed in P/N, collapses to ~0 when the box engages against a held output. #define CAN_ID_TURBINE_SPEED 0x1A2 #define CAN_BYTE_TURBINE_L 0 #define CAN_BYTE_TURBINE_H 1 // --- 0x0A8 "Torque 1" (DME/DDE, DLC 8, 10 ms) ------------------------------ // TORQ_AVL = torque the engine has AVAILABLE/is delivering. (0x0AA's TORQ_DVCH // is driver DEMAND — same bit layout, so both read ~27 Nm at idle, but they // diverge under load. This is the one to display as "engine torque".) #define CAN_ID_TORQUE_1 0x0A8 #define CAN_BYTE_TORQUE_L 1 // TORQ_AVL low (byte 1) — see can_to_torque_x10 #define CAN_BYTE_TORQUE_H 2 // TORQ_AVL high (byte 2) // --- 0x0AA "Torque 3" (DME/DDE, DLC 8, 10 ms) ------------------------------ #define CAN_ID_TORQUE_3 0x0AA #define CAN_BYTE_PEDAL_POS 3 // ANG_ACPD: % = raw * 0.39063 #define CAN_BYTE_RPM_L 4 // RPM_ENG: 1/min = raw16 * 0.25 #define CAN_BYTE_RPM_H 5 #define CAN_BYTE_CRUISE_STATE 6 // low nibble = ST_CLCTR_V // --- 0x3B4 "Power Management Battery Voltage" (DLC 8, 5 s) ----------------- #define CAN_ID_BATTERY_VOLTAGE 0x3B4 #define CAN_BYTE_BATTERY_VOLT_L 0 // U_BT: 12-bit little-endian, V = raw * 0.015 #define CAN_BYTE_BATTERY_VOLT_H 1 // low nibble only (high nibble = ST_BTSW) #define BATTERY_RAW_INVALID 0xFFF // U_BT's not-available marker // Byte 2 low nibble. The E65 repo calls this ST_ENGINE_RUN and the E60 VFL sheet // calls it an engine-running flag with 0x09=running — BOTH ARE WRONG FOR US. // Verified on this bus 2026-07-17: it tracks IGNITION, inverted, and does not // move when the engine starts. Use 0x1D0 ST_ENGINE_RUN for engine state. // Although 0x3B4 is nominally a 5 s periodic message, it ALSO transmits // on-change: the ignition nibble flips instantly when the key toggles (user- // verified), so an ignition-driven reset is effectively immediate. #define CAN_BYTE_IGNITION 2 #define IGNITION_ON 0x00 #define IGNITION_OFF 0x09 // All IDs are 11-bit standard frames — the extended-ID assumption came from the // bogus 0x1001/0x101F placeholders and is dead. #define USE_EXTENDED_CAN_IDS false // ============================================================================ // FRAME HELPERS // ============================================================================ /** * XOR checksum over a byte range. */ static inline uint8_t calculate_checksum(const uint8_t* data, size_t length) { uint8_t checksum = 0; for (size_t i = 0; i < length; i++) { checksum ^= data[i]; } return checksum; } /** * 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 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 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; } *type = t; *payload = &f[PACKET_HEADER_SIZE]; *len = l; return FRAME_OK; } // ============================================================================ // GEAR HELPERS (wire enum) // ============================================================================ 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); } } /** * Convert temperature from CAN format to internal format * @param can_value Raw CAN bus value * @param offset Value to SUBTRACT from raw (48 for 0x1D0 engine temps, 40 for 0x0B5) * @return Temperature in 0.1°C units */ static inline int16_t can_to_temperature(uint8_t can_value, int16_t offset) { return (int16_t)(((int16_t)can_value - offset) * 10); } /** * Extract the raw 12-bit U_BT field from a 0x3B4 frame. * The high nibble of byte 1 is ST_BTSW, NOT voltage — mask it off or you'll read * ~4x too high. * @param d Payload of a 0x3B4 frame (needs DLC >= 2) * @return Raw 12-bit value; BATTERY_RAW_INVALID (0xFFF) means "not available" */ static inline uint16_t can_battery_raw(const uint8_t* d) { return (uint16_t)(((d[CAN_BYTE_BATTERY_VOLT_H] & 0x0F) << 8) | d[CAN_BYTE_BATTERY_VOLT_L]); } /** * Decode battery voltage from a 0x3B4 frame. * U_BT is 12-bit little-endian, factor 0.015 V — i.e. 0.01 V units = raw * 1.5. * (Source example: raw 0x3D9 = 985 -> 14.775 V.) * * CAVEAT: on this bus the field reads BATTERY_RAW_INVALID almost always — the * Power Module appears not to be retained in the swap. Check can_battery_raw() * against BATTERY_RAW_INVALID before calling this; 0xFFF would otherwise decode * to a confident-looking 61 V. The factor itself is also unconfirmed against a * meter (0.015 here vs ~0.0147 implied by the E60 VFL sheet). * See wiki/pages/can-id-candidates.md. * * @param d Payload of a 0x3B4 frame (needs DLC >= 2) * @return Voltage in 0.01V units */ static inline uint16_t can_to_voltage(const uint8_t* d) { return (uint16_t)((can_battery_raw(d) * 3) / 2); // raw * 0.015 V -> 0.01 V units } /** * Decode engine RPM from a 0x0AA frame. RPM_ENG = raw16 (Intel) * 0.25. * @param d Payload of a 0x0AA frame (needs DLC >= 6) */ static inline uint16_t can_to_rpm(const uint8_t* d) { uint16_t raw = (uint16_t)((d[CAN_BYTE_RPM_H] << 8) | d[CAN_BYTE_RPM_L]); return (uint16_t)(raw / 4); } /** * Decode available engine torque (TORQ_AVL) from a 0x0A8 frame. * * The field is a SIGNED 12-bit value at bits 12-23, factor 0.5 Nm. The user's * spreadsheet formula (D2*256 + D1)/32 lands on the same number — algebraically * (D2<<8|D1)/32 == ((D2<<4)|(D1>>4)) * 0.5 — but it sweeps D1's low nibble into * the result, and those four bits are ALIV_TORQ_1_DME (the alive counter), not * torque. That adds up to ~0.5 Nm of jitter. We mask it off and sign-extend so * overrun/braking (negative torque) reads correctly. Verified against the repo's * 0x0A8 worked example: C7 08 03 00 ... -> 24 Nm, with ALIV=8 in D1's low nibble. * * @param d Payload of a 0x0A8 frame (needs DLC >= 3) * @return Torque in 0.1 Nm units, signed */ static inline int16_t can_to_torque_x10(const uint8_t* d) { uint16_t raw12 = (uint16_t)((d[CAN_BYTE_TORQUE_H] << 4) | (d[CAN_BYTE_TORQUE_L] >> 4)); int16_t s = (raw12 & 0x800) ? (int16_t)(raw12 | 0xF000) // sign-extend 12->16 bit : (int16_t)raw12; return (int16_t)(s * 5); // * 0.5 Nm, expressed in 0.1 Nm units } /** * Decode gearbox turbine (input) speed from a 0x1A2 frame. * RPM_GRB_TURB = raw16 (Intel) * 0.125 + 6. * @param d Payload of a 0x1A2 frame (needs DLC >= 2) */ static inline uint16_t can_to_turbine_rpm(const uint8_t* d) { uint16_t raw = (uint16_t)((d[CAN_BYTE_TURBINE_H] << 8) | d[CAN_BYTE_TURBINE_L]); return (uint16_t)(raw / 8 + 6); } /** * Map a raw 0x1D2 byte-0 lever code to a gear_position_t. * D and S/M share code 0x78 — use decode_gear() to resolve them. * @param d0 Byte 0 of a 0x1D2 frame * @return Lever position, or GEAR_UNKNOWN if the code isn't recognized */ static inline gear_position_t can_to_gear_lever(uint8_t d0) { switch (d0) { case GEAR_CODE_PARK: return GEAR_PARK; case GEAR_CODE_REVERSE: return GEAR_REVERSE; case GEAR_CODE_NEUTRAL: return GEAR_NEUTRAL; case GEAR_CODE_DRIVE: return GEAR_DRIVE; // D or S/M — see decode_gear() default: return GEAR_UNKNOWN; } } /** * Extract the engaged gear number from 0x1D2 byte 1. * High nibble is a +16 ladder: 0x5F=1st .. 0xAF=6th. 0x0F = no numbered gear. * @param d1 Byte 1 of a 0x1D2 frame * @return 1..6, or 0 if no gear is engaged / value out of range. * Always 0 in REVERSE — reverse is unnumbered here; use 0x0BA instead. */ static inline uint8_t can_to_engaged_gear(uint8_t d1) { if (d1 == GEAR_ENGAGED_NONE) return 0; uint8_t n = (uint8_t)((d1 >> 4) - 4); return (n >= 1 && n <= 6) ? n : 0; } /** * Resolve the full 0x1D2 frame into a single displayable gear_position_t. * * P/R/N come straight from the lever. In the D detent, byte 4 splits plain Drive * from the Sport/Manual side-gate; when in S/M we surface the engaged gear number * (GEAR_MANUAL_1..6) because that's what a driver in the side-gate wants to read. * * @param d Payload of a 0x1D2 frame * @param dlc Frame DLC (must be >= 5 to reach the mode byte) * @return Gear to display, or GEAR_UNKNOWN if the lever code isn't recognized */ static inline gear_position_t decode_gear(const uint8_t* d, uint8_t dlc) { if (dlc <= CAN_BYTE_GEAR_LEVER) return GEAR_UNKNOWN; gear_position_t lever = can_to_gear_lever(d[CAN_BYTE_GEAR_LEVER]); if (lever != GEAR_DRIVE) return lever; // P/R/N (or UNKNOWN) need no further work // In the D detent. Without the mode byte we can't tell D from S/M — report D. if (dlc <= CAN_BYTE_GEAR_MODE) return GEAR_DRIVE; if (d[CAN_BYTE_GEAR_MODE] == GEAR_MODE_DRIVE_AUTO) return GEAR_DRIVE; // Sport or Manual: show the engaged gear if the box has told us one. if (dlc > CAN_BYTE_GEAR_ENGAGED) { uint8_t n = can_to_engaged_gear(d[CAN_BYTE_GEAR_ENGAGED]); if (n >= 1 && n <= 6) return (gear_position_t)(GEAR_MANUAL_1 + (n - 1)); } return GEAR_DRIVE; } /** * Map a 0x0BA ST_GR_GRB nibble (the gearbox's own target gear) to a * gear_position_t, for cross-checking against the lever. * @param nibble Low nibble of 0x0BA byte 0 * @return Target gear, or GEAR_UNKNOWN if invalid/unrecognized */ static inline gear_position_t can_to_target_gear(uint8_t nibble) { switch (nibble) { case GRB_TARGET_PARK: return GEAR_PARK; case GRB_TARGET_REVERSE: return GEAR_REVERSE; case GRB_TARGET_NEUTRAL: return GEAR_NEUTRAL; default: break; } // 5..0xA = forward gears 1..6 (same ladder as 0x1D2 byte 1) if (nibble >= GRB_TARGET_GEAR1 && nibble <= GRB_TARGET_GEAR6) return GEAR_DRIVE; return GEAR_UNKNOWN; } /** * Extract the engaged gear number from a 0x0BA ST_GR_GRB nibble. * Unlike 0x1D2 byte 1, this ladder is the whole picture — but it numbers only * the forward gears, so P/R/N still return 0. * @param nibble Low nibble of 0x0BA byte 0 * @return 1..6, or 0 if not in a numbered forward gear */ static inline uint8_t can_to_target_gear_num(uint8_t nibble) { if (nibble < GRB_TARGET_GEAR1 || nibble > GRB_TARGET_GEAR6) return 0; return (uint8_t)(nibble - GRB_TARGET_GEAR1 + 1); } /** * Get human-readable gear position string * @param gear Gear position enum value * @return String representation of gear */ static inline const char* gear_to_string(gear_position_t gear) { switch (gear) { case GEAR_PARK: return "P"; case GEAR_REVERSE: return "R"; case GEAR_NEUTRAL: return "N"; case GEAR_DRIVE: return "D"; case GEAR_MANUAL_1: return "1"; case GEAR_MANUAL_2: return "2"; case GEAR_MANUAL_3: return "3"; case GEAR_MANUAL_4: return "4"; case GEAR_MANUAL_5: return "5"; case GEAR_MANUAL_6: return "6"; default: return "?"; } } /** * Format temperature for display * @param temp_x10 Temperature in 0.1°C units * @param buffer Output buffer (minimum 10 characters) * @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. sprintf(buffer, "%d.%dC", temp_x10 / 10, abs(temp_x10 % 10)); return buffer; } /** * Format voltage for display * @param voltage_x100 Voltage in 0.01V units * @param buffer Output buffer (minimum 10 characters) * @return Pointer to buffer */ static inline char* format_voltage(uint16_t voltage_x100, char* buffer) { sprintf(buffer, "%d.%02dV", voltage_x100 / 100, voltage_x100 % 100); 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 #endif // _AUTOMOTIVE_DATA_H