Files
julian 1cba9f30bc
Firmware / build (push) Successful in 10m49s
Reverse lights on DO0, Sport + Vehicle screens, per-DDE live data, ECU identification
- ReverseLight: isolated output DO0 (CH422G OC0 -> PC817 -> NPN sink) drives the
  reverse-lamp relay while the lever is in R on a live bus with ignition on; 10 Hz
  decision confirmed over 200 ms, written through the panel library's expander
  object so the backlight cannot undo it; `reverse status|on|off|force` console,
  default ON (NVS `revlight_en`). Wiki page reverse-lights-output with the wiring.
- Sport screen: BMW-style power + torque gauges (lv_meter on a dial-face image,
  image needle); PNG sources in assets/, tools/png2lvgl.py converter.
- Vehicle: final drive ratio + tyre circumference -> road speed, hp from torque;
  Settings > Vehicle page; `vehicle` console.
- Bench simulation (`sim` console) overlays torque / rpm / shaft on the snapshot.
- EcuIdent: KWP 1A 86 / 1A 80 read once, stored in NVS, shown on Settings >
  Vehicle, passive ECU CHANGED? check; `ecu` console.
- Ignition fallback from the 0x1D2 lever byte on buses without 0x3B4 (Patrol 2).
- Engine data: per-DDE `2C 10` identifier profiles (Patrol 1 vs Patrol 2
  rail 00C2 / boost 003A / battery 002F); DiagProbe liveConfigure().
- Wiki: Patrol 2 captures, vehicles page, obd identifier table per DDE, logs.
2026-10-28 16:46:42 +01:00

196 lines
7.8 KiB
C++

