Link protocol v2 receiver, ESP-NOW leg, Patrol gauge outputs, gear pulse
- protocol header v2 copied byte-identical from the 5B repo - uart_receiver: processFrame() shared by the UART framing task and ESP-NOW, version check, dedupe on packet_id+timestamp, per-transport liveness, CONFIG cache with sequence number - espnow_receiver: STA mode, channel hopping while silent, locks on frames - gauge_outputs: tach on IO7 (LEDC ch2, 14-bit), coolant PWM on IO8 (LEDC ch4, 8-bit), config cached in NVS, overrides applied but not saved - main: gear label from lever + engaged/target (pulses while shifting, red on mismatch), icons driven by A's alert bits, gauge update at 5 Hz, link stats - wiki: temp_stage.cfd (user's old CANNY program) decoded as prior art; controller-link, link-redundancy, patrol-gauge-outputs, open-questions updated with the bench-verified v2 results and calibration procedure Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* ESP-NOW Receiver Module (Controller B)
|
||||
*
|
||||
* Wireless leg of the A -> B link. Frames are byte-identical to the UART ones
|
||||
* and are handed to UARTReceiver::processFrame(), which dedupes on packet_id.
|
||||
*
|
||||
* Channel discovery: A transmits on ESPNOW_CHANNEL unless it is associated to
|
||||
* an access point. B listens on ESPNOW_CHANNEL first and, while it hears
|
||||
* nothing, hops through channels 1..13 until frames arrive, then locks.
|
||||
*/
|
||||
|
||||
#ifndef ESPNOW_RECEIVER_H
|
||||
#define ESPNOW_RECEIVER_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace EspNowReceiver {
|
||||
|
||||
/**
|
||||
* Bring the radio up in STA mode and register the receive callback.
|
||||
* @return true if ESP-NOW is listening
|
||||
*/
|
||||
bool init();
|
||||
|
||||
/**
|
||||
* Channel-hopping housekeeping. Call from loop().
|
||||
*/
|
||||
void tick();
|
||||
|
||||
bool isReady();
|
||||
uint8_t currentChannel();
|
||||
uint32_t framesReceived();
|
||||
|
||||
} // namespace EspNowReceiver
|
||||
|
||||
#endif // ESPNOW_RECEIVER_H
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Gauge Outputs Module (Controller B)
|
||||
*
|
||||
* Drives the Nissan Patrol cluster from the data Controller A sends:
|
||||
* - tachometer: variable-frequency square wave on IO7 (LEDC timer 1)
|
||||
* - coolant gauge: fixed-frequency PWM with variable duty on IO8 (LEDC timer 2)
|
||||
*
|
||||
* Everything tunable comes from link_config_t (pushed by A in CONFIG frames,
|
||||
* cached in NVS so a reboot of B does not wait for A). Both outputs are held
|
||||
* OFF while the link is down or the source value is invalid, unless A has set
|
||||
* a calibration override.
|
||||
*
|
||||
* External driver stages are mandatory: 3.3 V logic drives neither gauge
|
||||
* directly. See wiki/pages/patrol-gauge-outputs.md
|
||||
*/
|
||||
|
||||
#ifndef GAUGE_OUTPUTS_H
|
||||
#define GAUGE_OUTPUTS_H
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "protocol/automotive_data.h"
|
||||
|
||||
namespace GaugeOutputs {
|
||||
|
||||
#define GAUGE_TACH_PIN 7
|
||||
#define GAUGE_TEMP_PIN 8
|
||||
|
||||
/**
|
||||
* Load the last config from NVS (defaults if none) and set up both LEDC channels
|
||||
* with the outputs OFF.
|
||||
*/
|
||||
void init();
|
||||
|
||||
/**
|
||||
* Apply a configuration received from A. Persists it to NVS when persist is true
|
||||
* (overrides arrive unsaved by design: A does not persist them either).
|
||||
*/
|
||||
void applyConfig(const link_config_t& cfg, bool persist);
|
||||
|
||||
link_config_t getConfig();
|
||||
|
||||
/**
|
||||
* Recompute both outputs from the latest data. Call at the data rate (5 Hz).
|
||||
* @param d latest automotive_data_t from A
|
||||
* @param link_ok false when no valid frame has arrived within the link timeout
|
||||
*/
|
||||
void update(const automotive_data_t& d, bool link_ok);
|
||||
|
||||
/**
|
||||
* Print a one-line status (frequency, duty, source of each output) to Serial.
|
||||
*/
|
||||
void printStatus();
|
||||
|
||||
} // namespace GaugeOutputs
|
||||
|
||||
#endif // GAUGE_OUTPUTS_H
|
||||
@@ -1,15 +1,14 @@
|
||||
/**
|
||||
* UART Receiver Module for ESP32-S3-LCD-1.3 (Controller B)
|
||||
* Link Receiver Module (Controller B)
|
||||
*
|
||||
* Receives automotive data packets from Controller A (ESP32-S3-Touch-LCD-5B)
|
||||
* via UART at 115200 baud, 5Hz update rate.
|
||||
* Receives v2 frames from Controller A on two transports:
|
||||
* - UART1 (byte stream, framed here with a state machine)
|
||||
* - ESP-NOW (whole frames, delivered by EspNowReceiver)
|
||||
* Both feed processFrame(). DATA frames are deduplicated on packet_id so a frame
|
||||
* that arrives on both paths is applied once; CONFIG frames update the cached
|
||||
* link_config_t and bump a sequence number the main loop watches.
|
||||
*
|
||||
* Features:
|
||||
* - State machine-based packet parsing
|
||||
* - XOR checksum validation
|
||||
* - Thread-safe data access
|
||||
* - Connection monitoring and timeout detection
|
||||
* - Error statistics tracking
|
||||
* The namespace keeps its historical name; it is the link receiver for both paths.
|
||||
*/
|
||||
|
||||
#ifndef UART_RECEIVER_H
|
||||
@@ -18,65 +17,63 @@
|
||||
#include <Arduino.h>
|
||||
#include "protocol/automotive_data.h"
|
||||
|
||||
typedef enum {
|
||||
LINK_SOURCE_NONE = 0,
|
||||
LINK_SOURCE_UART = 1,
|
||||
LINK_SOURCE_ESPNOW = 2
|
||||
} link_source_t;
|
||||
|
||||
namespace UARTReceiver {
|
||||
|
||||
/**
|
||||
* @brief UART RX statistics structure
|
||||
*/
|
||||
typedef struct {
|
||||
uint32_t packets_received; // Total valid packets received
|
||||
uint32_t checksum_errors; // Packets with invalid checksum
|
||||
uint32_t framing_errors; // Packets with framing errors
|
||||
uint32_t timeout_errors; // Connection timeout events
|
||||
uint32_t last_packet_time; // millis() when last valid packet received
|
||||
uint32_t bytes_received; // Total bytes received
|
||||
uint32_t packets_received; // DATA frames applied (after dedupe)
|
||||
uint32_t packets_uart; // valid DATA frames seen on UART
|
||||
uint32_t packets_espnow; // valid DATA frames seen on ESP-NOW
|
||||
uint32_t duplicates; // DATA frames dropped as already applied
|
||||
uint32_t config_received; // CONFIG frames accepted
|
||||
uint32_t checksum_errors;
|
||||
uint32_t framing_errors;
|
||||
uint32_t version_errors; // frames from a different PACKET_VERSION
|
||||
uint32_t timeout_errors;
|
||||
uint32_t last_packet_time; // millis() of the last applied DATA frame
|
||||
uint32_t last_uart_time; // millis() of the last valid UART frame
|
||||
uint32_t last_espnow_time; // millis() of the last valid ESP-NOW frame
|
||||
uint32_t bytes_received; // UART bytes
|
||||
link_source_t last_source; // transport of the last applied DATA frame
|
||||
} uart_rx_stats_t;
|
||||
|
||||
/**
|
||||
* @brief Initialize UART receiver module
|
||||
*
|
||||
* Initializes Serial1 hardware and creates FreeRTOS reception task on Core 0.
|
||||
*
|
||||
* @return true if initialization successful, false otherwise
|
||||
* Create the mutex and the UART1 receive task on Core 0.
|
||||
*/
|
||||
bool init();
|
||||
|
||||
/**
|
||||
* @brief Get the latest received automotive data
|
||||
*
|
||||
* Thread-safe access to the most recently received valid packet.
|
||||
*
|
||||
* @return Copy of the latest automotive_data_t structure
|
||||
* Validate and apply one complete frame (start..end). Safe to call from the
|
||||
* ESP-NOW receive callback or the UART task.
|
||||
*/
|
||||
automotive_data_t getLatestData();
|
||||
void processFrame(const uint8_t* frame, size_t len, link_source_t source);
|
||||
|
||||
/**
|
||||
* @brief Get UART reception statistics
|
||||
*
|
||||
* @return Copy of current RX statistics
|
||||
*/
|
||||
automotive_data_t getLatestData();
|
||||
uart_rx_stats_t getStats();
|
||||
|
||||
/**
|
||||
* @brief Check if connection is active
|
||||
*
|
||||
* Returns true if a valid packet was received within the last timeout period.
|
||||
*
|
||||
* @param timeout_ms Timeout in milliseconds (default: 1000ms)
|
||||
* @return true if connection is active, false if timed out
|
||||
* True if a DATA frame was applied within timeout_ms, on either transport.
|
||||
*/
|
||||
bool isConnected(uint32_t timeout_ms = 1000);
|
||||
|
||||
/**
|
||||
* @brief Reset statistics counters
|
||||
* True if the given transport delivered a valid frame within timeout_ms.
|
||||
*/
|
||||
void resetStats();
|
||||
bool isSourceAlive(link_source_t source, uint32_t timeout_ms = 1000);
|
||||
|
||||
/**
|
||||
* @brief Get time since last valid packet in milliseconds
|
||||
*
|
||||
* @return Milliseconds since last packet, or UINT32_MAX if no packets received
|
||||
* Latest CONFIG payload from A (defaults until one arrives) and a sequence
|
||||
* number that increments each time a new one is accepted.
|
||||
*/
|
||||
link_config_t getConfig();
|
||||
uint32_t getConfigSeq();
|
||||
|
||||
void resetStats();
|
||||
uint32_t getTimeSinceLastPacket();
|
||||
|
||||
} // namespace UARTReceiver
|
||||
|
||||
+560
-112
@@ -1,133 +1,368 @@
|
||||
/**
|
||||
* 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 (matches UART protocol specification)
|
||||
// What the driver selected (0x1D2 byte 0 + byte 4 mode). This is the wire enum.
|
||||
typedef enum {
|
||||
GEAR_PARK = 0, // Park - transmission locked
|
||||
GEAR_REVERSE = 1, // Reverse gear
|
||||
GEAR_NEUTRAL = 2, // Neutral - no gear engaged
|
||||
GEAR_DRIVE = 3, // Drive - automatic mode
|
||||
GEAR_SPORT = 4, // Sport mode
|
||||
GEAR_MANUAL = 5, // Manual/Sequential mode
|
||||
GEAR_MANUAL_1 = 6, // Manual 1st gear
|
||||
GEAR_MANUAL_2 = 7, // Manual 2nd gear
|
||||
GEAR_MANUAL_3 = 8, // Manual 3rd gear
|
||||
GEAR_MANUAL_4 = 9, // Manual 4th gear
|
||||
GEAR_MANUAL_5 = 10, // Manual 5th gear
|
||||
GEAR_MANUAL_6 = 11, // Manual 6th gear
|
||||
GEAR_MANUAL_7 = 12, // Manual 7th gear
|
||||
GEAR_MANUAL_8 = 13, // Manual 8th gear
|
||||
GEAR_ERROR = 14 // Transmission fault/unknown
|
||||
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;
|
||||
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
|
||||
// ============================================================================
|
||||
// CAN BUS ID MAPPINGS (Placeholder - User will provide real IDs)
|
||||
// ============================================================================
|
||||
|
||||
// Standard OBD-II PIDs (example placeholders)
|
||||
// User needs to replace these with actual CAN message IDs for their vehicle
|
||||
#define CAN_ID_GEAR_POSITION 0x0C0 // Placeholder - vehicle specific
|
||||
#define CAN_ID_GEARBOX_TEMP 0x5C // Placeholder - typically proprietary
|
||||
#define CAN_ID_ENGINE_OIL_TEMP 0x5C // Placeholder - not standard OBD-II
|
||||
#define CAN_ID_COOLANT_TEMP 0x05 // Standard OBD-II PID (if using OBD-II)
|
||||
#define CAN_ID_BATTERY_VOLTAGE 0x42 // Standard OBD-II PID for system voltage
|
||||
#define CAN_ID_FAULT_CODES 0x01 // Standard OBD-II PID for DTCs
|
||||
|
||||
// Extended CAN IDs (29-bit) if needed
|
||||
#define USE_EXTENDED_CAN_IDS false // Set to true for 29-bit CAN IDs
|
||||
|
||||
// ============================================================================
|
||||
// PACKET STRUCTURE FOR UART TRANSMISSION
|
||||
// CONFIG FRAME PAYLOAD - tunables edited on A, executed on B
|
||||
// ============================================================================
|
||||
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS
|
||||
// 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
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 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;
|
||||
@@ -138,40 +373,257 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert temperature from CAN format to internal format
|
||||
* @param can_value Raw CAN bus value
|
||||
* @param offset Temperature offset (usually -40 for automotive)
|
||||
* @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 = -40) {
|
||||
return (int16_t)((can_value + offset) * 10); // Convert to 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert voltage from CAN format to internal format
|
||||
* @param can_value Raw CAN bus value (typically in 0.1V)
|
||||
* 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(uint16_t can_value) {
|
||||
return can_value * 10; // Convert 0.1V to 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -185,17 +637,12 @@ static inline const char* gear_to_string(gear_position_t gear) {
|
||||
case GEAR_REVERSE: return "R";
|
||||
case GEAR_NEUTRAL: return "N";
|
||||
case GEAR_DRIVE: return "D";
|
||||
case GEAR_SPORT: return "S";
|
||||
case GEAR_MANUAL: return "M";
|
||||
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";
|
||||
case GEAR_MANUAL_7: return "7";
|
||||
case GEAR_MANUAL_8: return "8";
|
||||
case GEAR_ERROR: return "?";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
@@ -207,6 +654,7 @@ 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) {
|
||||
// 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;
|
||||
}
|
||||
@@ -227,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
|
||||
Reference in New Issue
Block a user