e10e03eb90
Boot screen: land on the Driveline data screen instead of the SquareLine gauges Home screen. Done in display_init after ui_init while the backlight is still off (no flash of the wrong screen); Home stays reachable by swiping off Driveline. Engine torque added to the screen, decoded from 0x0A8 TORQ_AVL (available/ delivered torque), bits 12-23, signed x0.5 Nm. The user identified the ID and supplied the spreadsheet formula (D2*256+D1)/32, which is algebraically bits12-23 x0.5; confirmed against the repo's 0x0A8 worked example (24 Nm). Firmware masks D1's low nibble (that's the alive counter, not torque - the repo example shows ALIV=8 there) and sign-extends so overrun reads negative. 0x0AA TORQ_DVCH is the same layout but driver demand - identical at idle, diverges under load - so the delivered value is the right one to show. Output-shaft scaling revised: a direct Launch reference (output speed 128 rpm at our raw 1192) implies ~0.107, contradicting the earlier x0.125 (which would predict 149). One eyeballed cross-tool point, so nothing is adopted - the field stays raw counts - but 0.125 is downgraded in firmware and wiki, and the Launch now gives a direct rpm reference so calibration is just a multi-point sweep and a linear fit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
625 lines
24 KiB
C++
625 lines
24 KiB
C++
/**
|
|
* can_driver.cpp
|
|
*
|
|
* CAN Bus driver implementation for BMW vehicle data reception
|
|
* Based on Waveshare TWAI receive example
|
|
*/
|
|
|
|
#include "drivers/can_driver.h"
|
|
#include "modules/uart_manager.h"
|
|
#include "modules/settings_manager.h"
|
|
#include "modules/serial_lock.h"
|
|
#include "esp_log.h"
|
|
|
|
// Import shared data from UARTManager namespace
|
|
using UARTManager::g_data_mutex;
|
|
using UARTManager::g_automotive_data;
|
|
|
|
namespace CANDriver {
|
|
|
|
// ============================================================================
|
|
// CONFIGURATION
|
|
// ============================================================================
|
|
|
|
// CAN timeout threshold - stop UART if no messages received for this duration
|
|
#define CAN_TIMEOUT_MS 2000 // 2 seconds (for 5Hz expected rate, this is 10 missed messages)
|
|
|
|
// How long the lever (0x1D2) and the gearbox (0x0BA) must disagree before we call
|
|
// it a fault. They legitimately differ for a moment during every shift — 0x1D2 is
|
|
// a 200ms message and 0x0BA a 20ms one, so they are never perfectly in step.
|
|
// Without this window the flag would strobe on every gear change.
|
|
#define GEAR_MISMATCH_DEBOUNCE_MS 500
|
|
|
|
// ============================================================================
|
|
// MODULE STATE
|
|
// ============================================================================
|
|
|
|
static bool g_can_active = false;
|
|
static TaskHandle_t g_can_task_handle = NULL;
|
|
static QueueHandle_t g_can_event_queue = NULL;
|
|
static can_stats_t g_can_stats = {0};
|
|
static bool g_uart_auto_stopped = false; // Track if UART was auto-stopped due to CAN timeout
|
|
|
|
// Raw frame logging: capture EVERY frame (candump-style) for offline CAN ID
|
|
// discovery. Default ON since discovery is the current priority.
|
|
static bool g_raw_logging = true;
|
|
// Verbose per-frame DECODED prose logging. Default OFF: it's redundant with
|
|
// (and would drown) the raw capture stream. Enable only for quick eyeballing.
|
|
static bool g_verbose_decode = false;
|
|
|
|
// Driveline speeds — decoded but NOT sent over UART (see driveline_t in the header).
|
|
// Guarded by g_data_mutex along with g_automotive_data.
|
|
static driveline_t g_driveline = {0};
|
|
|
|
// Last gear LEVER code seen on 0x1D2, for the lever-vs-gearbox cross-check.
|
|
static gear_position_t g_last_lever = GEAR_UNKNOWN;
|
|
// When the current disagreement started (0 = currently in agreement).
|
|
static uint32_t g_mismatch_since = 0;
|
|
|
|
// ============================================================================
|
|
// PRIVATE FUNCTIONS
|
|
// ============================================================================
|
|
|
|
/**
|
|
* @brief Cross-check the driver's lever selection against the gearbox's own
|
|
* target gear and raise a fault if they disagree for long enough.
|
|
*
|
|
* This is the "lever says R but the car isn't moving" detector: if the box never
|
|
* took the request, 0x0BA reports a different gear than the lever shows.
|
|
*
|
|
* Note this compares INTENT, not mechanical engagement — 0x0BA is a target gear.
|
|
* Proving the box physically caught requires the turbine/engine speed ratio, which
|
|
* needs output-shaft calibration to gate correctly (it reads "not engaged" whenever
|
|
* the wheels are free, e.g. on a lift). Not attempted here on purpose.
|
|
* See wiki/pages/driveline-speed-signals.md
|
|
*
|
|
* Caller must hold g_data_mutex.
|
|
* @param target Gear the gearbox reports as its target
|
|
*/
|
|
static void updateGearMismatch(gear_position_t target) {
|
|
// Ignore frames we can't interpret rather than guessing a mismatch from them.
|
|
if (target == GEAR_UNKNOWN || g_last_lever == GEAR_UNKNOWN) return;
|
|
|
|
// The lever's D detent covers D/S/M; can_to_target_gear() maps every forward
|
|
// gear to GEAR_DRIVE, so both sides are directly comparable.
|
|
bool disagrees = (target != g_last_lever);
|
|
|
|
if (!disagrees) {
|
|
g_mismatch_since = 0;
|
|
g_driveline.gear_mismatch = false;
|
|
g_automotive_data.fault_codes &= ~FAULT_GEAR_MISMATCH;
|
|
return;
|
|
}
|
|
|
|
uint32_t now = millis();
|
|
if (g_mismatch_since == 0) {
|
|
g_mismatch_since = now; // start the clock, don't fault yet
|
|
} else if ((now - g_mismatch_since) >= GEAR_MISMATCH_DEBOUNCE_MS) {
|
|
g_driveline.gear_mismatch = true;
|
|
g_automotive_data.fault_codes |= FAULT_GEAR_MISMATCH;
|
|
g_automotive_data.valid_flags |= VALID_FLAG_FAULT_CODES;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @brief Parse BMW-specific CAN message and update automotive data
|
|
* @param message Received TWAI message
|
|
* @return true if message was parsed, false if unknown ID
|
|
*/
|
|
static bool parseCANMessage(const twai_message_t& message) {
|
|
bool parsed = false;
|
|
uint32_t id = message.identifier;
|
|
const uint8_t* data = message.data;
|
|
|
|
// Acquire mutex to update shared data (10ms timeout to prevent blocking)
|
|
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) != pdTRUE) {
|
|
ESP_LOGE("CANDrv", "Failed to acquire data mutex");
|
|
return false;
|
|
}
|
|
|
|
uint8_t dlc = message.data_length_code;
|
|
|
|
switch (id) {
|
|
case CAN_ID_ENGINE_DATA:
|
|
// 0x1D0: coolant (byte 0), engine oil (byte 1), engine run state (byte 2).
|
|
if (dlc > CAN_BYTE_COOLANT_TEMP) {
|
|
g_automotive_data.coolant_temp =
|
|
can_to_temperature(data[CAN_BYTE_COOLANT_TEMP], ENGINE_TEMP_OFFSET);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_COOLANT_TEMP;
|
|
parsed = true;
|
|
}
|
|
// Oil temp reads 0xFF on this M57N — the sensor isn't populated. Leave
|
|
// the valid flag clear rather than publishing -207 C as if it were real.
|
|
if (dlc > CAN_BYTE_ENGINE_OIL_TEMP && data[CAN_BYTE_ENGINE_OIL_TEMP] != 0xFF) {
|
|
g_automotive_data.engine_oil_temp =
|
|
can_to_temperature(data[CAN_BYTE_ENGINE_OIL_TEMP], ENGINE_TEMP_OFFSET);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_ENGINE_TEMP;
|
|
}
|
|
if (dlc > CAN_BYTE_ENGINE_STATUS) {
|
|
g_driveline.engine_run_state = (data[CAN_BYTE_ENGINE_STATUS] >> 4) & 0x03;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_TORQUE_EGS:
|
|
// 0x0B5: gearbox oil temp (byte 7) + the box's own cooling demand.
|
|
if (dlc > CAN_BYTE_GEARBOX_TEMP) {
|
|
g_automotive_data.gearbox_oil_temp =
|
|
can_to_temperature(data[CAN_BYTE_GEARBOX_TEMP], GEARBOX_TEMP_OFFSET);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_GEARBOX_TEMP;
|
|
parsed = true;
|
|
}
|
|
if (dlc > CAN_BYTE_GEARBOX_COOL) {
|
|
// ST_OTMP_GRB = bits 38-39 = byte 4, bits 6-7
|
|
g_driveline.gearbox_cooling = (data[CAN_BYTE_GEARBOX_COOL] >> 6) & 0x03;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_GEAR_DISPLAY: {
|
|
// 0x1D2: the EGS publishing its whole state — byte 0 is what the driver
|
|
// selected, byte 1 is what's actually engaged, byte 4 is the mode.
|
|
gear_position_t g = decode_gear(data, dlc);
|
|
if (g != GEAR_UNKNOWN) {
|
|
g_automotive_data.gear_position = (uint8_t)g;
|
|
g_automotive_data.valid_flags |= VALID_FLAG_GEAR_POS;
|
|
parsed = true;
|
|
}
|
|
// Keep the bare lever (not the resolved display value) for the
|
|
// cross-check below: 0x0BA reports a gear, never a mode.
|
|
if (dlc > CAN_BYTE_GEAR_LEVER) {
|
|
g_last_lever = can_to_gear_lever(data[CAN_BYTE_GEAR_LEVER]);
|
|
}
|
|
break;
|
|
}
|
|
|
|
case CAN_ID_GEARBOX_STATE: {
|
|
// 0x0BA: the gearbox's own target gear — the ONLY source of engaged
|
|
// reverse (0x1D2 byte 1 stays 0x0F in R) — plus the output shaft.
|
|
if (dlc > CAN_BYTE_GEARBOX_TARGET) {
|
|
gear_position_t target =
|
|
can_to_target_gear(data[CAN_BYTE_GEARBOX_TARGET] & 0x0F);
|
|
updateGearMismatch(target);
|
|
// ST_CCLT lives in the top two bits of the same byte.
|
|
g_driveline.converter_clutch =
|
|
(data[CAN_BYTE_CONVERTER_CLUTCH] >> 6) & 0x03;
|
|
parsed = true;
|
|
}
|
|
if (dlc > CAN_BYTE_OUTPUT_SHAFT_H) {
|
|
// Raw counts only — scaling uncalibrated, so no physical unit.
|
|
g_driveline.output_shaft_raw =
|
|
(uint16_t)((data[CAN_BYTE_OUTPUT_SHAFT_H] << 8) | data[CAN_BYTE_OUTPUT_SHAFT_L]);
|
|
}
|
|
break;
|
|
}
|
|
|
|
case CAN_ID_TURBINE_SPEED:
|
|
// 0x1A2: gearbox input speed — the physical engagement signal.
|
|
if (dlc > CAN_BYTE_TURBINE_H) {
|
|
g_driveline.turbine_rpm = can_to_turbine_rpm(data);
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_TORQUE_1:
|
|
// 0x0A8: TORQ_AVL — available/delivered engine torque.
|
|
if (dlc > CAN_BYTE_TORQUE_H) {
|
|
g_driveline.engine_torque_x10 = can_to_torque_x10(data);
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_TORQUE_3:
|
|
// 0x0AA: engine RPM + accelerator pedal.
|
|
if (dlc > CAN_BYTE_RPM_H) {
|
|
g_driveline.engine_rpm = can_to_rpm(data);
|
|
parsed = true;
|
|
}
|
|
if (dlc > CAN_BYTE_PEDAL_POS) {
|
|
// ANG_ACPD: % = raw * 0.39063 (i.e. raw * 100 / 256)
|
|
g_driveline.pedal_percent = (uint8_t)((data[CAN_BYTE_PEDAL_POS] * 100) / 256);
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_BATTERY_VOLTAGE:
|
|
// 0x3B4: U_BT (12-bit LE x 0.015 V) + ignition state.
|
|
if (dlc > CAN_BYTE_BATTERY_VOLT_H) {
|
|
// The field reads 0xFFF (not-available) on nearly every frame of
|
|
// this bus. Publishing that would put a confident 61 V on the
|
|
// display, so only accept real readings and leave the valid flag
|
|
// clear otherwise.
|
|
if (can_battery_raw(data) != BATTERY_RAW_INVALID) {
|
|
g_automotive_data.battery_voltage = can_to_voltage(data);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_BATTERY_VOLT;
|
|
}
|
|
parsed = true;
|
|
}
|
|
if (dlc > CAN_BYTE_IGNITION) {
|
|
// Byte 2's low nibble tracks ignition (inverted), NOT engine run
|
|
// — verified on this bus against both published claims.
|
|
g_driveline.ignition_on =
|
|
((data[CAN_BYTE_IGNITION] & 0x0F) == IGNITION_ON);
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
default:
|
|
// Unknown CAN ID - ignore
|
|
break;
|
|
}
|
|
|
|
xSemaphoreGive(g_data_mutex);
|
|
|
|
return parsed;
|
|
}
|
|
|
|
/**
|
|
* @brief Emit one raw CAN frame as a compact, greppable, re-parseable line.
|
|
*
|
|
* Format (CSV, one frame per line):
|
|
* CANRAW,<ts_ms>,<id_hex>,<extd>,<dlc>,<data_hex>
|
|
* where:
|
|
* ts_ms = millis() timestamp (relative to boot)
|
|
* id_hex = arbitration ID in hex, no 0x prefix (3 digits min for 11-bit)
|
|
* extd = 1 if 29-bit extended ID, 0 if 11-bit standard
|
|
* dlc = data length code (0..8)
|
|
* data_hex = payload bytes, uppercase hex, no separators (e.g. 1122AABB)
|
|
*
|
|
* The "CANRAW," prefix lets you filter these out of the mixed ESP_LOG serial
|
|
* stream: pio device monitor > drive.log then grep CANRAW, drive.log
|
|
*
|
|
* @param message Received TWAI message
|
|
*/
|
|
static void emitRawFrame(const twai_message_t& message) {
|
|
char buf[72];
|
|
int n = snprintf(buf, sizeof(buf), "CANRAW,%lu,%03lX,%u,%u,",
|
|
(unsigned long)millis(),
|
|
(unsigned long)message.identifier,
|
|
(unsigned)(message.extd ? 1 : 0),
|
|
(unsigned)message.data_length_code);
|
|
for (int i = 0; i < message.data_length_code && n < (int)sizeof(buf) - 4; i++) {
|
|
n += snprintf(buf + n, sizeof(buf) - n, "%02X", message.data[i]);
|
|
}
|
|
// Append the line terminator into the SAME buffer so the whole frame goes
|
|
// out in one Serial.write() — no other task can splice into the middle.
|
|
buf[n++] = '\r';
|
|
buf[n++] = '\n';
|
|
|
|
// Serialize against all other serial writers so lines never interleave.
|
|
SerialLock::lock();
|
|
Serial.write((const uint8_t*)buf, n);
|
|
SerialLock::unlock();
|
|
}
|
|
|
|
/**
|
|
* @brief Handle received CAN message
|
|
* @param message TWAI message structure
|
|
*/
|
|
static void handleRxMessage(twai_message_t& message) {
|
|
g_can_stats.messages_received++;
|
|
g_can_stats.last_receive_time = millis();
|
|
|
|
// Raw capture FIRST, before parse — logs every frame including unknown IDs
|
|
if (g_raw_logging) {
|
|
emitRawFrame(message);
|
|
}
|
|
|
|
// Auto-restart UART if it was stopped due to CAN timeout
|
|
if (g_uart_auto_stopped) {
|
|
ESP_LOGI("CANDrv", "✓ CAN messages resumed, auto-restarting UART");
|
|
UARTManager::linkToCANState(true);
|
|
g_uart_auto_stopped = false;
|
|
}
|
|
|
|
// Parse the message
|
|
if (parseCANMessage(message)) {
|
|
g_can_stats.messages_parsed++;
|
|
|
|
// Per-frame decoded prose — off by default (redundant with raw capture)
|
|
if (g_verbose_decode && xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
|
ESP_LOGI("CANDrv", "✓ RX 0x%X → Gear:%s%s Coolant:%d.%d°C Gearbox:%d.%d°C Batt:%d.%02dV | RPM:%u Turb:%u Shaft:%u [%d/%d]",
|
|
message.identifier,
|
|
gear_to_string((gear_position_t)g_automotive_data.gear_position),
|
|
g_driveline.gear_mismatch ? " !MISMATCH" : "",
|
|
g_automotive_data.coolant_temp / 10, abs(g_automotive_data.coolant_temp % 10),
|
|
g_automotive_data.gearbox_oil_temp / 10, abs(g_automotive_data.gearbox_oil_temp % 10),
|
|
g_automotive_data.battery_voltage / 100, g_automotive_data.battery_voltage % 100,
|
|
g_driveline.engine_rpm,
|
|
g_driveline.turbine_rpm,
|
|
g_driveline.output_shaft_raw,
|
|
g_can_stats.messages_parsed,
|
|
g_can_stats.messages_received);
|
|
xSemaphoreGive(g_data_mutex);
|
|
}
|
|
} else if (g_verbose_decode) {
|
|
// Unknown message ID (raw capture already logged it; this is just prose)
|
|
ESP_LOGW("CANDrv", "⚠ Unknown CAN ID=0x%X (DLC=%d) [%d total]",
|
|
message.identifier,
|
|
message.data_length_code,
|
|
g_can_stats.messages_received);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @brief Initialize TWAI driver
|
|
* @return true if successful
|
|
*/
|
|
static bool initTWAI() {
|
|
// General config - NORMAL mode (can send ACK to prevent retransmissions)
|
|
// Note: LISTEN_ONLY mode cannot ACK, causing transmitters to flood the bus with retries
|
|
twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(
|
|
(gpio_num_t)CAN_TX_PIN,
|
|
(gpio_num_t)CAN_RX_PIN,
|
|
TWAI_MODE_NORMAL // Required to send ACK bits - prevents message flooding
|
|
);
|
|
|
|
// Increase RX queue from default 5 to 20 to handle burst traffic
|
|
// At 25 msg/sec, this provides 800ms buffer (20/25 = 0.8s)
|
|
g_config.rx_queue_len = 20;
|
|
|
|
// Timing config - 500 Kbps for BMW
|
|
twai_timing_config_t t_config = CAN_BAUD_RATE;
|
|
|
|
// Filter config - accept all messages (we'll filter in software)
|
|
twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();
|
|
|
|
// Install TWAI driver
|
|
if (twai_driver_install(&g_config, &t_config, &f_config) != ESP_OK) {
|
|
ESP_LOGE("CANDrv", "Failed to install TWAI driver");
|
|
return false;
|
|
}
|
|
ESP_LOGI("CANDrv", "TWAI driver installed (GPIO%d/GPIO%d, 500Kbps, NORMAL/ACK)",
|
|
CAN_TX_PIN, CAN_RX_PIN);
|
|
|
|
// Start TWAI driver
|
|
if (twai_start() != ESP_OK) {
|
|
ESP_LOGE("CANDrv", "Failed to start TWAI driver");
|
|
return false;
|
|
}
|
|
ESP_LOGI("CANDrv", "TWAI driver started");
|
|
|
|
// Configure alerts
|
|
uint32_t alerts_to_enable = TWAI_ALERT_RX_DATA |
|
|
TWAI_ALERT_ERR_PASS |
|
|
TWAI_ALERT_BUS_ERROR |
|
|
TWAI_ALERT_RX_QUEUE_FULL;
|
|
|
|
if (twai_reconfigure_alerts(alerts_to_enable, NULL) != ESP_OK) {
|
|
ESP_LOGE("CANDrv", "Failed to reconfigure alerts");
|
|
return false;
|
|
}
|
|
ESP_LOGI("CANDrv", "CAN alerts configured");
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* @brief Stop and uninstall TWAI driver
|
|
*/
|
|
static void deinitTWAI() {
|
|
twai_stop();
|
|
twai_driver_uninstall();
|
|
ESP_LOGI("CANDrv", "TWAI driver stopped and uninstalled");
|
|
}
|
|
|
|
/**
|
|
* @brief CAN reception task (runs on Core 0)
|
|
* @param parameter Unused
|
|
*/
|
|
static void canTask(void* parameter) {
|
|
ESP_LOGI("CANTask", "CAN task started on Core 0");
|
|
|
|
while (true) {
|
|
// Check for queue events (start/stop commands)
|
|
// Use shorter timeout when CAN active for faster message processing
|
|
uint32_t queue_timeout = g_can_active ? 1 : 10;
|
|
can_queue_event_t event;
|
|
if (xQueueReceive(g_can_event_queue, &event, pdMS_TO_TICKS(queue_timeout)) == pdTRUE) {
|
|
switch (event.type) {
|
|
case CAN_EVENT_START:
|
|
if (!g_can_active) {
|
|
ESP_LOGI("CANTask", "Starting CAN reception...");
|
|
if (initTWAI()) {
|
|
g_can_active = true;
|
|
memset(&g_can_stats, 0, sizeof(g_can_stats));
|
|
// Drop stale driveline/gear state from a previous session
|
|
memset(&g_driveline, 0, sizeof(g_driveline));
|
|
g_last_lever = GEAR_UNKNOWN;
|
|
g_mismatch_since = 0;
|
|
ESP_LOGI("CANTask", "CAN reception active");
|
|
|
|
// Auto-start UART transmission (CAN drives UART)
|
|
UARTManager::linkToCANState(true);
|
|
} else {
|
|
ESP_LOGE("CANTask", "Failed to start CAN reception");
|
|
}
|
|
}
|
|
break;
|
|
|
|
case CAN_EVENT_STOP:
|
|
if (g_can_active) {
|
|
ESP_LOGI("CANTask", "Stopping CAN reception...");
|
|
deinitTWAI();
|
|
g_can_active = false;
|
|
g_uart_auto_stopped = false; // Reset auto-stop flag
|
|
|
|
// Auto-stop UART transmission (CAN drives UART)
|
|
UARTManager::linkToCANState(false);
|
|
|
|
ESP_LOGI("CANTask", "CAN stopped. Stats: %d msgs received, %d parsed",
|
|
g_can_stats.messages_received,
|
|
g_can_stats.messages_parsed);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
// If CAN is active, poll for messages
|
|
if (g_can_active) {
|
|
uint32_t alerts_triggered;
|
|
// Use 0 timeout (non-blocking) for faster polling
|
|
twai_read_alerts(&alerts_triggered, 0);
|
|
|
|
// Handle error alerts
|
|
if (alerts_triggered & TWAI_ALERT_ERR_PASS) {
|
|
ESP_LOGW("CANTask", "TWAI controller has become error passive");
|
|
}
|
|
if (alerts_triggered & TWAI_ALERT_BUS_ERROR) {
|
|
twai_status_info_t status;
|
|
twai_get_status_info(&status);
|
|
ESP_LOGW("CANTask", "Bus error detected (count: %d)", status.bus_error_count);
|
|
g_can_stats.parse_errors++;
|
|
}
|
|
if (alerts_triggered & TWAI_ALERT_RX_QUEUE_FULL) {
|
|
twai_status_info_t status;
|
|
twai_get_status_info(&status);
|
|
ESP_LOGW("CANTask", "RX queue full! Missed: %d, Overrun: %d, Queue: %d",
|
|
status.rx_missed_count, status.rx_overrun_count, status.msgs_to_rx);
|
|
g_can_stats.parse_errors++; // Track overflow events
|
|
}
|
|
|
|
// Periodic queue depth monitoring (every 1000 messages)
|
|
if (g_can_stats.messages_received % 1000 == 0 && g_can_stats.messages_received > 0) {
|
|
twai_status_info_t status;
|
|
twai_get_status_info(&status);
|
|
ESP_LOGI("CANTask", "Queue health: %d msgs pending (max 20)", status.msgs_to_rx);
|
|
}
|
|
|
|
// Handle received messages
|
|
if (alerts_triggered & TWAI_ALERT_RX_DATA) {
|
|
twai_message_t message;
|
|
while (twai_receive(&message, 0) == ESP_OK) {
|
|
handleRxMessage(message);
|
|
}
|
|
}
|
|
|
|
// Check for CAN timeout - stop UART if no messages received recently
|
|
if (g_can_stats.messages_received > 0) { // Only check if we've received at least one message
|
|
uint32_t time_since_last_rx = millis() - g_can_stats.last_receive_time;
|
|
|
|
if (time_since_last_rx > CAN_TIMEOUT_MS && !g_uart_auto_stopped) {
|
|
// CAN data is stale - auto-stop UART to prevent transmitting stale data
|
|
ESP_LOGW("CANTask", "⚠ CAN timeout (%dms since last message), auto-stopping UART", time_since_last_rx);
|
|
UARTManager::linkToCANState(false);
|
|
g_uart_auto_stopped = true;
|
|
}
|
|
}
|
|
} else {
|
|
// CAN inactive, sleep longer to save CPU
|
|
vTaskDelay(pdMS_TO_TICKS(100));
|
|
}
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// PUBLIC API IMPLEMENTATION
|
|
// ============================================================================
|
|
|
|
void init(bool auto_start) {
|
|
ESP_LOGI("CANDrv", "Initializing CAN subsystem...");
|
|
|
|
// Create event queue
|
|
g_can_event_queue = xQueueCreate(10, sizeof(can_queue_event_t));
|
|
if (g_can_event_queue == NULL) {
|
|
ESP_LOGE("CANDrv", "ERROR: Failed to create CAN event queue!");
|
|
return;
|
|
}
|
|
|
|
// Create CAN task on Core 0
|
|
BaseType_t task_created = xTaskCreatePinnedToCore(
|
|
canTask,
|
|
"CAN_Task",
|
|
CAN_TASK_STACK_SIZE,
|
|
NULL,
|
|
CAN_TASK_PRIORITY,
|
|
&g_can_task_handle,
|
|
CAN_TASK_CORE
|
|
);
|
|
|
|
if (task_created != pdPASS) {
|
|
ESP_LOGE("CANDrv", "ERROR: Failed to create CAN task!");
|
|
return;
|
|
}
|
|
|
|
ESP_LOGI("CANDrv", "CAN task created successfully on Core 0");
|
|
|
|
// Auto-start if requested
|
|
if (auto_start) {
|
|
ESP_LOGI("CANDrv", "Auto-starting CAN...");
|
|
start();
|
|
} else {
|
|
ESP_LOGI("CANDrv", "CAN initially disabled");
|
|
}
|
|
}
|
|
|
|
void start() {
|
|
can_queue_event_t evt;
|
|
evt.type = CAN_EVENT_START;
|
|
xQueueSend(g_can_event_queue, &evt, 0);
|
|
}
|
|
|
|
void stop() {
|
|
can_queue_event_t evt;
|
|
evt.type = CAN_EVENT_STOP;
|
|
xQueueSend(g_can_event_queue, &evt, 0);
|
|
}
|
|
|
|
can_stats_t getStats() {
|
|
return g_can_stats;
|
|
}
|
|
|
|
driveline_t getDriveline() {
|
|
driveline_t snapshot;
|
|
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
|
snapshot = g_driveline;
|
|
xSemaphoreGive(g_data_mutex);
|
|
} else {
|
|
// Never hand back a torn read; an all-zero snapshot is honest about
|
|
// having no fresh data (engine_run_state 0 == ENGINE_RUN_OFF).
|
|
memset(&snapshot, 0, sizeof(snapshot));
|
|
}
|
|
return snapshot;
|
|
}
|
|
|
|
bool isActive() {
|
|
return g_can_active;
|
|
}
|
|
|
|
void setRawLogging(bool enabled) {
|
|
g_raw_logging = enabled;
|
|
ESP_LOGI("CANDrv", "Raw frame logging %s", enabled ? "ENABLED" : "disabled");
|
|
}
|
|
|
|
bool isRawLogging() {
|
|
return g_raw_logging;
|
|
}
|
|
|
|
void setVerboseDecode(bool enabled) {
|
|
g_verbose_decode = enabled;
|
|
ESP_LOGI("CANDrv", "Verbose decode logging %s", enabled ? "ENABLED" : "disabled");
|
|
}
|
|
|
|
void onCANToggle(lv_event_t *e) {
|
|
lv_obj_t *target = lv_event_get_target(e);
|
|
if (target == NULL) {
|
|
ESP_LOGE("CANDrv", "ERROR: CAN toggle target is NULL!");
|
|
return;
|
|
}
|
|
|
|
bool state = lv_obj_has_state(target, LV_STATE_CHECKED);
|
|
ESP_LOGI("CANDrv", "===== CAN Toggle Event =====");
|
|
ESP_LOGI("CANDrv", "CAN Toggle State: %s", state ? "ON" : "OFF");
|
|
|
|
// Save state to NVS
|
|
SettingsManager::saveCANState(state);
|
|
|
|
// Send command to CAN task
|
|
if (state) {
|
|
start();
|
|
ESP_LOGI("CANDrv", "CAN START command sent to task");
|
|
} else {
|
|
stop();
|
|
ESP_LOGI("CANDrv", "CAN STOP command sent to task");
|
|
}
|
|
}
|
|
|
|
} // namespace CANDriver
|