/**
* can_driver.h
*
* CAN Bus driver for ESP32-S3-Touch-LCD-5B using TWAI (Two-Wire Automotive Interface)
* Reads BMW E60/E65 PT-CAN messages at 500 Kbps.
*
* Hardware: GPIO 15 (TX), GPIO 16 (RX)
* Mode: TWAI_MODE_NORMAL — the board ACKs the bus (LISTEN_ONLY can't ACK, which
* makes transmitters flood it with retries). The driver is read-only in
* normal operation; the single sanctioned transmit path is transmit(),
* used ONLY by DiagProbe for on-demand OBD-II requests (see
* src/modules/diag_probe.h). Nothing else may call it.
* Baud: 500 Kbps
*/
#ifndef _CAN_DRIVER_H
#define _CAN_DRIVER_H
#include <Arduino.h>
#include <lvgl.h>
#include "driver/twai.h"
#include "protocol/automotive_data.h"
// ============================================================================
// HARDWARE CONFIGURATION
// ============================================================================
#define CAN_TX_PIN 15
#define CAN_RX_PIN 16
#define CAN_BAUD_RATE TWAI_TIMING_CONFIG_500KBITS()
// ============================================================================
// TASK CONFIGURATION
// ============================================================================
#define CAN_TASK_STACK_SIZE 4096
#define CAN_TASK_PRIORITY 1
#define CAN_TASK_CORE 0 // Run on Core 0 with UART task
// ============================================================================
// CAN EVENT TYPES
// ============================================================================
typedef enum {
CAN_EVENT_START,
CAN_EVENT_STOP
} can_event_type_t;
typedef struct {
can_event_type_t type;
} can_queue_event_t;
// ============================================================================
// CAN STATISTICS
// ============================================================================
typedef struct {
uint32_t messages_received;
uint32_t messages_parsed;
uint32_t parse_errors;
uint32_t last_receive_time;
uint32_t messages_transmitted; // frames handed to the TWAI TX queue (DiagProbe only)
uint32_t tx_failures; // queue refusals + TWAI_ALERT_TX_FAILED (no ACK / bus error)
} can_stats_t;
// ============================================================================
// DRIVELINE STATE
// ============================================================================
// Where driveline_t.ignition_on came from (see the field's comment).
#define IGN_SRC_NONE 0 // no frame seen yet
#define IGN_SRC_3B4 1 // 0x3B4 byte 2 nibble, seen within the last IGN_3B4_HOLD_MS
#define IGN_SRC_LEVER 2 // 0x1D2 byte 0: lever code valid = on, 0xF0 = off
/**
* Decoded driveline speeds. Deliberately NOT part of automotive_data_t: that
* struct is the wire format for the UART link to Inst. Cluster, and widening it
* would break the receiver. These live here until there's a reason to spend a
* protocol version bump on them.
*
* See wiki/pages/driveline-speed-signals.md for the physics and the calibration
* that output_shaft_raw still needs.
*/
typedef struct {
uint16_t engine_rpm; // 0x0AA RPM_ENG (verified)
int16_t engine_torque_x10; // 0x0A8 TORQ_AVL, available engine torque, 0.1 Nm signed
uint16_t turbine_rpm; // 0x1A2 RPM_GRB_TURB (verified). ~engine speed in
// P/N; collapses toward 0 when the box engages.
uint16_t output_shaft_raw; // 0x0BA bytes 3-4, RAW COUNTS — scaling unknown.
// Zero when the output is held, non-zero when the
// wheels turn. The only road-speed signal we have.
uint8_t pedal_percent; // 0x0AA ANG_ACPD
uint8_t engine_run_state; // 0x1D0 ST_ENGINE_RUN (ENGINE_RUN_* constants)
uint8_t gearbox_cooling; // 0x0B5 ST_OTMP_GRB (GEARBOX_COOL_* constants)
uint8_t converter_clutch; // 0x0BA ST_CCLT (CCLT_* constants). When CLOSED,
// turbine_rpm == engine_rpm by design — read this
// before interpreting the two as a slip ratio.
bool ignition_on; // Terminal 15. From 0x3B4 byte 2 low nibble when
// that frame is on the bus (Patrol 1); otherwise
// from the 0x1D2 lever byte: a recognised P/R/N/D
// code means key on, 0xF0 means key off (Patrol 2
// has no 0x3B4 at all - captures 2026-10-18).
uint8_t ignition_src; // IGN_SRC_* : which of the two decided ignition_on
uint8_t lever; // 0x1D2 byte 0 as gear_position_t: the selected
// detent (P/R/N/D). GEAR_UNKNOWN before first frame.
uint8_t engaged_gear; // 0x1D2 byte 1: gear the box is actually in, 1..6;
// 0 = none (P/R/N, and R which is unnumbered here).
// Populated in plain D too, not just S/M.
uint8_t gear_mode; // 0x1D2 byte 4 raw: GEAR_MODE_DRIVE_AUTO / _SPORT
// / _MANUAL. Only meaningful when lever == D.
bool gear_mismatch; // lever (0x1D2) vs gearbox (0x0BA) disagree,
// sustained past the debounce window
} driveline_t;
// ============================================================================
// PUBLIC API
// ============================================================================
namespace CANDriver {
/**
* Initialize CAN driver and create FreeRTOS task
* @param auto_start If true, CAN bus starts listening immediately
*/
void init(bool auto_start = false);
/**
* Start CAN bus reception
*/
void start();
/**
* Stop CAN bus reception
*/
void stop();
/**
* Get current CAN statistics
* @return Statistics structure
*/
can_stats_t getStats();
/**
* Get the decoded driveline speeds (engine / turbine / output shaft).
* Not carried over the UART link — see driveline_t.
* @return Snapshot of the current driveline state
*/
driveline_t getDriveline();
/**
* Check if CAN is currently active
* @return true if CAN is receiving messages
*/
bool isActive();
/**
* Transmit ONE standard (11-bit) frame, single-shot (no automatic
* retransmission if nobody ACKs). The only write path onto the vehicle
* bus; reserved for DiagProbe (console requests + the Engine data screen's
* live poll). Echoes the frame on the console as a "CANTX," line (same
* shape as CANRAW) so captures hold both halves of an exchange; the live
* poll passes echo=false unless CANRAW logging is on (10 frames/s).
* @return true if the frame was queued (delivery is reported via stats)
*/
bool transmit(uint32_t id, const uint8_t* data, uint8_t len, bool echo = true);
/**
* Enable/disable raw frame logging (candump-style capture of EVERY frame).
* When enabled, each received frame is printed to Serial as a compact,
* greppable, re-parseable line prefixed "CANRAW," (see emitRawFrame()).
* Intended for CAN ID discovery: capture a drive, save the serial stream
* to a file, and analyze offline.
* @param enabled true to log every frame
*/
void setRawLogging(bool enabled);
/**
* @return true if raw frame logging is currently enabled
*/
bool isRawLogging();
/**
* Enable/disable verbose per-frame DECODED logging (human-prose ESP_LOG
* lines for known/unknown IDs). Noisy; off by default so it doesn't drown
* the raw capture stream. Independent of setRawLogging().
* @param enabled true to log decoded values per frame
*/
void setVerboseDecode(bool enabled);
/**
* Settings-screen switch: start/stop the CAN task and remember the choice in NVS.
*/
void setEnabled(bool enabled);
}
#endif // _CAN_DRIVER_H