418 lines
15 KiB
C++
418 lines
15 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 "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)
|
|
|
|
// ============================================================================
|
|
// 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
|
|
|
|
// ============================================================================
|
|
// PRIVATE FUNCTIONS
|
|
// ============================================================================
|
|
|
|
/**
|
|
* @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;
|
|
}
|
|
|
|
switch (id) {
|
|
case CAN_ID_COOLANT_TEMP:
|
|
// Engine coolant temperature (byte 0)
|
|
if (message.data_length_code > CAN_BYTE_COOLANT_TEMP) {
|
|
g_automotive_data.coolant_temp = can_to_temperature(data[CAN_BYTE_COOLANT_TEMP]);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_COOLANT_TEMP;
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_ENGINE_OIL_TEMP:
|
|
// Engine oil temperature (byte 7)
|
|
if (message.data_length_code > CAN_BYTE_ENGINE_OIL_TEMP) {
|
|
g_automotive_data.engine_oil_temp = can_to_temperature(data[CAN_BYTE_ENGINE_OIL_TEMP]);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_ENGINE_TEMP;
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_GEARBOX_TEMP:
|
|
// Gearbox oil temperature (byte 3)
|
|
if (message.data_length_code > CAN_BYTE_GEARBOX_TEMP) {
|
|
g_automotive_data.gearbox_oil_temp = can_to_temperature(data[CAN_BYTE_GEARBOX_TEMP]);
|
|
g_automotive_data.valid_flags |= VALID_FLAG_GEARBOX_TEMP;
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_GEARBOX_DATA:
|
|
// Gearbox position and current gear (bytes 0 and 1)
|
|
if (message.data_length_code > CAN_BYTE_CURRENT_GEAR) {
|
|
// Byte 0: Gear position (P/R/N/D/S/M)
|
|
g_automotive_data.gear_position = data[CAN_BYTE_GEAR_POS];
|
|
|
|
// Byte 1: Current gear number (1-8) - stored for future use
|
|
// Could be displayed alongside position for manual modes
|
|
|
|
g_automotive_data.valid_flags |= VALID_FLAG_GEAR_POS;
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
case CAN_ID_BATTERY_VOLTAGE:
|
|
// Battery voltage (bytes 0-1, 16-bit value)
|
|
if (message.data_length_code > CAN_BYTE_BATTERY_VOLT_L) {
|
|
// Combine high and low bytes (assuming big-endian)
|
|
uint16_t raw_voltage = (data[CAN_BYTE_BATTERY_VOLT_H] << 8) | data[CAN_BYTE_BATTERY_VOLT_L];
|
|
|
|
// Convert to internal format (0.01V units)
|
|
// Assuming CAN sends in 0.1V units, multiply by 10
|
|
g_automotive_data.battery_voltage = raw_voltage * 10;
|
|
|
|
g_automotive_data.valid_flags |= VALID_FLAG_BATTERY_VOLT;
|
|
parsed = true;
|
|
}
|
|
break;
|
|
|
|
default:
|
|
// Unknown CAN ID - ignore
|
|
break;
|
|
}
|
|
|
|
xSemaphoreGive(g_data_mutex);
|
|
|
|
return parsed;
|
|
}
|
|
|
|
/**
|
|
* @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();
|
|
|
|
// 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++;
|
|
|
|
// DETAILED LOGGING (TEMPORARY FOR DEBUGGING)
|
|
// Log EVERY parsed message with actual values
|
|
if (xSemaphoreTake(g_data_mutex, pdMS_TO_TICKS(10)) == pdTRUE) {
|
|
ESP_LOGI("CANDrv", "✓ RX CAN ID=0x%X → Coolant:%d.%d°C, Oil:%d.%d°C, Gearbox:%d.%d°C, Batt:%d.%02dV, Gear:%d [%d/%d]",
|
|
message.identifier,
|
|
g_automotive_data.coolant_temp / 10, abs(g_automotive_data.coolant_temp % 10),
|
|
g_automotive_data.engine_oil_temp / 10, abs(g_automotive_data.engine_oil_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_automotive_data.gear_position,
|
|
g_can_stats.messages_parsed,
|
|
g_can_stats.messages_received);
|
|
xSemaphoreGive(g_data_mutex);
|
|
}
|
|
} else {
|
|
// Unknown message ID - log ALL unknown messages for debugging
|
|
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, LISTEN_ONLY)",
|
|
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));
|
|
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;
|
|
}
|
|
|
|
bool isActive() {
|
|
return g_can_active;
|
|
}
|
|
|
|
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
|