/** * 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 "modules/tunables.h" #include "modules/diag_probe.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; // Gearbox target gear number from 0x0BA (1..6 forward, 0 = P/R/N/none), for the // wire's target nibble. Lives here because 0x0BA and 0x1D2 arrive separately. static uint8_t g_target_gear_num = 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.alerts &= ~ALERT_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.alerts |= ALERT_GEAR_MISMATCH; g_automotive_data.valid_flags |= VALID_FLAG_ALERTS; } } /** * @brief Publish the wire gear fields (lever + target/engaged nibbles) from the * driveline pieces. Caller must hold g_data_mutex. */ static void publishGear() { uint8_t lever; switch ((gear_position_t)g_driveline.lever) { case GEAR_PARK: lever = LEVER_PARK; break; case GEAR_REVERSE: lever = LEVER_REVERSE; break; case GEAR_NEUTRAL: lever = LEVER_NEUTRAL; break; case GEAR_DRIVE: lever = (g_driveline.gear_mode == GEAR_MODE_SPORT) ? LEVER_SPORT : (g_driveline.gear_mode == GEAR_MODE_MANUAL) ? LEVER_MANUAL : LEVER_DRIVE; break; default: lever = LEVER_UNKNOWN; break; } g_automotive_data.gear_lever = lever; g_automotive_data.gear_nibbles = (uint8_t)((g_target_gear_num << 4) | (g_driveline.engaged_gear & 0x0F)); if (lever != LEVER_UNKNOWN) { g_automotive_data.valid_flags |= VALID_FLAG_GEAR_POS; } } /** * @brief Re-evaluate the alert bitmap from the current values and A's thresholds * (Tunables). The gear-mismatch bit is owned by updateGearMismatch() and * preserved here. Caller must hold g_data_mutex. */ static void updateAlerts() { link_config_t cfg = Tunables::get(); uint8_t valid = g_automotive_data.valid_flags; uint16_t a = g_automotive_data.alerts & ALERT_GEAR_MISMATCH; if ((valid & VALID_FLAG_COOLANT_TEMP) && g_automotive_data.coolant_temp >= (int16_t)(cfg.coolant_hot_c * 10)) { a |= ALERT_COOLANT_HOT; } if ((valid & VALID_FLAG_GEARBOX_TEMP) && g_automotive_data.gearbox_oil_temp >= (int16_t)(cfg.gearbox_hot_c * 10)) { a |= ALERT_GEARBOX_HOT; } if (g_driveline.gearbox_cooling == GEARBOX_COOL_STAGE1 || g_driveline.gearbox_cooling == GEARBOX_COOL_STAGE2) { a |= ALERT_GEARBOX_COOLING; } if ((valid & VALID_FLAG_BATTERY_VOLT) && g_automotive_data.battery_voltage < cfg.battery_low_x100) { a |= ALERT_BATTERY_LOW; } g_automotive_data.alerts = a; g_automotive_data.valid_flags |= VALID_FLAG_ALERTS; } /** * @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. if (decode_gear(data, dlc) != GEAR_UNKNOWN) { parsed = true; } // Break the frame into its pieces for the driveline screen, which // composes its own richer label (e.g. "D3"). Keep the bare lever 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]); g_driveline.lever = (uint8_t)g_last_lever; } if (dlc > CAN_BYTE_GEAR_ENGAGED) { g_driveline.engaged_gear = can_to_engaged_gear(data[CAN_BYTE_GEAR_ENGAGED]); } if (dlc > CAN_BYTE_GEAR_MODE) { g_driveline.gear_mode = data[CAN_BYTE_GEAR_MODE]; } publishGear(); 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); g_target_gear_num = can_to_target_gear_num(data[CAN_BYTE_GEARBOX_TARGET] & 0x0F); publishGear(); // 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); g_automotive_data.engine_rpm = g_driveline.engine_rpm; g_automotive_data.valid_flags |= VALID_FLAG_RPM; 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; } updateAlerts(); 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,,,,, * 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 emitFrameLine(const char* prefix, const twai_message_t& message) { char buf[72]; int n = snprintf(buf, sizeof(buf), "%s,%lu,%03lX,%u,%u,", prefix, (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) { emitFrameLine("CANRAW", message); } // Diagnostic replies (0x7E8..) and foreign-tester detection DiagProbe::onFrame(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) { char gearbuf[8]; gear_compose(g_automotive_data.gear_lever, gear_engaged(g_automotive_data.gear_nibbles), gearbuf, sizeof(gearbuf)); 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, gearbuf, 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 | TWAI_ALERT_TX_FAILED; 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)); // GEAR_PARK is 0, so a zeroed lever would read as "P" // before the first 0x1D2 frame — force UNKNOWN instead. g_driveline.lever = (uint8_t)GEAR_UNKNOWN; g_last_lever = GEAR_UNKNOWN; g_target_gear_num = 0; 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) { SerialLock::lock(); ESP_LOGW("CANTask", "TWAI controller has become error passive"); SerialLock::unlock(); } if (alerts_triggered & TWAI_ALERT_BUS_ERROR) { twai_status_info_t status; twai_get_status_info(&status); SerialLock::lock(); ESP_LOGW("CANTask", "Bus error detected (count: %d)", status.bus_error_count); SerialLock::unlock(); g_can_stats.parse_errors++; } if (alerts_triggered & TWAI_ALERT_TX_FAILED) { // Single-shot frame got no ACK or hit a bus error: nobody is // listening on that ID, or the bus is unhappy. Not retried. g_can_stats.tx_failures++; SerialLock::lock(); ESP_LOGW("CANTask", "TX failed (no ACK / bus error) - %lu so far", (unsigned long)g_can_stats.tx_failures); SerialLock::unlock(); } 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)); snapshot.lever = (uint8_t)GEAR_UNKNOWN; // 0 would mean GEAR_PARK } return snapshot; } bool isActive() { return g_can_active; } bool transmit(uint32_t id, const uint8_t* data, uint8_t len) { if (!g_can_active || data == NULL || len > 8 || id > 0x7FF) { g_can_stats.tx_failures++; return false; } twai_message_t m; memset(&m, 0, sizeof(m)); m.identifier = id; m.extd = 0; m.ss = 1; // single shot: never retransmit on error m.data_length_code = len; memcpy(m.data, data, len); esp_err_t r = twai_transmit(&m, pdMS_TO_TICKS(20)); if (r != ESP_OK) { g_can_stats.tx_failures++; ESP_LOGW("CANDrv", "twai_transmit(0x%03lX) failed: %s", (unsigned long)id, esp_err_to_name(r)); return false; } g_can_stats.messages_transmitted++; emitFrameLine("CANTX", m); return true; } 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