[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7E9Q4YGX7VFP41GGCQF9DYA":3,"skill-same:01M7E9Q4YGX7VFP41GGCQF9DYA":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":31,"commitSha":32,"skillDirectory":33,"forksCount":14,"repositoryHtmlUrl":34,"repositoryHomepageUrl":34,"ownerHtmlUrl":35,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":36,"install":37,"resources":50},"01M7E9Q4YGX7VFP41GGCQF9DYA","automotive-ecu-systems",null,"Automotive Ecu Systems expertise. Covers 8 topics: Bcm Body Control, Bms Battery Management, Domain Controller Integration, Ivi Infotainment Systems, Pdu Power Distribution.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fautomotive\u002Fautomotive-ecu-systems\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: automotive-ecu-systems\ndescription: >\n  Automotive Ecu Systems expertise. Covers 8 topics: Bcm Body Control, Bms Battery Management, Domain Controller Integration, Ivi Infotainment Systems, Pdu Power Distribution.\ntags: [automotive, automotive-ecu-systems]\nsource: \"https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\"\nsource_repository: \"pangzhenying2025\u002Fhermes-automotive-skills\"\nsource_path: \"skills\u002Fautomotive-ecu-systems\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n# Automotive Ecu Systems\n\n## Bcm Body Control\n\n# BCM (Body Control Module) - Comfort and Convenience Systems\n\n## Overview\nThe Body Control Unit (BCM) manages exterior\u002Finterior lighting, HVAC integration, door locks, windows, wipers, keyless entry, anti-theft systems, and power distribution across body electronics. This skill covers production-ready BCM development with LIN bus mastering.\n\n## Core Responsibilities\n\n### 1. Exterior\u002FInterior Lighting Control\n```c\n\u002F* bcm_lighting_control.c - Comprehensive lighting management *\u002F\n#include \"bcm_lighting_control.h\"\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n\n#define PWM_FREQUENCY_HZ 1000\n#define DIM_STEP_PERCENT 5\n#define AUTO_HEADLIGHT_THRESHOLD_LUX 100\n\ntypedef enum {\n    LIGHT_MODE_OFF = 0,\n    LIGHT_MODE_PARKING,\n    LIGHT_MODE_DAYTIME_RUNNING,\n    LIGHT_MODE_LOW_BEAM,\n    LIGHT_MODE_HIGH_BEAM,\n    LIGHT_MODE_AUTO\n} HeadlightMode_t;\n\ntypedef struct {\n    bool left_turn_signal_active;\n    bool right_turn_signal_active;\n    bool hazard_active;\n    uint8_t turn_signal_phase;  \u002F* 0-100% for flashing *\u002F\n    uint32_t last_toggle_ms;\n} TurnSignalState_t;\n\ntypedef struct {\n    HeadlightMode_t mode;\n    uint8_t brightness_percent;\n    bool high_beam_assist_active;\n    bool adaptive_lighting_active;\n} HeadlightState_t;\n\nstatic TurnSignalState_t g_turn_signals = {0};\nstatic HeadlightState_t g_headlights = {0};\n\nvoid BCM_Lighting_Init(void) {\n    \u002F* Initialize PWM channels for LED control *\u002F\n    PWM_Init(PWM_CHANNEL_LEFT_HEADLIGHT, PWM_FREQUENCY_HZ);\n    PWM_Init(PWM_CHANNEL_RIGHT_HEADLIGHT, PWM_FREQUENCY_HZ);\n    PWM_Init(PWM_CHANNEL_DOME_LIGHT, PWM_FREQUENCY_HZ);\n    PWM_Init(PWM_CHANNEL_AMBIENT_LIGHT, PWM_FREQUENCY_HZ);\n\n    \u002F* Set initial state *\u002F\n    g_headlights.mode = LIGHT_MODE_OFF;\n    g_headlights.brightness_percent = 100;\n\n    \u002F* Load saved settings from EEPROM *\u002F\n    NvM_ReadBlock(NVM_BLOCK_LIGHTING_SETTINGS, &g_headlights);\n}\n\nvoid BCM_TurnSignals_Update(void) {\n    uint32_t current_time = GetSystemTime_ms();\n\n    \u002F* Flash at 1 Hz (500ms on, 500ms off) *\u002F\n    if ((current_time - g_turn_signals.last_toggle_ms) > 500) {\n        g_turn_signals.turn_signal_phase = (g_turn_signals.turn_signal_phase == 0) ? 100 : 0;\n        g_turn_signals.last_toggle_ms = current_time;\n    }\n\n    \u002F* Left turn signal *\u002F\n    if (g_turn_signals.left_turn_signal_active || g_turn_signals.hazard_active) {\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_FRONT, g_turn_signals.turn_signal_phase);\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_REAR, g_turn_signals.turn_signal_phase);\n    } else {\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_FRONT, 0);\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_REAR, 0);\n    }\n\n    \u002F* Right turn signal *\u002F\n    if (g_turn_signals.right_turn_signal_active || g_turn_signals.hazard_active) {\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_FRONT, g_turn_signals.turn_signal_phase);\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_REAR, g_turn_signals.turn_signal_phase);\n    } else {\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_FRONT, 0);\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_REAR, 0);\n    }\n}\n\nvoid BCM_Headlights_Update(void) {\n    uint16_t ambient_light_lux = BCM_LightSensor_Read();\n\n    switch (g_headlights.mode) {\n        case LIGHT_MODE_OFF:\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 0);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 0);\n            break;\n\n        case LIGHT_MODE_PARKING:\n            \u002F* 20% brightness for parking lights *\u002F\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 20);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 20);\n            break;\n\n        case LIGHT_MODE_DAYTIME_RUNNING:\n            \u002F* 50% brightness for DRL *\u002F\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 50);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 50);\n            break;\n\n        case LIGHT_MODE_LOW_BEAM:\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, g_headlights.brightness_percent);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, g_headlights.brightness_percent);\n            break;\n\n        case LIGHT_MODE_HIGH_BEAM:\n            \u002F* Full brightness for high beam *\u002F\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 100);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 100);\n            PWM_SetDutyCycle(PWM_CHANNEL_HIGH_BEAM, 100);\n            break;\n\n        case LIGHT_MODE_AUTO:\n            \u002F* Automatic headlight control based on ambient light *\u002F\n            if (ambient_light_lux \u003C AUTO_HEADLIGHT_THRESHOLD_LUX) {\n                \u002F* Dark: enable low beams *\u002F\n                g_headlights.mode = LIGHT_MODE_LOW_BEAM;\n            } else {\n                \u002F* Bright: enable DRL only *\u002F\n                g_headlights.mode = LIGHT_MODE_DAYTIME_RUNNING;\n            }\n            break;\n    }\n\n    \u002F* High beam assist: automatically switch to low beam when oncoming traffic detected *\u002F\n    if (g_headlights.high_beam_assist_active && g_headlights.mode == LIGHT_MODE_HIGH_BEAM) {\n        bool oncoming_detected = ADAS_Camera_DetectOncomingVehicle();\n        if (oncoming_detected) {\n            g_headlights.mode = LIGHT_MODE_LOW_BEAM;\n        }\n    }\n}\n\n\u002F* Interior dome light with fade-in\u002Ffade-out *\u002F\nvoid BCM_DomeLight_SetState(bool on, bool fade) {\n    static uint8_t current_brightness = 0;\n    uint8_t target_brightness = on ? 100 : 0;\n\n    if (fade) {\n        \u002F* Fade gradually *\u002F\n        while (current_brightness != target_brightness) {\n            if (current_brightness \u003C target_brightness) {\n                current_brightness += DIM_STEP_PERCENT;\n            } else {\n                current_brightness -= DIM_STEP_PERCENT;\n            }\n\n            PWM_SetDutyCycle(PWM_CHANNEL_DOME_LIGHT, current_brightness);\n            OsTask_Sleep(50);  \u002F* 50ms steps for smooth fade *\u002F\n        }\n    } else {\n        \u002F* Immediate switch *\u002F\n        current_brightness = target_brightness;\n        PWM_SetDutyCycle(PWM_CHANNEL_DOME_LIGHT, current_brightness);\n    }\n}\n```\n\n### 2. Door Lock\u002FUnlock and Keyless Entry\n```c\n\u002F* bcm_door_control.c - Central locking and keyless entry *\u002F\n#include \"bcm_door_control.h\"\n\n#define KEYFOB_UNLOCK_TIMEOUT_MS 3000\n#define AUTO_LOCK_SPEED_THRESHOLD_KPH 10\n#define PASSIVE_ENTRY_RANGE_M 2.0\n\ntypedef enum {\n    DOOR_FL = 0,\n    DOOR_FR,\n    DOOR_RL,\n    DOOR_RR,\n    DOOR_TRUNK,\n    DOOR_COUNT\n} DoorID_t;\n\ntypedef struct {\n    bool locked;\n    bool open;\n    uint32_t last_lock_timestamp_ms;\n} DoorState_t;\n\ntypedef struct {\n    uint32_t keyfob_id;\n    int8_t rssi_dbm;\n    float distance_m;  \u002F* Estimated from RSSI *\u002F\n    bool authenticated;\n} KeyFobState_t;\n\nstatic DoorState_t g_doors[DOOR_COUNT] = {0};\nstatic KeyFobState_t g_active_keyfob = {0};\n\nvoid BCM_DoorControl_Init(void) {\n    \u002F* Initialize door lock actuators *\u002F\n    for (int i = 0; i \u003C DOOR_COUNT; i++) {\n        GPIO_ConfigOutput(DOOR_LOCK_PINS[i]);\n        g_doors[i].locked = true;\n    }\n\n    \u002F* Initialize door open sensors (switches) *\u002F\n    for (int i = 0; i \u003C DOOR_COUNT; i++) {\n        GPIO_ConfigInput(DOOR_SWITCH_PINS[i], GPIO_PULL_UP);\n    }\n\n    \u002F* Initialize BLE for passive keyless entry *\u002F\n    BLE_Init();\n    BLE_StartAdvertising(\"VehicleKey\");\n}\n\nvoid BCM_DoorControl_LockAll(void) {\n    for (int i = 0; i \u003C DOOR_COUNT; i++) {\n        if (!g_doors[i].locked) {\n            \u002F* Activate lock actuator (pulse for 500ms) *\u002F\n            GPIO_Set(DOOR_LOCK_PINS[i], true);\n            OsTask_Sleep(500);\n            GPIO_Set(DOOR_LOCK_PINS[i], false);\n\n            g_doors[i].locked = true;\n            g_doors[i].last_lock_timestamp_ms = GetSystemTime_ms();\n        }\n    }\n\n    \u002F* Chirp horn once to confirm lock *\u002F\n    BCM_Horn_Chirp(1);\n\n    \u002F* Flash turn signals once *\u002F\n    BCM_TurnSignals_Flash(1);\n}\n\nvoid BCM_DoorControl_UnlockAll(void) {\n    \u002F* Unlock driver door first (common in luxury vehicles) *\u002F\n    BCM_DoorControl_UnlockSingle(DOOR_FL);\n\n    \u002F* Wait 2 seconds, then unlock all if button pressed again *\u002F\n    uint32_t start_time = GetSystemTime_ms();\n    while ((GetSystemTime_ms() - start_time) \u003C 2000) {\n        if (KeyFob_ButtonPressed(KEYFOB_BUTTON_UNLOCK)) {\n            \u002F* Second press: unlock all doors *\u002F\n            for (int i = 0; i \u003C DOOR_COUNT; i++) {\n                BCM_DoorControl_UnlockSingle((DoorID_t)i);\n            }\n            break;\n        }\n        OsTask_Sleep(10);\n    }\n\n    \u002F* Flash turn signals twice *\u002F\n    BCM_TurnSignals_Flash(2);\n}\n\nvoid BCM_DoorControl_UnlockSingle(DoorID_t door) {\n    if (g_doors[door].locked) {\n        \u002F* Activate unlock actuator *\u002F\n        GPIO_Set(DOOR_UNLOCK_PINS[door], true);\n        OsTask_Sleep(500);\n        GPIO_Set(DOOR_UNLOCK_PINS[door], false);\n\n        g_doors[door].locked = false;\n    }\n}\n\n\u002F* Passive keyless entry: unlock when approaching with authenticated key *\u002F\nvoid BCM_PassiveEntry_Update(void) {\n    \u002F* Scan for BLE key fobs *\u002F\n    if (BLE_ScanForDevice(g_active_keyfob.keyfob_id)) {\n        g_active_keyfob.rssi_dbm = BLE_GetRSSI();\n\n        \u002F* Estimate distance from RSSI (simplified model) *\u002F\n        g_active_keyfob.distance_m = pow(10, (-59 - g_active_keyfob.rssi_dbm) \u002F (10 * 2.0));\n\n        \u002F* Authenticate key fob *\u002F\n        if (!g_active_keyfob.authenticated) {\n            uint8_t challenge[16];\n            uint8_t response[16];\n\n            BCM_Crypto_GenerateChallenge(challenge);\n            BLE_SendChallenge(challenge);\n\n            if (BLE_ReceiveResponse(response) &&\n                BCM_Crypto_VerifyResponse(challenge, response)) {\n                g_active_keyfob.authenticated = true;\n            }\n        }\n\n        \u002F* Unlock if authenticated and within range *\u002F\n        if (g_active_keyfob.authenticated &&\n            g_active_keyfob.distance_m \u003C PASSIVE_ENTRY_RANGE_M) {\n            \u002F* Check if door handle touched (capacitive sensor) *\u002F\n            if (GPIO_Read(DOOR_HANDLE_SENSOR_FL)) {\n                BCM_DoorControl_UnlockSingle(DOOR_FL);\n            }\n        }\n    }\n}\n\n\u002F* Auto-lock when driving *\u002F\nvoid BCM_AutoLock_Update(void) {\n    uint16_t vehicle_speed = VCU_GetVehicleSpeed_kph();\n\n    if (vehicle_speed > AUTO_LOCK_SPEED_THRESHOLD_KPH) {\n        \u002F* Vehicle is moving: auto-lock all doors *\u002F\n        bool any_unlocked = false;\n        for (int i = 0; i \u003C DOOR_COUNT; i++) {\n            if (!g_doors[i].locked) {\n                any_unlocked = true;\n                break;\n            }\n        }\n\n        if (any_unlocked) {\n            BCM_DoorControl_LockAll();\n        }\n    }\n}\n```\n\n### 3. Window Control with Anti-Pinch\n```c\n\u002F* bcm_window_control.c - Power window management with anti-pinch *\u002F\n#include \"bcm_window_control.h\"\n\n#define WINDOW_FL 0\n#define WINDOW_FR 1\n#define WINDOW_RL 2\n#define WINDOW_RR 3\n#define WINDOW_COUNT 4\n\n#define ANTI_PINCH_FORCE_THRESHOLD_N 100\n#define WINDOW_POSITION_SAMPLES 10\n\ntypedef enum {\n    WINDOW_STATE_STOPPED = 0,\n    WINDOW_STATE_MOVING_UP,\n    WINDOW_STATE_MOVING_DOWN,\n    WINDOW_STATE_PINCH_DETECTED\n} WindowState_t;\n\ntypedef struct {\n    WindowState_t state;\n    uint8_t position_percent;  \u002F* 0=closed, 100=fully open *\u002F\n    uint16_t motor_current_ma;\n    bool one_touch_up_active;\n    bool one_touch_down_active;\n} WindowControl_t;\n\nstatic WindowControl_t g_windows[WINDOW_COUNT] = {0};\n\nvoid BCM_WindowControl_Init(void) {\n    \u002F* Initialize window motor drivers (H-bridge) *\u002F\n    for (int i = 0; i \u003C WINDOW_COUNT; i++) {\n        GPIO_ConfigOutput(WINDOW_MOTOR_UP_PINS[i]);\n        GPIO_ConfigOutput(WINDOW_MOTOR_DOWN_PINS[i]);\n    }\n\n    \u002F* Initialize window position sensors (Hall effect) *\u002F\n    for (int i = 0; i \u003C WINDOW_COUNT; i++) {\n        ADC_ConfigChannel(WINDOW_POSITION_ADC_CHANNELS[i]);\n    }\n\n    \u002F* Initialize current sensing for anti-pinch *\u002F\n    for (int i = 0; i \u003C WINDOW_COUNT; i++) {\n        ADC_ConfigChannel(WINDOW_CURRENT_ADC_CHANNELS[i]);\n    }\n}\n\nvoid BCM_Window_MoveUp(uint8_t window_id) {\n    if (window_id >= WINDOW_COUNT) return;\n\n    WindowControl_t* window = &g_windows[window_id];\n\n    if (window->position_percent == 0) {\n        return;  \u002F* Already fully closed *\u002F\n    }\n\n    \u002F* Activate motor upward *\u002F\n    GPIO_Set(WINDOW_MOTOR_UP_PINS[window_id], true);\n    GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], false);\n\n    window->state = WINDOW_STATE_MOVING_UP;\n}\n\nvoid BCM_Window_MoveDown(uint8_t window_id) {\n    if (window_id >= WINDOW_COUNT) return;\n\n    WindowControl_t* window = &g_windows[window_id];\n\n    if (window->position_percent == 100) {\n        return;  \u002F* Already fully open *\u002F\n    }\n\n    \u002F* Activate motor downward *\u002F\n    GPIO_Set(WINDOW_MOTOR_UP_PINS[window_id], false);\n    GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], true);\n\n    window->state = WINDOW_STATE_MOVING_DOWN;\n}\n\nvoid BCM_Window_Stop(uint8_t window_id) {\n    if (window_id >= WINDOW_COUNT) return;\n\n    \u002F* Stop motor *\u002F\n    GPIO_Set(WINDOW_MOTOR_UP_PINS[window_id], false);\n    GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], false);\n\n    g_windows[window_id].state = WINDOW_STATE_STOPPED;\n}\n\n\u002F* Anti-pinch detection: monitor motor current during closing *\u002F\nvoid BCM_Window_AntiPinchUpdate(uint8_t window_id) {\n    WindowControl_t* window = &g_windows[window_id];\n\n    if (window->state != WINDOW_STATE_MOVING_UP) {\n        return;  \u002F* Only check during closing *\u002F\n    }\n\n    \u002F* Read motor current *\u002F\n    uint16_t adc_value = ADC_Read(WINDOW_CURRENT_ADC_CHANNELS[window_id]);\n    window->motor_current_ma = (adc_value * 5000) \u002F 4096;  \u002F* 12-bit ADC, 0-5A range *\u002F\n\n    \u002F* Detect excessive current (indicates obstruction) *\u002F\n    if (window->motor_current_ma > ANTI_PINCH_FORCE_THRESHOLD_N) {\n        \u002F* Pinch detected: reverse window *\u002F\n        window->state = WINDOW_STATE_PINCH_DETECTED;\n\n        BCM_Window_Stop(window_id);\n        OsTask_Sleep(100);\n\n        \u002F* Move down slightly to release obstruction *\u002F\n        GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], true);\n        OsTask_Sleep(500);\n        GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], false);\n\n        window->state = WINDOW_STATE_STOPPED;\n\n        \u002F* Log event *\u002F\n        DTC_SetFault(DTC_WINDOW_ANTI_PINCH_TRIGGERED + window_id);\n    }\n}\n\n\u002F* One-touch up\u002Fdown *\u002F\nvoid BCM_Window_OneTouchUp(uint8_t window_id) {\n    g_windows[window_id].one_touch_up_active = true;\n\n    while (g_windows[window_id].position_percent > 0 &&\n           g_windows[window_id].state != WINDOW_STATE_PINCH_DETECTED) {\n        BCM_Window_MoveUp(window_id);\n        BCM_Window_UpdatePosition(window_id);\n        BCM_Window_AntiPinchUpdate(window_id);\n        OsTask_Sleep(10);\n    }\n\n    BCM_Window_Stop(window_id);\n    g_windows[window_id].one_touch_up_active = false;\n}\n```\n\n### 4. LIN Bus Mastering (Door Modules)\n```c\n\u002F* bcm_lin_master.c - LIN bus control for door modules *\u002F\n#include \"bcm_lin_master.h\"\n\n#define LIN_BAUDRATE 19200\n#define LIN_BREAK_DURATION_US 750\n#define LIN_FRAME_TIMEOUT_MS 50\n\ntypedef struct {\n    uint8_t frame_id;\n    uint8_t data[8];\n    uint8_t length;\n    uint8_t checksum;\n} LINFrame_t;\n\n\u002F* Door module addresses *\u002F\n#define LIN_DOOR_FL_ID 0x01\n#define LIN_DOOR_FR_ID 0x02\n#define LIN_DOOR_RL_ID 0x03\n#define LIN_DOOR_RR_ID 0x04\n\nvoid BCM_LIN_Init(void) {\n    \u002F* Configure UART for LIN *\u002F\n    UART_Init(LIN_UART_PORT, LIN_BAUDRATE);\n    UART_SetMode(LIN_UART_PORT, UART_MODE_LIN);\n}\n\nvoid BCM_LIN_SendBreak(void) {\n    \u002F* Generate LIN break field (dominant for 750µs) *\u002F\n    GPIO_Set(LIN_TX_PIN, false);\n    usleep(LIN_BREAK_DURATION_US);\n    GPIO_Set(LIN_TX_PIN, true);\n}\n\nbool BCM_LIN_SendFrame(const LINFrame_t* frame) {\n    \u002F* Send break + sync byte + frame ID *\u002F\n    BCM_LIN_SendBreak();\n    UART_WriteByte(LIN_UART_PORT, 0x55);  \u002F* Sync byte *\u002F\n    UART_WriteByte(LIN_UART_PORT, frame->frame_id);\n\n    \u002F* Send data *\u002F\n    for (int i = 0; i \u003C frame->length; i++) {\n        UART_WriteByte(LIN_UART_PORT, frame->data[i]);\n    }\n\n    \u002F* Send checksum *\u002F\n    UART_WriteByte(LIN_UART_PORT, frame->checksum);\n\n    return true;\n}\n\n\u002F* Command door module to lock\u002Funlock *\u002F\nvoid BCM_LIN_DoorLockCommand(uint8_t door_module_id, bool lock) {\n    LINFrame_t frame;\n    frame.frame_id = door_module_id;\n    frame.length = 2;\n    frame.data[0] = lock ? 0x01 : 0x02;  \u002F* 0x01=lock, 0x02=unlock *\u002F\n    frame.data[1] = 0x00;\n    frame.checksum = BCM_LIN_CalculateChecksum(&frame);\n\n    BCM_LIN_SendFrame(&frame);\n}\n\n\u002F* Read door status from LIN module *\u002F\nbool BCM_LIN_ReadDoorStatus(uint8_t door_module_id, bool* door_open, bool* window_position) {\n    LINFrame_t request;\n    request.frame_id = door_module_id | 0x40;  \u002F* Read request *\u002F\n    request.length = 0;\n    request.checksum = BCM_LIN_CalculateChecksum(&request);\n\n    BCM_LIN_SendFrame(&request);\n\n    \u002F* Wait for response *\u002F\n    LINFrame_t response;\n    if (BCM_LIN_ReceiveFrame(&response, LIN_FRAME_TIMEOUT_MS)) {\n        *door_open = (response.data[0] & 0x01) != 0;\n        *window_position = response.data[1];\n        return true;\n    }\n\n    return false;\n}\n```\n\n## BCM CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: BCM VCU IVI\n\n\u002F* BCM Lighting Status *\u002F\nBO_ 512 BCM_LightingStatus: 8 BCM\n SG_ BCM_HeadlightMode : 0|8@1+ (0,0) [0|5] \"\"  IVI\n SG_ BCM_LeftTurnSignal : 8|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_RightTurnSignal : 9|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_HazardActive : 10|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_HighBeamActive : 11|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_BrakeLight : 12|1@1+ (0,0) [0|1] \"\"  VCU\n\n\u002F* BCM Door Status *\u002F\nBO_ 513 BCM_DoorStatus: 8 BCM\n SG_ BCM_DoorLocked_FL : 0|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorLocked_FR : 1|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorLocked_RL : 2|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorLocked_RR : 3|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorOpen_FL : 8|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_DoorOpen_FR : 9|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_DoorOpen_RL : 10|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_DoorOpen_RR : 11|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_TrunkOpen : 12|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n\nVAL_ 512 BCM_HeadlightMode 0 \"Off\" 1 \"Parking\" 2 \"DRL\" 3 \"LowBeam\" 4 \"HighBeam\" 5 \"Auto\";\n```\n\n## References\n- SAE J1850: Class B Data Communication Network Interface\n- ISO 17987: Local Interconnect Network (LIN) Protocol\n- IEC 60529: IP Rating (Ingress Protection)\n- ECE R48: Installation of lighting devices\n\n## Common Issues\n- LIN bus communication errors due to incorrect timing\n- Anti-pinch false triggers from motor current spikes\n- Keyless entry authentication failures\n- Door lock actuators jamming in cold weather\n- PWM flicker at low brightness levels\n\n---\n\n## Bms Battery Management\n\n# BMS (Battery Management System) for EVs\u002FHEVs\n\n## Overview\nThe Battery Management System (BMS) monitors cell voltages, estimates SOC\u002FSOH, performs cell balancing, manages thermal systems, controls contactors, and ensures ISO 26262 ASIL-D safety compliance for high-voltage battery packs.\n\n## Core Responsibilities\n\n### 1. Cell Voltage Monitoring\n```c\n\u002F* bms_cell_monitoring.c - Multi-cell voltage acquisition *\u002F\n#include \"bms_cell_monitoring.h\"\n\n#define MAX_CELLS_PER_MODULE 12\n#define MAX_MODULES 10\n#define TOTAL_CELLS (MAX_CELLS_PER_MODULE * MAX_MODULES)\n\n#define CELL_OVERVOLTAGE_MV 4200\n#define CELL_UNDERVOLTAGE_MV 2500\n\ntypedef struct {\n    uint16_t voltage_mv;\n    int16_t temperature_c_x10;  \u002F* 0.1°C resolution *\u002F\n    bool balancing_active;\n} CellData_t;\n\ntypedef struct {\n    CellData_t cells[MAX_CELLS_PER_MODULE];\n    uint8_t module_id;\n    int16_t module_temperature_c_x10;\n    bool communication_ok;\n} ModuleData_t;\n\nstatic ModuleData_t g_modules[MAX_MODULES];\n\n\u002F* LTC6811 Battery Monitor IC interface *\u002F\nvoid BMS_CellMonitoring_Init(void) {\n    \u002F* Initialize SPI for LTC6811 daisy chain *\u002F\n    SPI_Init(SPI_BMS, 1000000);  \u002F* 1 MHz *\u002F\n\n    \u002F* Wake up all LTC6811 ICs *\u002F\n    BMS_LTC6811_Wakeup();\n\n    \u002F* Configure cell measurement mode *\u002F\n    uint8_t config[6] = {\n        0xF8,  \u002F* GPIO pull-downs off, REFON=1 *\u002F\n        0x00,  \u002F* Discharge switches off *\u002F\n        0x00, 0x00, 0x00, 0x00\n    };\n    BMS_LTC6811_WriteConfig(config);\n}\n\nvoid BMS_CellMonitoring_Update(void) {\n    \u002F* Start cell voltage conversion (all cells, all modules) *\u002F\n    BMS_LTC6811_StartCellConversion(ADC_MODE_NORMAL, ADC_FILTER_7KHZ);\n\n    \u002F* Wait for conversion (2.3ms for normal mode) *\u002F\n    OsTask_Sleep(3);\n\n    \u002F* Read cell voltages from all modules *\u002F\n    for (uint8_t module = 0; module \u003C MAX_MODULES; module++) {\n        uint16_t cell_voltages[MAX_CELLS_PER_MODULE];\n\n        if (BMS_LTC6811_ReadCellVoltages(module, cell_voltages)) {\n            for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n                g_modules[module].cells[cell].voltage_mv = cell_voltages[cell] \u002F 10;  \u002F* 100µV resolution *\u002F\n\n                \u002F* Check overvoltage\u002Fundervoltage *\u002F\n                if (cell_voltages[cell] > CELL_OVERVOLTAGE_MV) {\n                    BMS_Fault_SetOvervoltage(module, cell);\n                }\n                if (cell_voltages[cell] \u003C CELL_UNDERVOLTAGE_MV) {\n                    BMS_Fault_SetUndervoltage(module, cell);\n                }\n            }\n            g_modules[module].communication_ok = true;\n        } else {\n            g_modules[module].communication_ok = false;\n            BMS_Fault_SetCommunicationLoss(module);\n        }\n    }\n\n    \u002F* Read temperatures via GPIO (NTC thermistors) *\u002F\n    BMS_LTC6811_ReadGPIO();\n}\n\nuint16_t BMS_GetMinCellVoltage_mV(void) {\n    uint16_t min_voltage = 0xFFFF;\n\n    for (uint8_t mod = 0; mod \u003C MAX_MODULES; mod++) {\n        for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n            if (g_modules[mod].cells[cell].voltage_mv \u003C min_voltage) {\n                min_voltage = g_modules[mod].cells[cell].voltage_mv;\n            }\n        }\n    }\n\n    return min_voltage;\n}\n\nuint16_t BMS_GetMaxCellVoltage_mV(void) {\n    uint16_t max_voltage = 0;\n\n    for (uint8_t mod = 0; mod \u003C MAX_MODULES; mod++) {\n        for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n            if (g_modules[mod].cells[cell].voltage_mv > max_voltage) {\n                max_voltage = g_modules[mod].cells[cell].voltage_mv;\n            }\n        }\n    }\n\n    return max_voltage;\n}\n```\n\n### 2. SOC\u002FSOH Estimation (Coulomb Counting + Kalman Filter)\n```c\n\u002F* bms_soc_estimation.c - State of Charge \u002F State of Health algorithms *\u002F\n#include \"bms_soc_estimation.h\"\n#include \u003Cmath.h>\n\n#define BATTERY_CAPACITY_AH 75.0\n#define COULOMB_EFFICIENCY 0.98  \u002F* Charge efficiency *\u002F\n\ntypedef struct {\n    float soc_percent;           \u002F* 0-100% *\u002F\n    float soh_percent;           \u002F* 0-100%, degrades over time *\u002F\n    float coulomb_count_ah;      \u002F* Accumulated amp-hours *\u002F\n    float ocv_voltage_v;         \u002F* Open circuit voltage *\u002F\n    uint32_t cycle_count;        \u002F* Full charge\u002Fdischarge cycles *\u002F\n    float remaining_capacity_ah;\n} SOCState_t;\n\nstatic SOCState_t g_soc_state = {\n    .soc_percent = 50.0,\n    .soh_percent = 100.0,\n    .coulomb_count_ah = BATTERY_CAPACITY_AH \u002F 2.0,\n    .remaining_capacity_ah = BATTERY_CAPACITY_AH\n};\n\n\u002F* OCV-SOC lookup table (Open Circuit Voltage to SOC mapping) *\u002F\nstatic const struct {\n    float voltage_v;\n    float soc_percent;\n} OCV_SOC_TABLE[] = {\n    {3.27, 0.0},\n    {3.61, 10.0},\n    {3.69, 20.0},\n    {3.71, 30.0},\n    {3.73, 40.0},\n    {3.77, 50.0},\n    {3.83, 60.0},\n    {3.92, 70.0},\n    {4.01, 80.0},\n    {4.08, 90.0},\n    {4.20, 100.0}\n};\n\nvoid BMS_SOC_Init(void) {\n    \u002F* Load last known SOC from EEPROM *\u002F\n    NvM_ReadBlock(NVM_BLOCK_SOC_STATE, &g_soc_state);\n\n    \u002F* Initialize Kalman filter for SOC estimation *\u002F\n    BMS_KalmanFilter_Init();\n}\n\nvoid BMS_SOC_Update(float current_a, uint32_t delta_time_ms) {\n    \u002F* Coulomb counting: integrate current over time *\u002F\n    float delta_time_h = delta_time_ms \u002F 3600000.0;\n    float delta_ah = current_a * delta_time_h;\n\n    \u002F* Positive current = discharge, negative = charge *\u002F\n    if (current_a > 0) {\n        g_soc_state.coulomb_count_ah -= delta_ah;\n    } else {\n        g_soc_state.coulomb_count_ah -= delta_ah * COULOMB_EFFICIENCY;\n    }\n\n    \u002F* Clamp to capacity limits *\u002F\n    if (g_soc_state.coulomb_count_ah \u003C 0) {\n        g_soc_state.coulomb_count_ah = 0;\n    }\n    if (g_soc_state.coulomb_count_ah > g_soc_state.remaining_capacity_ah) {\n        g_soc_state.coulomb_count_ah = g_soc_state.remaining_capacity_ah;\n    }\n\n    \u002F* Calculate SOC from coulomb count *\u002F\n    g_soc_state.soc_percent = (g_soc_state.coulomb_count_ah \u002F\n                                g_soc_state.remaining_capacity_ah) * 100.0;\n\n    \u002F* Kalman filter fusion with OCV-based SOC (when current near zero) *\u002F\n    if (fabs(current_a) \u003C 1.0) {  \u002F* Low current: use OCV *\u002F\n        float pack_voltage_v = BMS_GetPackVoltage() \u002F 1000.0;\n        float avg_cell_voltage_v = pack_voltage_v \u002F TOTAL_CELLS;\n\n        float ocv_soc = BMS_SOC_LookupOCV(avg_cell_voltage_v);\n\n        \u002F* Kalman filter update *\u002F\n        g_soc_state.soc_percent = BMS_KalmanFilter_Update(\n            g_soc_state.soc_percent,\n            ocv_soc);\n    }\n\n    \u002F* Persist SOC every 1% change *\u002F\n    static float last_saved_soc = 0;\n    if (fabs(g_soc_state.soc_percent - last_saved_soc) > 1.0) {\n        NvM_WriteBlock(NVM_BLOCK_SOC_STATE, &g_soc_state);\n        last_saved_soc = g_soc_state.soc_percent;\n    }\n}\n\nfloat BMS_SOC_LookupOCV(float voltage_v) {\n    \u002F* Linear interpolation in OCV-SOC table *\u002F\n    for (int i = 0; i \u003C (sizeof(OCV_SOC_TABLE) \u002F sizeof(OCV_SOC_TABLE[0])) - 1; i++) {\n        if (voltage_v >= OCV_SOC_TABLE[i].voltage_v &&\n            voltage_v \u003C= OCV_SOC_TABLE[i+1].voltage_v) {\n\n            float v_range = OCV_SOC_TABLE[i+1].voltage_v - OCV_SOC_TABLE[i].voltage_v;\n            float soc_range = OCV_SOC_TABLE[i+1].soc_percent - OCV_SOC_TABLE[i].soc_percent;\n            float v_delta = voltage_v - OCV_SOC_TABLE[i].voltage_v;\n\n            return OCV_SOC_TABLE[i].soc_percent + (v_delta \u002F v_range) * soc_range;\n        }\n    }\n\n    return 50.0;  \u002F* Default fallback *\u002F\n}\n\n\u002F* SOH estimation based on capacity fade *\u002F\nvoid BMS_SOH_Update(void) {\n    \u002F* Detect full charge cycle: SOC goes 100% -> 0% -> 100% *\u002F\n    static bool charging = false;\n    static bool discharged = false;\n\n    if (g_soc_state.soc_percent > 99.0 && !charging) {\n        charging = true;\n\n        if (discharged) {\n            \u002F* Full cycle completed *\u002F\n            g_soc_state.cycle_count++;\n\n            \u002F* Estimate capacity fade: 80% at 1000 cycles (linear model) *\u002F\n            g_soc_state.remaining_capacity_ah =\n                BATTERY_CAPACITY_AH * (1.0 - (g_soc_state.cycle_count \u002F 5000.0));\n\n            g_soc_state.soh_percent = (g_soc_state.remaining_capacity_ah \u002F\n                                       BATTERY_CAPACITY_AH) * 100.0;\n\n            discharged = false;\n        }\n    }\n\n    if (g_soc_state.soc_percent \u003C 5.0) {\n        discharged = true;\n        charging = false;\n    }\n}\n```\n\n### 3. Cell Balancing (Active\u002FPassive)\n```c\n\u002F* bms_cell_balancing.c - Cell voltage equalization *\u002F\n#include \"bms_cell_balancing.h\"\n\n#define BALANCE_THRESHOLD_MV 10  \u002F* Start balancing if cell delta > 10mV *\u002F\n#define BALANCE_TARGET_MV 5      \u002F* Stop when delta \u003C 5mV *\u002F\n#define MAX_BALANCE_CURRENT_MA 200\n\nvoid BMS_CellBalancing_Update(void) {\n    uint16_t min_voltage = BMS_GetMinCellVoltage_mV();\n    uint16_t max_voltage = BMS_GetMaxCellVoltage_mV();\n\n    if ((max_voltage - min_voltage) \u003C BALANCE_THRESHOLD_MV) {\n        \u002F* Cells well balanced: disable all balancing *\u002F\n        BMS_CellBalancing_DisableAll();\n        return;\n    }\n\n    \u002F* Passive balancing: discharge high cells through resistors *\u002F\n    for (uint8_t mod = 0; mod \u003C MAX_MODULES; mod++) {\n        uint16_t balance_mask = 0;\n\n        for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n            uint16_t cell_voltage = g_modules[mod].cells[cell].voltage_mv;\n\n            \u002F* Balance if above minimum + threshold *\u002F\n            if (cell_voltage > (min_voltage + BALANCE_TARGET_MV)) {\n                balance_mask |= (1 \u003C\u003C cell);\n                g_modules[mod].cells[cell].balancing_active = true;\n            } else {\n                g_modules[mod].cells[cell].balancing_active = false;\n            }\n        }\n\n        \u002F* Write balance control register to LTC6811 *\u002F\n        BMS_LTC6811_SetBalancing(mod, balance_mask);\n    }\n}\n```\n\n### 4. Contactor Control (Safety-Critical)\n```c\n\u002F* bms_contactor_control.c - High-voltage contactor sequencing *\u002F\n#include \"bms_contactor_control.h\"\n\n#define PRECHARGE_TIMEOUT_MS 5000\n#define PRECHARGE_THRESHOLD_PERCENT 95\n\ntypedef enum {\n    CONTACTOR_STATE_OPEN = 0,\n    CONTACTOR_STATE_PRECHARGING,\n    CONTACTOR_STATE_CLOSED,\n    CONTACTOR_STATE_FAULT\n} ContactorState_t;\n\nstatic ContactorState_t g_contactor_state = CONTACTOR_STATE_OPEN;\n\nvoid BMS_Contactor_Close(void) {\n    \u002F* Safety checks before closing *\u002F\n    if (!BMS_Safety_PreCloseCheck()) {\n        g_contactor_state = CONTACTOR_STATE_FAULT;\n        return;\n    }\n\n    \u002F* Step 1: Close negative contactor *\u002F\n    GPIO_Set(GPIO_CONTACTOR_NEGATIVE, true);\n    OsTask_Sleep(50);\n\n    \u002F* Step 2: Precharge positive side through resistor *\u002F\n    g_contactor_state = CONTACTOR_STATE_PRECHARGING;\n    GPIO_Set(GPIO_PRECHARGE_RELAY, true);\n\n    uint32_t start_time = GetSystemTime_ms();\n    uint16_t pack_voltage_v = BMS_GetPackVoltage();\n    uint16_t link_voltage_v = ADC_ReadHVLinkVoltage();\n\n    \u002F* Wait for DC link to charge to 95% of pack voltage *\u002F\n    while ((GetSystemTime_ms() - start_time) \u003C PRECHARGE_TIMEOUT_MS) {\n        link_voltage_v = ADC_ReadHVLinkVoltage();\n\n        if (link_voltage_v > (pack_voltage_v * PRECHARGE_THRESHOLD_PERCENT \u002F 100)) {\n            break;  \u002F* Precharge complete *\u002F\n        }\n\n        OsTask_Sleep(10);\n    }\n\n    if (link_voltage_v \u003C (pack_voltage_v * PRECHARGE_THRESHOLD_PERCENT \u002F 100)) {\n        \u002F* Precharge timeout: fault *\u002F\n        GPIO_Set(GPIO_PRECHARGE_RELAY, false);\n        GPIO_Set(GPIO_CONTACTOR_NEGATIVE, false);\n        g_contactor_state = CONTACTOR_STATE_FAULT;\n        DTC_SetFault(DTC_PRECHARGE_TIMEOUT);\n        return;\n    }\n\n    \u002F* Step 3: Close positive contactor *\u002F\n    GPIO_Set(GPIO_CONTACTOR_POSITIVE, true);\n    OsTask_Sleep(50);\n\n    \u002F* Step 4: Open precharge relay *\u002F\n    GPIO_Set(GPIO_PRECHARGE_RELAY, false);\n\n    g_contactor_state = CONTACTOR_STATE_CLOSED;\n}\n\nvoid BMS_Contactor_Open(void) {\n    \u002F* Open positive first, then negative *\u002F\n    GPIO_Set(GPIO_CONTACTOR_POSITIVE, false);\n    OsTask_Sleep(50);\n    GPIO_Set(GPIO_CONTACTOR_NEGATIVE, false);\n\n    g_contactor_state = CONTACTOR_STATE_OPEN;\n}\n```\n\n## BMS CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: BMS VCU MCU\n\n\u002F* BMS Battery Status *\u002F\nBO_ 768 BMS_BatteryStatus: 8 BMS\n SG_ BMS_PackVoltage_V : 0|16@1+ (0.1,0) [0|600] \"V\"  VCU,MCU\n SG_ BMS_PackCurrent_A : 16|16@1- (0.1,-320) [-320|320] \"A\"  VCU,MCU\n SG_ BMS_SOC_percent : 32|8@1+ (0.5,0) [0|100] \"%\"  VCU,MCU\n SG_ BMS_SOH_percent : 40|8@1+ (0.5,0) [0|100] \"%\"  VCU\n SG_ BMS_MaxCellTemp_C : 48|8@1+ (1,-40) [-40|100] \"C\"  VCU,MCU\n SG_ BMS_ContactorState : 56|8@1+ (0,0) [0|3] \"\"  VCU,MCU\n\nVAL_ 768 BMS_ContactorState 0 \"Open\" 1 \"Precharging\" 2 \"Closed\" 3 \"Fault\";\n```\n\n## ISO 26262 ASIL-D Safety Mechanisms\n- Dual voltage measurement paths with cross-checking\n- Watchdog timer for contactor control\n- Cell voltage plausibility checks\n- Safe state transition on fault detection\n\n## References\n- ISO 26262: Functional Safety for Road Vehicles\n- UL 2580: Batteries for Use in Electric Vehicles\n- IEC 62133: Safety Requirements for Portable Sealed Secondary Cells\n- SAE J2464: EV Battery Systems Crashworthiness\n\n## Common Issues\n- SOC drift from coulomb counting errors\n- Cell balancing inefficiency at low SOC\n- Precharge relay welding from inrush current\n- Temperature sensor failures affecting thermal management\n\n---\n\n## Domain Controller Integration\n\n# Domain Controller Architecture - Next-Gen Vehicle E\u002FE Architecture\n\n## Overview\nDomain Controller architecture centralizes ECU functions into fewer, more powerful computing platforms: Chassis Domain, Powertrain Domain, Body\u002FComfort Domain, ADAS Domain, with cross-domain communication via service-oriented architecture (SOA) and resource sharing.\n\n## Domain Controller Concepts\n\n### 1. Chassis Domain Controller\n```c\n\u002F* chassis_domain_controller.c - Integrated chassis functions *\u002F\n#include \"chassis_domain.h\"\n\n\u002F* Consolidated functions: ESC, ABS, TCS, EPS, ADAS braking *\u002F\ntypedef struct {\n    \u002F* Electronic Stability Control *\u002F\n    bool esc_active;\n    float yaw_rate_deg_s;\n    float lateral_acceleration_g;\n\n    \u002F* Anti-lock Braking System *\u002F\n    uint8_t wheel_speeds_kph[4];\n    bool abs_active[4];\n\n    \u002F* Traction Control System *\u002F\n    bool tcs_active;\n    uint16_t tcs_torque_reduction_nm;\n\n    \u002F* Electric Power Steering *\u002F\n    float steering_angle_deg;\n    float steering_torque_nm;\n\n    \u002F* ADAS Braking Interface *\u002F\n    bool adas_brake_request;\n    float adas_decel_mps2;\n} ChassisDomain_t;\n\nstatic ChassisDomain_t g_chassis = {0};\n\nvoid ChassisDomain_Main_10ms(void) {\n    \u002F* Read sensors from CAN\u002FFlexRay *\u002F\n    ChassisDomain_ReadSensors();\n\n    \u002F* ESC control loop *\u002F\n    ChassisDomain_ESC_Update();\n\n    \u002F* ABS control per wheel *\u002F\n    for (int i = 0; i \u003C 4; i++) {\n        ChassisDomain_ABS_UpdateWheel(i);\n    }\n\n    \u002F* TCS integration with powertrain domain *\u002F\n    if (g_chassis.tcs_active) {\n        \u002F* Send torque reduction request to powertrain domain *\u002F\n        SOMEIP_SendRequest(POWERTRAIN_DOMAIN_SERVICE_ID,\n                           METHOD_REDUCE_TORQUE,\n                           &g_chassis.tcs_torque_reduction_nm,\n                           sizeof(uint16_t));\n    }\n\n    \u002F* ADAS brake arbitration *\u002F\n    if (g_chassis.adas_brake_request) {\n        ChassisDomain_ADAS_BrakeControl();\n    }\n\n    \u002F* Publish chassis status to Ethernet backbone *\u002F\n    ChassisDomain_PublishStatus();\n}\n\nvoid ChassisDomain_ESC_Update(void) {\n    \u002F* Read IMU (gyroscope + accelerometer) *\u002F\n    float yaw_rate = IMU_GetYawRate();\n    float lat_accel = IMU_GetLateralAcceleration();\n\n    \u002F* Calculate desired yaw rate from steering angle *\u002F\n    float desired_yaw = (g_chassis.steering_angle_deg * VCU_GetVehicleSpeed_kph()) \u002F 15.0;\n\n    \u002F* ESC intervention if yaw error exceeds threshold *\u002F\n    float yaw_error = desired_yaw - yaw_rate;\n\n    if (fabs(yaw_error) > 5.0) {\n        g_chassis.esc_active = true;\n\n        \u002F* Apply differential braking to correct yaw *\u002F\n        if (yaw_error > 0) {\n            \u002F* Understeer: brake inside rear wheel *\u002F\n            ChassisDomain_ApplyBrake(WHEEL_RL, 30);\n        } else {\n            \u002F* Oversteer: brake outside front wheel *\u002F\n            ChassisDomain_ApplyBrake(WHEEL_FL, 30);\n        }\n\n        \u002F* Reduce engine torque *\u002F\n        SOMEIP_SendRequest(POWERTRAIN_DOMAIN_SERVICE_ID,\n                           METHOD_REDUCE_TORQUE,\n                           &(uint16_t){100}, 2);\n    } else {\n        g_chassis.esc_active = false;\n    }\n}\n```\n\n### 2. Powertrain Domain Controller\n```c\n\u002F* powertrain_domain_controller.c - EV powertrain integration *\u002F\n#include \"powertrain_domain.h\"\n\n\u002F* Consolidated: VCU, BMS, MCU functions *\u002F\ntypedef struct {\n    \u002F* Motor control *\u002F\n    int16_t motor_torque_cmd_nm;\n    uint16_t motor_speed_rpm;\n    float motor_temperature_c;\n\n    \u002F* Battery management *\u002F\n    float battery_soc_percent;\n    uint16_t battery_voltage_v;\n    float battery_current_a;\n\n    \u002F* Thermal management *\u002F\n    bool cooling_pump_active;\n    uint8_t radiator_fan_speed_percent;\n} PowertrainDomain_t;\n\nstatic PowertrainDomain_t g_powertrain = {0};\n\nvoid PowertrainDomain_Main_10ms(void) {\n    \u002F* Motor control *\u002F\n    PowertrainDomain_MotorControl();\n\n    \u002F* Battery management *\u002F\n    PowertrainDomain_BMS_Update();\n\n    \u002F* Thermal management *\u002F\n    PowertrainDomain_ThermalControl();\n\n    \u002F* Service-oriented communication *\u002F\n    PowertrainDomain_HandleSOARequests();\n}\n\nvoid PowertrainDomain_HandleSOARequests(void) {\n    \u002F* Handle SOME\u002FIP service requests from other domains *\u002F\n    SOMEIP_Request_t req;\n\n    if (SOMEIP_ReceiveRequest(&req)) {\n        switch (req.method_id) {\n            case METHOD_REDUCE_TORQUE: {\n                uint16_t reduction_nm = *(uint16_t*)req.payload;\n                g_powertrain.motor_torque_cmd_nm -= reduction_nm;\n\n                \u002F* Send response *\u002F\n                SOMEIP_SendResponse(&req, RESPONSE_OK, NULL, 0);\n                break;\n            }\n\n            case METHOD_GET_SOC: {\n                uint8_t soc = (uint8_t)g_powertrain.battery_soc_percent;\n                SOMEIP_SendResponse(&req, RESPONSE_OK, &soc, 1);\n                break;\n            }\n\n            case METHOD_SET_CHARGING_LIMIT: {\n                uint8_t limit_percent = *(uint8_t*)req.payload;\n                PowertrainDomain_SetChargingLimit(limit_percent);\n                SOMEIP_SendResponse(&req, RESPONSE_OK, NULL, 0);\n                break;\n            }\n        }\n    }\n}\n```\n\n### 3. Body\u002FComfort Domain Controller\n```c\n\u002F* body_domain_controller.c - Comfort and convenience functions *\u002F\n#include \"body_domain.h\"\n\n\u002F* Consolidated: BCM, HVAC, seats, ambient lighting *\u002F\ntypedef struct {\n    \u002F* Climate control *\u002F\n    float cabin_temperature_c;\n    uint8_t hvac_fan_speed;\n    bool ac_compressor_active;\n\n    \u002F* Lighting *\u002F\n    HeadlightMode_t headlight_mode;\n    uint8_t ambient_light_brightness;\n\n    \u002F* Seats *\u002F\n    uint8_t driver_seat_heating_level;\n    uint8_t passenger_seat_heating_level;\n} BodyDomain_t;\n\nstatic BodyDomain_t g_body = {0};\n\nvoid BodyDomain_Main_50ms(void) {\n    \u002F* Climate control *\u002F\n    BodyDomain_HVAC_Update();\n\n    \u002F* Lighting control *\u002F\n    BodyDomain_Lighting_Update();\n\n    \u002F* Seat control *\u002F\n    BodyDomain_Seats_Update();\n\n    \u002F* User preference synchronization (cloud) *\u002F\n    BodyDomain_SyncUserPreferences();\n}\n\nvoid BodyDomain_SyncUserPreferences(void) {\n    \u002F* Load user profile from cloud (via TCU) *\u002F\n    UserProfile_t profile;\n\n    if (Cloud_GetUserProfile(g_authenticated_user_id, &profile)) {\n        \u002F* Apply preferences *\u002F\n        g_body.driver_seat_heating_level = profile.seat_heat_pref;\n        g_body.ambient_light_brightness = profile.ambient_light_pref;\n        g_body.headlight_mode = profile.headlight_mode_pref;\n\n        \u002F* Adjust seat position (via LIN to seat ECU) *\u002F\n        LIN_SendSeatPosition(profile.seat_position);\n    }\n}\n```\n\n### 4. ADAS Domain Controller\n```c\n\u002F* adas_domain_controller.c - Perception, planning, control *\u002F\n#include \"adas_domain.h\"\n\n\u002F* Consolidated: camera, radar, lidar fusion, path planning *\u002F\ntypedef struct {\n    \u002F* Perception *\u002F\n    Object_t detected_objects[32];\n    uint8_t object_count;\n\n    \u002F* Localization *\u002F\n    float ego_position_x;\n    float ego_position_y;\n    float ego_heading_deg;\n\n    \u002F* Path planning *\u002F\n    Trajectory_t planned_path;\n\n    \u002F* Control *\u002F\n    float target_acceleration_mps2;\n    float target_steering_angle_deg;\n} ADASDomain_t;\n\nstatic ADASDomain_t g_adas = {0};\n\nvoid ADASDomain_Main_20ms(void) {\n    \u002F* Sensor fusion *\u002F\n    ADASDomain_SensorFusion();\n\n    \u002F* Object detection and tracking *\u002F\n    ADASDomain_ObjectTracking();\n\n    \u002F* Path planning *\u002F\n    ADASDomain_PathPlanning();\n\n    \u002F* Send control commands to chassis\u002Fpowertrain domains *\u002F\n    ADASDomain_SendControlCommands();\n}\n\nvoid ADASDomain_SendControlCommands(void) {\n    \u002F* Request steering via chassis domain *\u002F\n    SOMEIP_SendRequest(CHASSIS_DOMAIN_SERVICE_ID,\n                       METHOD_SET_STEERING_ANGLE,\n                       &g_adas.target_steering_angle_deg,\n                       sizeof(float));\n\n    \u002F* Request acceleration via powertrain domain *\u002F\n    if (g_adas.target_acceleration_mps2 > 0) {\n        \u002F* Acceleration *\u002F\n        int16_t torque_nm = (int16_t)(g_adas.target_acceleration_mps2 * 50);\n        SOMEIP_SendRequest(POWERTRAIN_DOMAIN_SERVICE_ID,\n                           METHOD_SET_TORQUE,\n                           &torque_nm,\n                           sizeof(int16_t));\n    } else {\n        \u002F* Braking *\u002F\n        float decel_mps2 = -g_adas.target_acceleration_mps2;\n        SOMEIP_SendRequest(CHASSIS_DOMAIN_SERVICE_ID,\n                           METHOD_APPLY_BRAKE,\n                           &decel_mps2,\n                           sizeof(float));\n    }\n}\n```\n\n## Service-Oriented Architecture (SOME\u002FIP)\n\n### SOME\u002FIP Service Definition (ARXML)\n```xml\n\u003C!-- adas_services.arxml -->\n\u003CAUTOSAR>\n  \u003CAR-PACKAGES>\n    \u003CAR-PACKAGE>\n      \u003CSHORT-NAME>ADAS_Services\u003C\u002FSHORT-NAME>\n      \u003CELEMENTS>\n        \u003CSOMEIP-SERVICE-INTERFACE>\n          \u003CSHORT-NAME>ADAS_Control_Service\u003C\u002FSHORT-NAME>\n          \u003CSERVICE-INTERFACE-ID>0x1234\u003C\u002FSERVICE-INTERFACE-ID>\n          \u003CMAJOR-VERSION>1\u003C\u002FMAJOR-VERSION>\n          \u003CMINOR-VERSION>0\u003C\u002FMINOR-VERSION>\n\n          \u003CMETHODS>\n            \u003CSOMEIP-METHOD>\n              \u003CSHORT-NAME>SetSteeringAngle\u003C\u002FSHORT-NAME>\n              \u003CMETHOD-ID>0x0001\u003C\u002FMETHOD-ID>\n              \u003CCALL-SEMANTIC>REQUEST-RESPONSE\u003C\u002FCALL-SEMANTIC>\n            \u003C\u002FSOMEIP-METHOD>\n            \u003CSOMEIP-METHOD>\n              \u003CSHORT-NAME>ApplyBrake\u003C\u002FSHORT-NAME>\n              \u003CMETHOD-ID>0x0002\u003C\u002FMETHOD-ID>\n              \u003CCALL-SEMANTIC>REQUEST-RESPONSE\u003C\u002FCALL-SEMANTIC>\n            \u003C\u002FSOMEIP-METHOD>\n          \u003C\u002FMETHODS>\n\n          \u003CEVENTS>\n            \u003CSOMEIP-EVENT>\n              \u003CSHORT-NAME>ObjectDetected\u003C\u002FSHORT-NAME>\n              \u003CEVENT-ID>0x8001\u003C\u002FEVENT-ID>\n            \u003C\u002FSOMEIP-EVENT>\n          \u003C\u002FEVENTS>\n        \u003C\u002FSOMEIP-SERVICE-INTERFACE>\n      \u003C\u002FELEMENTS>\n    \u003C\u002FAR-PACKAGE>\n  \u003C\u002FAR-PACKAGES>\n\u003C\u002FAUTOSAR>\n```\n\n### Cross-Domain Communication Example\n```c\n\u002F* domain_communication.c - SOME\u002FIP client\u002Fserver example *\u002F\n#include \"someip.h\"\n\n\u002F* Client: ADAS domain requests torque from powertrain domain *\u002F\nvoid ADAS_RequestTorque(int16_t torque_nm) {\n    SOMEIP_Message_t msg;\n    msg.service_id = POWERTRAIN_SERVICE_ID;\n    msg.method_id = METHOD_SET_TORQUE;\n    msg.client_id = ADAS_DOMAIN_CLIENT_ID;\n    msg.session_id = GetNextSessionID();\n    msg.payload_length = sizeof(int16_t);\n    memcpy(msg.payload, &torque_nm, sizeof(int16_t));\n\n    SOMEIP_Send(&msg);\n\n    \u002F* Wait for response *\u002F\n    SOMEIP_Message_t response;\n    if (SOMEIP_WaitForResponse(&response, 100)) {\n        if (response.return_code == SOMEIP_RETURN_OK) {\n            \u002F* Request acknowledged *\u002F\n        }\n    }\n}\n\n\u002F* Server: Powertrain domain handles torque request *\u002F\nvoid Powertrain_SOMEIP_Handler(const SOMEIP_Message_t* request) {\n    if (request->method_id == METHOD_SET_TORQUE) {\n        int16_t requested_torque = *(int16_t*)request->payload;\n\n        \u002F* Apply safety limits *\u002F\n        if (requested_torque > MAX_TORQUE_NM) {\n            requested_torque = MAX_TORQUE_NM;\n        }\n\n        \u002F* Set motor torque *\u002F\n        VCU_SetMotorTorque(requested_torque);\n\n        \u002F* Send response *\u002F\n        SOMEIP_Message_t response;\n        response.service_id = request->service_id;\n        response.method_id = request->method_id;\n        response.client_id = request->client_id;\n        response.session_id = request->session_id;\n        response.return_code = SOMEIP_RETURN_OK;\n        response.payload_length = 0;\n\n        SOMEIP_Send(&response);\n    }\n}\n```\n\n## Resource Sharing and Timing\n\n### Hypervisor-Based Domain Isolation\n```c\n\u002F* hypervisor_config.h - QNX Hypervisor partition configuration *\u002F\n\n\u002F* Chassis Domain - Guest VM #1 *\u002F\n#define CHASSIS_DOMAIN_RAM_BASE 0x80000000\n#define CHASSIS_DOMAIN_RAM_SIZE 512MB\n#define CHASSIS_DOMAIN_CPU_MASK 0x03  \u002F* CPU 0-1 *\u002F\n#define CHASSIS_DOMAIN_PRIORITY CRITICAL\n\n\u002F* Powertrain Domain - Guest VM #2 *\u002F\n#define POWERTRAIN_DOMAIN_RAM_BASE 0xA0000000\n#define POWERTRAIN_DOMAIN_RAM_SIZE 512MB\n#define POWERTRAIN_DOMAIN_CPU_MASK 0x0C  \u002F* CPU 2-3 *\u002F\n#define POWERTRAIN_DOMAIN_PRIORITY CRITICAL\n\n\u002F* Body Domain - Guest VM #3 *\u002F\n#define BODY_DOMAIN_RAM_BASE 0xC0000000\n#define BODY_DOMAIN_RAM_SIZE 256MB\n#define BODY_DOMAIN_CPU_MASK 0x10  \u002F* CPU 4 *\u002F\n#define BODY_DOMAIN_PRIORITY NORMAL\n\n\u002F* ADAS Domain - Guest VM #4 (highest compute) *\u002F\n#define ADAS_DOMAIN_RAM_BASE 0xD0000000\n#define ADAS_DOMAIN_RAM_SIZE 2GB\n#define ADAS_DOMAIN_CPU_MASK 0xE0  \u002F* CPU 5-7 *\u002F\n#define ADAS_DOMAIN_PRIORITY HIGH\n```\n\n## Benefits of Domain Controller Architecture\n- **Reduced wiring harness complexity**: Fewer ECUs = less copper\n- **Centralized computing**: More powerful processors, better performance\n- **OTA update efficiency**: Update entire domain instead of individual ECUs\n- **Cost reduction**: Consolidation reduces hardware costs\n- **Scalability**: Easier to add features without new ECUs\n\n## References\n- AUTOSAR Adaptive Platform R22-11\n- SOME\u002FIP Protocol Specification v1.3\n- QNX Hypervisor for Automotive\n- ISO 21434: Road Vehicles - Cybersecurity Engineering\n- ASAM OpenX: Service-Oriented Communication\n\n## Common Issues\n- Inter-domain latency exceeding real-time requirements\n- Resource contention between domains on shared CPU cores\n- SOME\u002FIP service discovery failures\n- Hypervisor overhead impacting deterministic timing\n- Cross-domain debugging complexity\n\n---\n\n## Ivi Infotainment Systems\n\n# IVI (In-Vehicle Infotainment) Systems\n\n## Overview\nThe In-Vehicle Infotainment (IVI) system manages navigation, multimedia, connectivity (CarPlay\u002FAndroid Auto), voice assistant, HMI frameworks (Qt\u002FFlutter), and runs on Android Automotive OS, QNX, or Linux platforms.\n\n## Platform Architectures\n\n### 1. Android Automotive OS (AAOS)\n```java\n\u002F\u002F VehicleHalService.java - Android Automotive HAL integration\npackage com.example.ivi;\n\nimport android.car.Car;\nimport android.car.VehiclePropertyIds;\nimport android.car.hardware.CarPropertyValue;\nimport android.car.hardware.property.CarPropertyManager;\n\npublic class VehicleHalService {\n    private CarPropertyManager mCarPropertyManager;\n\n    public void init(Context context) {\n        Car car = Car.createCar(context);\n        mCarPropertyManager = (CarPropertyManager) car.getCarManager(Car.PROPERTY_SERVICE);\n\n        \u002F\u002F Subscribe to vehicle speed updates\n        mCarPropertyManager.registerCallback(\n            new CarPropertyManager.CarPropertyEventCallback() {\n                @Override\n                public void onChangeEvent(CarPropertyValue value) {\n                    if (value.getPropertyId() == VehiclePropertyIds.PERF_VEHICLE_SPEED) {\n                        float speedMs = (Float) value.getValue();\n                        updateSpeedUI(speedMs * 3.6f);  \u002F\u002F Convert to km\u002Fh\n                    }\n                }\n\n                @Override\n                public void onErrorEvent(int propId, int zone) {\n                    Log.e(\"VehicleHal\", \"Property error: \" + propId);\n                }\n            },\n            VehiclePropertyIds.PERF_VEHICLE_SPEED,\n            CarPropertyManager.SENSOR_RATE_NORMAL);\n    }\n\n    public void setHvacTemperature(float tempCelsius) {\n        mCarPropertyManager.setFloatProperty(\n            VehiclePropertyIds.HVAC_TEMPERATURE_SET,\n            VehicleAreaType.VEHICLE_AREA_TYPE_SEAT,\n            tempCelsius);\n    }\n}\n```\n\n### 2. QNX-Based IVI\n```c\n\u002F* qnx_ivi_service.c - QNX CAR platform integration *\u002F\n#include \u003Cqnxcar\u002Fcarcontrol.h>\n#include \u003Cscreen\u002Fscreen.h>\n\nvoid IVI_QNX_Init(void) {\n    \u002F* Initialize QNX CAR framework *\u002F\n    car_control_t *control = car_control_create();\n\n    \u002F* Register for CAN message callbacks *\u002F\n    car_control_set_can_callback(control, IVI_CAN_MessageHandler);\n\n    \u002F* Initialize Screen Graphics Subsystem *\u002F\n    screen_context_t screen_ctx;\n    screen_create_context(&screen_ctx, SCREEN_APPLICATION_CONTEXT);\n\n    \u002F* Create display window *\u002F\n    screen_window_t window;\n    screen_create_window(&window, screen_ctx);\n    screen_set_window_property_iv(window, SCREEN_PROPERTY_SIZE, (int[]){1920, 1080});\n}\n\nvoid IVI_CAN_MessageHandler(car_can_message_t *msg) {\n    if (msg->id == 0x100) {  \u002F* VCU Motor Command *\u002F\n        uint16_t torque = (msg->data[0] \u003C\u003C 8) | msg->data[1];\n        IVI_UpdatePowerMeter(torque);\n    }\n}\n```\n\n### 3. Navigation Integration (HERE\u002FTomTom)\n```kotlin\n\u002F\u002F NavigationService.kt - HERE SDK integration\npackage com.example.ivi.navigation\n\nimport com.here.sdk.core.GeoCoordinates\nimport com.here.sdk.routing.CalculateRouteCallback\nimport com.here.sdk.routing.Route\nimport com.here.sdk.routing.RoutingEngine\n\nclass NavigationService {\n    private lateinit var routingEngine: RoutingEngine\n\n    fun initialize() {\n        routingEngine = RoutingEngine()\n    }\n\n    fun calculateRoute(\n        origin: GeoCoordinates,\n        destination: GeoCoordinates,\n        callback: (Route?) -> Unit\n    ) {\n        val waypoints = listOf(\n            Waypoint(origin),\n            Waypoint(destination)\n        )\n\n        val carOptions = CarOptions().apply {\n            routeOptions.alternatives = 3\n            avoidanceOptions.avoidTollRoads = false\n            optimizationMode = OptimizationMode.FASTEST\n        }\n\n        routingEngine.calculateRoute(waypoints, carOptions) { routingError, routes ->\n            if (routingError == null && routes?.isNotEmpty() == true) {\n                callback(routes[0])\n            } else {\n                callback(null)\n            }\n        }\n    }\n}\n```\n\n### 4. CarPlay\u002FAndroid Auto Integration\n```java\n\u002F\u002F AndroidAutoService.java - Android Auto projection\npackage com.example.ivi.projection;\n\nimport android.content.Intent;\nimport com.google.android.apps.auto.sdk.CarActivity;\n\npublic class AndroidAutoService extends CarActivity {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n\n        \u002F\u002F Start Android Auto projection\n        Intent intent = new Intent(\"com.google.android.gms.car.PROJECTION_SERVICE\");\n        startService(intent);\n    }\n\n    @Override\n    public void onCarConnectionStateChanged(int state) {\n        if (state == CarConnection.STATE_CONNECTED) {\n            \u002F\u002F Phone connected: mirror Android Auto UI\n            enableProjectionMode();\n        }\n    }\n}\n```\n\n### 5. Voice Assistant Integration (Alexa\u002FGoogle Assistant)\n```python\n# voice_assistant.py - Voice command handler\nimport speech_recognition as sr\nimport pyttsx3\n\nclass VoiceAssistant:\n    def __init__(self):\n        self.recognizer = sr.Recognizer()\n        self.tts = pyttsx3.init()\n\n    def listen_for_command(self):\n        with sr.Microphone() as source:\n            print(\"Listening...\")\n            audio = self.recognizer.listen(source)\n\n        try:\n            command = self.recognizer.recognize_google(audio)\n            self.process_command(command)\n        except sr.UnknownValueError:\n            self.speak(\"Sorry, I didn't understand that.\")\n\n    def process_command(self, command):\n        if \"navigate to\" in command.lower():\n            destination = command.lower().replace(\"navigate to\", \"\").strip()\n            self.navigate(destination)\n        elif \"set temperature\" in command.lower():\n            temp = int(command.split()[-1])\n            self.set_hvac_temperature(temp)\n\n    def speak(self, text):\n        self.tts.say(text)\n        self.tts.runAndWait()\n```\n\n## HMI Framework (Qt QML)\n```qml\n\u002F* DashboardView.qml - Main instrument cluster *\u002F\nimport QtQuick 2.15\nimport QtQuick.Controls 2.15\n\nRectangle {\n    width: 1920\n    height: 720\n\n    \u002F\u002F Speedometer\n    Item {\n        id: speedometer\n        x: 100\n        y: 100\n\n        Canvas {\n            id: speedArc\n            width: 400\n            height: 400\n\n            onPaint: {\n                var ctx = getContext(\"2d\");\n                ctx.clearRect(0, 0, width, height);\n\n                \u002F\u002F Draw arc for speed (0-240 km\u002Fh)\n                ctx.beginPath();\n                ctx.arc(200, 200, 150, 0.75 * Math.PI, (0.75 + 1.5 * (vehicleSpeed \u002F 240)) * Math.PI);\n                ctx.lineWidth = 20;\n                ctx.strokeStyle = \"#00FF00\";\n                ctx.stroke();\n            }\n\n            Connections {\n                target: vehicleData\n                onSpeedChanged: speedArc.requestPaint()\n            }\n        }\n\n        Text {\n            text: vehicleData.speed + \" km\u002Fh\"\n            font.pixelSize: 48\n            color: \"white\"\n            anchors.centerIn: parent\n        }\n    }\n\n    \u002F\u002F Battery SOC gauge\n    Rectangle {\n        x: 600\n        y: 100\n        width: 300\n        height: 50\n        color: \"transparent\"\n        border.color: \"white\"\n\n        Rectangle {\n            width: parent.width * (vehicleData.batterySOC \u002F 100)\n            height: parent.height\n            color: vehicleData.batterySOC > 20 ? \"#00FF00\" : \"#FF0000\"\n        }\n\n        Text {\n            text: vehicleData.batterySOC + \"%\"\n            color: \"white\"\n            anchors.centerIn: parent\n        }\n    }\n}\n```\n\n## IVI CAN Interface (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: IVI VCU BCM BMS\n\n\u002F* IVI User Commands *\u002F\nBO_ 1024 IVI_UserCommand: 8 IVI\n SG_ IVI_DriveMode : 0|8@1+ (0,0) [0|3] \"\"  VCU\n SG_ IVI_ACTempSet : 8|8@1+ (0.5,10) [10|35] \"C\"  BCM\n SG_ IVI_ACFanSpeed : 16|8@1+ (0,0) [0|7] \"\"  BCM\n\nVAL_ 1024 IVI_DriveMode 0 \"Eco\" 1 \"Normal\" 2 \"Sport\" 3 \"Custom\";\n```\n\n## References\n- Android Automotive OS Developer Guide\n- QNX CAR Platform API Reference\n- HERE SDK for Automotive\n- CarPlay App Programming Guide\n- W3C Automotive Web Platform Specification\n\n## Common Issues\n- High CPU usage from rendering complex 3D gauges\n- CarPlay\u002FAndroid Auto disconnection during navigation\n- Voice recognition accuracy in noisy cabin\n- Slow boot time (> 10 seconds)\n\n---\n\n## Pdu Power Distribution\n\n# PDU (Power Distribution Unit) - High\u002FLow Voltage Power Management\n\n## Overview\nThe Power Distribution Unit (PDU) manages high-voltage DC\u002FDC converters, low-voltage power distribution, fuse\u002Frelay control, load shedding, power budgeting, battery voltage monitoring, and wake-up source management.\n\n## Core Responsibilities\n\n### 1. High-Voltage DC\u002FDC Converter\n```c\n\u002F* pdu_hv_dcdc.c - High-voltage to 12V DC\u002FDC conversion *\u002F\n#include \"pdu_hv_dcdc.h\"\n\n#define HV_INPUT_MIN_V 200\n#define HV_INPUT_MAX_V 450\n#define LV_OUTPUT_TARGET_V 14.0\n#define MAX_OUTPUT_CURRENT_A 150\n\ntypedef struct {\n    uint16_t hv_input_voltage_v;\n    float lv_output_voltage_v;\n    float output_current_a;\n    float efficiency_percent;\n    bool enabled;\n    bool fault_active;\n} DCDC_State_t;\n\nstatic DCDC_State_t g_dcdc = {0};\n\nvoid PDU_DCDC_Init(void) {\n    \u002F* Configure PWM for DC\u002FDC converter control *\u002F\n    PWM_Init(PWM_CHANNEL_DCDC, 100000);  \u002F* 100 kHz switching *\u002F\n\n    \u002F* Set initial duty cycle to 0 *\u002F\n    PWM_SetDutyCycle(PWM_CHANNEL_DCDC, 0);\n\n    g_dcdc.enabled = false;\n}\n\nvoid PDU_DCDC_Enable(void) {\n    \u002F* Safety checks *\u002F\n    g_dcdc.hv_input_voltage_v = ADC_ReadHVInput();\n\n    if (g_dcdc.hv_input_voltage_v \u003C HV_INPUT_MIN_V ||\n        g_dcdc.hv_input_voltage_v > HV_INPUT_MAX_V) {\n        g_dcdc.fault_active = true;\n        return;\n    }\n\n    \u002F* Enable DC\u002FDC converter *\u002F\n    GPIO_Set(GPIO_DCDC_ENABLE, true);\n    g_dcdc.enabled = true;\n\n    \u002F* Start voltage regulation loop *\u002F\n    PDU_DCDC_RegulationLoop();\n}\n\nvoid PDU_DCDC_RegulationLoop(void) {\n    \u002F* PI controller for output voltage regulation *\u002F\n    static float integral = 0;\n    const float Kp = 0.5;\n    const float Ki = 0.1;\n\n    while (g_dcdc.enabled) {\n        \u002F* Read output voltage and current *\u002F\n        g_dcdc.lv_output_voltage_v = ADC_ReadLVOutput();\n        g_dcdc.output_current_a = ADC_ReadOutputCurrent();\n\n        \u002F* Calculate error *\u002F\n        float error = LV_OUTPUT_TARGET_V - g_dcdc.lv_output_voltage_v;\n\n        \u002F* PI control *\u002F\n        integral += error * 0.01;  \u002F* 10ms loop time *\u002F\n        float duty_cycle = (Kp * error) + (Ki * integral);\n\n        \u002F* Clamp duty cycle *\u002F\n        if (duty_cycle > 95) duty_cycle = 95;\n        if (duty_cycle \u003C 5) duty_cycle = 5;\n\n        PWM_SetDutyCycle(PWM_CHANNEL_DCDC, duty_cycle);\n\n        \u002F* Overcurrent protection *\u002F\n        if (g_dcdc.output_current_a > MAX_OUTPUT_CURRENT_A) {\n            PDU_DCDC_Disable();\n            g_dcdc.fault_active = true;\n            DTC_SetFault(DTC_DCDC_OVERCURRENT);\n            break;\n        }\n\n        OsTask_Sleep(10);\n    }\n}\n\nvoid PDU_DCDC_Disable(void) {\n    PWM_SetDutyCycle(PWM_CHANNEL_DCDC, 0);\n    GPIO_Set(GPIO_DCDC_ENABLE, false);\n    g_dcdc.enabled = false;\n}\n```\n\n### 2. Low-Voltage Power Distribution (Fuse\u002FRelay Control)\n```c\n\u002F* pdu_lv_distribution.c - 12V power distribution and load management *\u002F\n#include \"pdu_lv_distribution.h\"\n\n#define MAX_POWER_CHANNELS 16\n\ntypedef enum {\n    LOAD_PRIORITY_CRITICAL = 0,    \u002F* Safety: always on *\u002F\n    LOAD_PRIORITY_HIGH,             \u002F* Powertrain *\u002F\n    LOAD_PRIORITY_MEDIUM,           \u002F* Comfort *\u002F\n    LOAD_PRIORITY_LOW               \u002F* Infotainment *\u002F\n} LoadPriority_t;\n\ntypedef struct {\n    const char* name;\n    uint8_t relay_pin;\n    uint8_t current_sense_adc;\n    float max_current_a;\n    LoadPriority_t priority;\n    bool enabled;\n    float measured_current_a;\n} PowerChannel_t;\n\nstatic PowerChannel_t g_power_channels[MAX_POWER_CHANNELS] = {\n    {\"BCM\", GPIO_RELAY_BCM, ADC_CH_BCM_CURRENT, 15.0, LOAD_PRIORITY_CRITICAL, true, 0},\n    {\"VCU\", GPIO_RELAY_VCU, ADC_CH_VCU_CURRENT, 10.0, LOAD_PRIORITY_CRITICAL, true, 0},\n    {\"BMS\", GPIO_RELAY_BMS, ADC_CH_BMS_CURRENT, 8.0, LOAD_PRIORITY_CRITICAL, true, 0},\n    {\"MCU\", GPIO_RELAY_MCU, ADC_CH_MCU_CURRENT, 12.0, LOAD_PRIORITY_HIGH, true, 0},\n    {\"IVI\", GPIO_RELAY_IVI, ADC_CH_IVI_CURRENT, 20.0, LOAD_PRIORITY_LOW, true, 0},\n    {\"HVAC\", GPIO_RELAY_HVAC, ADC_CH_HVAC_CURRENT, 25.0, LOAD_PRIORITY_MEDIUM, true, 0},\n    {\"Headlights\", GPIO_RELAY_LIGHTS, ADC_CH_LIGHTS_CURRENT, 10.0, LOAD_PRIORITY_HIGH, false, 0},\n    {\"USB_Ports\", GPIO_RELAY_USB, ADC_CH_USB_CURRENT, 5.0, LOAD_PRIORITY_LOW, false, 0}\n};\n\nvoid PDU_LV_Init(void) {\n    \u002F* Initialize all relay control pins *\u002F\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        GPIO_ConfigOutput(g_power_channels[i].relay_pin);\n\n        \u002F* Enable critical and high priority loads by default *\u002F\n        if (g_power_channels[i].priority \u003C= LOAD_PRIORITY_HIGH) {\n            PDU_LV_EnableChannel(i);\n        }\n    }\n}\n\nvoid PDU_LV_EnableChannel(uint8_t channel_id) {\n    if (channel_id >= MAX_POWER_CHANNELS) return;\n\n    GPIO_Set(g_power_channels[channel_id].relay_pin, true);\n    g_power_channels[channel_id].enabled = true;\n}\n\nvoid PDU_LV_DisableChannel(uint8_t channel_id) {\n    if (channel_id >= MAX_POWER_CHANNELS) return;\n\n    GPIO_Set(g_power_channels[channel_id].relay_pin, false);\n    g_power_channels[channel_id].enabled = false;\n}\n\n\u002F* Monitor current and detect overcurrent faults *\u002F\nvoid PDU_LV_MonitorCurrents(void) {\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        if (!g_power_channels[i].enabled) continue;\n\n        \u002F* Read current sensor (Hall effect sensor, 185mV\u002FA) *\u002F\n        uint16_t adc_value = ADC_Read(g_power_channels[i].current_sense_adc);\n        float voltage_mv = (adc_value * 5000.0) \u002F 4096.0;\n\n        g_power_channels[i].measured_current_a = (voltage_mv - 2500.0) \u002F 185.0;\n\n        \u002F* Check for overcurrent *\u002F\n        if (g_power_channels[i].measured_current_a > g_power_channels[i].max_current_a) {\n            \u002F* Overcurrent detected: disable channel *\u002F\n            PDU_LV_DisableChannel(i);\n            DTC_SetFault(DTC_OVERCURRENT_BASE + i);\n\n            \u002F* Log event *\u002F\n            Log(\"Overcurrent on %s: %.2f A (max %.2f A)\",\n                g_power_channels[i].name,\n                g_power_channels[i].measured_current_a,\n                g_power_channels[i].max_current_a);\n        }\n    }\n}\n```\n\n### 3. Load Shedding (Power Budget Management)\n```c\n\u002F* pdu_load_shedding.c - Intelligent load management under power constraints *\u002F\n#include \"pdu_load_shedding.h\"\n\n#define BATTERY_CRITICAL_VOLTAGE_V 11.0\n#define BATTERY_LOW_VOLTAGE_V 11.5\n\nvoid PDU_LoadShedding_Update(void) {\n    float battery_voltage = ADC_ReadBatteryVoltage();\n    float total_current = 0;\n\n    \u002F* Calculate total current draw *\u002F\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        if (g_power_channels[i].enabled) {\n            total_current += g_power_channels[i].measured_current_a;\n        }\n    }\n\n    \u002F* Check if battery voltage is low *\u002F\n    if (battery_voltage \u003C BATTERY_CRITICAL_VOLTAGE_V) {\n        \u002F* Critical: shed all non-critical loads *\u002F\n        for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n            if (g_power_channels[i].priority > LOAD_PRIORITY_CRITICAL) {\n                PDU_LV_DisableChannel(i);\n            }\n        }\n\n        Log(\"Critical battery voltage: %.2f V - load shedding active\", battery_voltage);\n\n    } else if (battery_voltage \u003C BATTERY_LOW_VOLTAGE_V) {\n        \u002F* Low: shed low-priority loads *\u002F\n        for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n            if (g_power_channels[i].priority >= LOAD_PRIORITY_LOW) {\n                PDU_LV_DisableChannel(i);\n            }\n        }\n\n        Log(\"Low battery voltage: %.2f V - reducing load\", battery_voltage);\n    }\n\n    \u002F* Check DC\u002FDC converter output current limit *\u002F\n    if (total_current > (MAX_OUTPUT_CURRENT_A * 0.9)) {\n        \u002F* Approaching limit: shed lowest priority loads *\u002F\n        for (int i = MAX_POWER_CHANNELS - 1; i >= 0; i--) {\n            if (g_power_channels[i].priority == LOAD_PRIORITY_LOW &&\n                g_power_channels[i].enabled) {\n                PDU_LV_DisableChannel(i);\n\n                \u002F* Recalculate total current *\u002F\n                total_current -= g_power_channels[i].measured_current_a;\n\n                if (total_current \u003C (MAX_OUTPUT_CURRENT_A * 0.85)) {\n                    break;  \u002F* Sufficient headroom *\u002F\n                }\n            }\n        }\n    }\n}\n```\n\n### 4. Wake-Up Source Management\n```c\n\u002F* pdu_wakeup_sources.c - Network wake-up coordination *\u002F\n#include \"pdu_wakeup_sources.h\"\n\n#define WAKEUP_CAN_TIMEOUT_MS 100\n#define SLEEP_DELAY_MS 5000\n\ntypedef enum {\n    WAKEUP_SOURCE_CAN = 0,\n    WAKEUP_SOURCE_LIN,\n    WAKEUP_SOURCE_IGNITION,\n    WAKEUP_SOURCE_DOOR,\n    WAKEUP_SOURCE_TIMER,\n    WAKEUP_SOURCE_COUNT\n} WakeupSource_t;\n\nstatic bool g_wakeup_pending[WAKEUP_SOURCE_COUNT] = {false};\n\nvoid PDU_Wakeup_OnCANActivity(void) {\n    g_wakeup_pending[WAKEUP_SOURCE_CAN] = true;\n\n    \u002F* Power up CAN transceivers *\u002F\n    GPIO_Set(GPIO_CAN_POWERTRAIN_ENABLE, true);\n    GPIO_Set(GPIO_CAN_CHASSIS_ENABLE, true);\n\n    \u002F* Notify ECUs of wake-up *\u002F\n    CAN_SendWakeupNotification();\n}\n\nvoid PDU_Sleep_Prepare(void) {\n    \u002F* Wait for all ECUs to enter sleep *\u002F\n    uint32_t start_time = GetSystemTime_ms();\n\n    while ((GetSystemTime_ms() - start_time) \u003C SLEEP_DELAY_MS) {\n        \u002F* Check for wake-up requests *\u002F\n        for (int i = 0; i \u003C WAKEUP_SOURCE_COUNT; i++) {\n            if (g_wakeup_pending[i]) {\n                \u002F* Wake-up requested: abort sleep *\u002F\n                return;\n            }\n        }\n        OsTask_Sleep(10);\n    }\n\n    \u002F* Enter sleep mode *\u002F\n    PDU_EnterSleep();\n}\n\nvoid PDU_EnterSleep(void) {\n    \u002F* Disable non-critical power channels *\u002F\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        if (g_power_channels[i].priority > LOAD_PRIORITY_CRITICAL) {\n            PDU_LV_DisableChannel(i);\n        }\n    }\n\n    \u002F* Configure wake-up sources *\u002F\n    CAN_ConfigureWakeup(CAN_WAKEUP_ENABLED);\n    GPIO_ConfigureWakeup(GPIO_IGNITION, GPIO_WAKEUP_RISING_EDGE);\n\n    \u002F* Enter low-power mode *\u002F\n    Mcu_SetMode(MCU_MODE_SLEEP);\n}\n```\n\n## PDU CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: PDU VCU BMS BCM\n\n\u002F* PDU Power Status *\u002F\nBO_ 896 PDU_PowerStatus: 8 PDU\n SG_ PDU_BatteryVoltage_V : 0|16@1+ (0.01,0) [0|16] \"V\"  VCU,BMS\n SG_ PDU_DCDCOutputCurrent_A : 16|16@1+ (0.1,0) [0|200] \"A\"  VCU\n SG_ PDU_LoadSheddingActive : 32|1@1+ (0,0) [0|1] \"\"  VCU,BCM\n SG_ PDU_PowerChannelStatus : 40|16@1+ (0,0) [0|65535] \"\"  VCU\n\n\u002F* Each bit in PowerChannelStatus represents one load (0=off, 1=on) *\u002F\n```\n\n## References\n- LTC3780: High-Voltage Buck-Boost DC\u002FDC Controller\n- ISO 16750: Road vehicles - Environmental conditions and testing for electrical and electronic equipment\n- SAE J1455: Recommended Environmental Practices for Electronic Equipment Design\n- IEC 61000-4-2: EMC Immunity to Electrostatic Discharge\n\n## Common Issues\n- DC\u002FDC converter instability at high loads\n- Relay contact welding from inrush current\n- False overcurrent detection from current sensor noise\n- Wake-up failures due to CAN transceiver not powered\n\n---\n\n## Tcu Telematics Connectivity\n\n# TCU (Telematics Control Unit) - Connectivity and Remote Services\n\n## Overview\nThe Telematics Control Unit (TCU) provides 4G\u002F5G cellular connectivity, GNSS positioning, remote diagnostics, OTA updates, eCall\u002FbCall emergency services, and fleet management integration. This skill covers production-ready TCU development with modem integration.\n\n## Core Responsibilities\n\n### 1. 4G\u002F5G Modem Integration\n```c\n\u002F* tcu_modem_manager.c - Cellular modem control (Quectel\u002FSierra Wireless) *\u002F\n#include \"tcu_modem_manager.h\"\n#include \u003Cstring.h>\n#include \u003Cstdio.h>\n\n#define MODEM_UART_PORT \"\u002Fdev\u002FttyUSB2\"\n#define MODEM_BAUD_RATE 115200\n#define AT_COMMAND_TIMEOUT_MS 5000\n#define MAX_AT_RESPONSE_LENGTH 512\n\ntypedef enum {\n    MODEM_STATE_OFF = 0,\n    MODEM_STATE_INITIALIZING,\n    MODEM_STATE_REGISTERING,\n    MODEM_STATE_CONNECTED,\n    MODEM_STATE_ERROR\n} ModemState_t;\n\ntypedef struct {\n    int uart_fd;\n    ModemState_t state;\n    char imei[16];\n    char iccid[21];\n    int signal_strength_dbm;\n    char network_operator[32];\n    char ip_address[16];\n    bool data_session_active;\n} ModemContext_t;\n\nstatic ModemContext_t g_modem = {0};\n\n\u002F* AT command send\u002Freceive *\u002F\nbool TCU_Modem_SendATCommand(const char* cmd, char* response, uint16_t response_size) {\n    \u002F* Send AT command *\u002F\n    char cmd_buffer[128];\n    snprintf(cmd_buffer, sizeof(cmd_buffer), \"%s\\r\\n\", cmd);\n\n    int bytes_written = write(g_modem.uart_fd, cmd_buffer, strlen(cmd_buffer));\n    if (bytes_written \u003C 0) {\n        return false;\n    }\n\n    \u002F* Wait for response *\u002F\n    uint32_t start_time = GetSystemTime_ms();\n    int total_bytes = 0;\n\n    while ((GetSystemTime_ms() - start_time) \u003C AT_COMMAND_TIMEOUT_MS) {\n        int bytes_available = 0;\n        ioctl(g_modem.uart_fd, FIONREAD, &bytes_available);\n\n        if (bytes_available > 0) {\n            int bytes_read = read(g_modem.uart_fd,\n                                   &response[total_bytes],\n                                   response_size - total_bytes - 1);\n            if (bytes_read > 0) {\n                total_bytes += bytes_read;\n                response[total_bytes] = '\\0';\n\n                \u002F* Check for \"OK\" or \"ERROR\" *\u002F\n                if (strstr(response, \"OK\\r\\n\") != NULL) {\n                    return true;\n                }\n                if (strstr(response, \"ERROR\\r\\n\") != NULL) {\n                    return false;\n                }\n            }\n        }\n\n        usleep(10000);  \u002F* 10ms polling interval *\u002F\n    }\n\n    return false;  \u002F* Timeout *\u002F\n}\n\nvoid TCU_Modem_Init(void) {\n    \u002F* Open UART port *\u002F\n    g_modem.uart_fd = open(MODEM_UART_PORT, O_RDWR | O_NOCTTY);\n    if (g_modem.uart_fd \u003C 0) {\n        g_modem.state = MODEM_STATE_ERROR;\n        return;\n    }\n\n    \u002F* Configure UART: 115200 8N1 *\u002F\n    struct termios tty;\n    tcgetattr(g_modem.uart_fd, &tty);\n    cfsetospeed(&tty, B115200);\n    cfsetispeed(&tty, B115200);\n    tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;\n    tty.c_cflag &= ~PARENB;\n    tty.c_cflag &= ~CSTOPB;\n    tcsetattr(g_modem.uart_fd, TCSANOW, &tty);\n\n    g_modem.state = MODEM_STATE_INITIALIZING;\n\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Basic AT command check *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT\", response, sizeof(response))) {\n        g_modem.state = MODEM_STATE_ERROR;\n        return;\n    }\n\n    \u002F* Disable echo *\u002F\n    TCU_Modem_SendATCommand(\"ATE0\", response, sizeof(response));\n\n    \u002F* Get IMEI *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+GSN\", response, sizeof(response))) {\n        sscanf(response, \"%15s\", g_modem.imei);\n    }\n\n    \u002F* Get ICCID (SIM card ID) *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+CCID\", response, sizeof(response))) {\n        sscanf(response, \"+CCID: %20s\", g_modem.iccid);\n    }\n\n    \u002F* Check SIM status *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT+CPIN?\", response, sizeof(response))) {\n        g_modem.state = MODEM_STATE_ERROR;\n        return;\n    }\n\n    \u002F* Start network registration *\u002F\n    TCU_Modem_StartNetworkRegistration();\n}\n\nvoid TCU_Modem_StartNetworkRegistration(void) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Set network mode: LTE only for 4G, NR+LTE for 5G *\u002F\n    TCU_Modem_SendATCommand(\"AT+QCFG=\\\"nwscanmode\\\",3\", response, sizeof(response));\n\n    \u002F* Enable network registration URC *\u002F\n    TCU_Modem_SendATCommand(\"AT+CREG=2\", response, sizeof(response));\n\n    \u002F* Check registration status *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+CREG?\", response, sizeof(response))) {\n        int n, stat;\n        if (sscanf(response, \"+CREG: %d,%d\", &n, &stat) == 2) {\n            if (stat == 1 || stat == 5) {  \u002F* Registered (home or roaming) *\u002F\n                g_modem.state = MODEM_STATE_REGISTERED;\n                TCU_Modem_GetNetworkInfo();\n            } else {\n                g_modem.state = MODEM_STATE_REGISTERING;\n            }\n        }\n    }\n}\n\nvoid TCU_Modem_GetNetworkInfo(void) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Get signal strength *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+CSQ\", response, sizeof(response))) {\n        int rssi, ber;\n        if (sscanf(response, \"+CSQ: %d,%d\", &rssi, &ber) == 2) {\n            \u002F* Convert RSSI to dBm: dBm = -113 + 2*rssi *\u002F\n            g_modem.signal_strength_dbm = -113 + (2 * rssi);\n        }\n    }\n\n    \u002F* Get operator name *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+COPS?\", response, sizeof(response))) {\n        char operator_name[32];\n        if (sscanf(response, \"+COPS: 0,0,\\\"%31[^\\\"]\\\"\", operator_name) == 1) {\n            strncpy(g_modem.network_operator, operator_name, sizeof(g_modem.network_operator));\n        }\n    }\n}\n\nbool TCU_Modem_StartDataSession(const char* apn) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n    char cmd[128];\n\n    \u002F* Configure PDP context *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QICSGP=1,1,\\\"%s\\\",\\\"\\\",\\\"\\\",1\", apn);\n    if (!TCU_Modem_SendATCommand(cmd, response, sizeof(response))) {\n        return false;\n    }\n\n    \u002F* Activate PDP context *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT+QIACT=1\", response, sizeof(response))) {\n        return false;\n    }\n\n    \u002F* Get IP address *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+QIACT?\", response, sizeof(response))) {\n        char ip_addr[16];\n        if (sscanf(response, \"+QIACT: 1,1,1,\\\"%15[^\\\"]\\\"\", ip_addr) == 1) {\n            strncpy(g_modem.ip_address, ip_addr, sizeof(g_modem.ip_address));\n            g_modem.data_session_active = true;\n            g_modem.state = MODEM_STATE_CONNECTED;\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\u002F* HTTP client for cloud connectivity *\u002F\nbool TCU_Modem_HTTPPost(const char* url, const char* json_payload, char* response) {\n    char cmd[256];\n    char at_response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Configure HTTP context *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QHTTPCFG=\\\"contextid\\\",1\");\n    TCU_Modem_SendATCommand(cmd, at_response, sizeof(at_response));\n\n    \u002F* Set URL *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QHTTPURL=%zu,80\", strlen(url));\n    TCU_Modem_SendATCommand(cmd, at_response, sizeof(at_response));\n\n    \u002F* Send URL *\u002F\n    write(g_modem.uart_fd, url, strlen(url));\n    usleep(100000);\n\n    \u002F* POST data *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QHTTPPOST=%zu,80,80\", strlen(json_payload));\n    TCU_Modem_SendATCommand(cmd, at_response, sizeof(at_response));\n\n    \u002F* Send payload *\u002F\n    write(g_modem.uart_fd, json_payload, strlen(json_payload));\n\n    \u002F* Wait for response *\u002F\n    sleep(2);\n\n    \u002F* Read response *\u002F\n    TCU_Modem_SendATCommand(\"AT+QHTTPREAD=80\", response, MAX_AT_RESPONSE_LENGTH);\n\n    return true;\n}\n```\n\n### 2. GNSS\u002FGPS Position Tracking\n```c\n\u002F* tcu_gnss_manager.c - GPS\u002FGLONASS\u002FBeiDou positioning *\u002F\n#include \"tcu_gnss_manager.h\"\n#include \u003Cmath.h>\n\n#define EARTH_RADIUS_KM 6371.0\n\ntypedef struct {\n    double latitude;\n    double longitude;\n    float altitude_m;\n    float speed_kph;\n    float heading_deg;\n    uint8_t satellites_used;\n    float hdop;  \u002F* Horizontal dilution of precision *\u002F\n    bool fix_valid;\n    uint32_t timestamp_ms;\n} GNSSPosition_t;\n\nstatic GNSSPosition_t g_gnss_position = {0};\n\nvoid TCU_GNSS_Init(void) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Enable GNSS *\u002F\n    TCU_Modem_SendATCommand(\"AT+QGPS=1\", response, sizeof(response));\n\n    \u002F* Configure GNSS to use GPS+GLONASS+BeiDou *\u002F\n    TCU_Modem_SendATCommand(\"AT+QGPSCFG=\\\"gnssconfig\\\",7\", response, sizeof(response));\n}\n\nbool TCU_GNSS_GetPosition(GNSSPosition_t* position) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Query GNSS position *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT+QGPSLOC=2\", response, sizeof(response))) {\n        return false;\n    }\n\n    \u002F* Parse NMEA-like response: +QGPSLOC: \u003Ctime>,\u003Clat>,\u003Clon>,\u003Chdop>,\u003Calt>,\u003Cfix>,\u003Ccog>,\u003Cspkm>,\u003Cspkn>,\u003Cdate>,\u003Cnsat> *\u002F\n    char time_str[16], date_str[16];\n    int fix_type, nsat;\n\n    int parsed = sscanf(response,\n                        \"+QGPSLOC: %15[^,],%lf,%lf,%f,%f,%d,%f,%f,%*f,%15[^,],%d\",\n                        time_str,\n                        &position->latitude,\n                        &position->longitude,\n                        &position->hdop,\n                        &position->altitude_m,\n                        &fix_type,\n                        &position->heading_deg,\n                        &position->speed_kph,\n                        date_str,\n                        &nsat);\n\n    if (parsed >= 9) {\n        position->satellites_used = nsat;\n        position->fix_valid = (fix_type >= 2);  \u002F* 2D or 3D fix *\u002F\n        position->timestamp_ms = GetSystemTime_ms();\n\n        \u002F* Update global position *\u002F\n        memcpy(&g_gnss_position, position, sizeof(GNSSPosition_t));\n\n        return true;\n    }\n\n    return false;\n}\n\n\u002F* Calculate distance between two GPS coordinates (Haversine formula) *\u002F\nfloat TCU_GNSS_CalculateDistance_km(double lat1, double lon1, double lat2, double lon2) {\n    double dLat = (lat2 - lat1) * M_PI \u002F 180.0;\n    double dLon = (lon2 - lon1) * M_PI \u002F 180.0;\n\n    lat1 = lat1 * M_PI \u002F 180.0;\n    lat2 = lat2 * M_PI \u002F 180.0;\n\n    double a = sin(dLat \u002F 2) * sin(dLat \u002F 2) +\n               sin(dLon \u002F 2) * sin(dLon \u002F 2) * cos(lat1) * cos(lat2);\n\n    double c = 2 * atan2(sqrt(a), sqrt(1 - a));\n\n    return EARTH_RADIUS_KM * c;\n}\n\n\u002F* Geofencing: check if vehicle is inside defined boundary *\u002F\nbool TCU_GNSS_IsInsideGeofence(double center_lat, double center_lon, float radius_km) {\n    if (!g_gnss_position.fix_valid) {\n        return false;\n    }\n\n    float distance = TCU_GNSS_CalculateDistance_km(\n        g_gnss_position.latitude,\n        g_gnss_position.longitude,\n        center_lat,\n        center_lon);\n\n    return (distance \u003C= radius_km);\n}\n```\n\n### 3. Remote Diagnostics (UDS over HTTP)\n```c\n\u002F* tcu_remote_diagnostics.c - Cloud-based diagnostic services *\u002F\n#include \"tcu_remote_diagnostics.h\"\n#include \"json.h\"\n\n#define CLOUD_DIAGNOSTICS_URL \"https:\u002F\u002Ftelemetry.example.com\u002Fapi\u002Fv1\u002Fdiagnostics\"\n\ntypedef struct {\n    uint32_t dtc_code;\n    uint8_t status;\n    uint32_t occurrence_count;\n    uint32_t first_occurrence_timestamp;\n} DTC_Entry_t;\n\nvoid TCU_RemoteDiagnostics_SendDTCs(void) {\n    \u002F* Read DTCs from all ECUs via CAN *\u002F\n    DTC_Entry_t dtc_list[32];\n    uint8_t dtc_count = 0;\n\n    \u002F* Query VCU for DTCs *\u002F\n    uint8_t uds_request[] = {0x19, 0x02, 0xFF};  \u002F* ReadDTCByStatusMask *\u002F\n    uint8_t uds_response[256];\n    uint16_t response_length;\n\n    if (UDS_SendRequest(VCU_DIAGNOSTIC_ADDR, uds_request, 3,\n                        uds_response, &response_length)) {\n        \u002F* Parse DTC response *\u002F\n        for (int i = 3; i \u003C response_length; i += 4) {\n            dtc_list[dtc_count].dtc_code = (uds_response[i] \u003C\u003C 16) |\n                                            (uds_response[i+1] \u003C\u003C 8) |\n                                            uds_response[i+2];\n            dtc_list[dtc_count].status = uds_response[i+3];\n            dtc_count++;\n        }\n    }\n\n    \u002F* Build JSON payload *\u002F\n    char json_payload[1024];\n    snprintf(json_payload, sizeof(json_payload),\n             \"{\"\n             \"\\\"vin\\\":\\\"%s\\\",\"\n             \"\\\"timestamp\\\":%u,\"\n             \"\\\"dtcs\\\":[\",\n             g_vehicle_vin,\n             GetSystemTime_ms());\n\n    for (int i = 0; i \u003C dtc_count; i++) {\n        char dtc_entry[128];\n        snprintf(dtc_entry, sizeof(dtc_entry),\n                 \"{\\\"code\\\":\\\"0x%06X\\\",\\\"status\\\":0x%02X}%s\",\n                 dtc_list[i].dtc_code,\n                 dtc_list[i].status,\n                 (i \u003C dtc_count - 1) ? \",\" : \"\");\n        strcat(json_payload, dtc_entry);\n    }\n\n    strcat(json_payload, \"]}\");\n\n    \u002F* Send to cloud via HTTPS *\u002F\n    char response[512];\n    TCU_Modem_HTTPPost(CLOUD_DIAGNOSTICS_URL, json_payload, response);\n}\n\nvoid TCU_RemoteDiagnostics_ExecuteCommand(const char* command_json) {\n    \u002F* Parse remote diagnostic command *\u002F\n    json_object* root = json_tokener_parse(command_json);\n    json_object* cmd_type_obj = json_object_object_get(root, \"command\");\n\n    const char* cmd_type = json_object_get_string(cmd_type_obj);\n\n    if (strcmp(cmd_type, \"READ_DTC\") == 0) {\n        TCU_RemoteDiagnostics_SendDTCs();\n    } else if (strcmp(cmd_type, \"CLEAR_DTC\") == 0) {\n        \u002F* Send UDS ClearDiagnosticInformation *\u002F\n        uint8_t uds_clear_dtc[] = {0x14, 0xFF, 0xFF, 0xFF};\n        uint8_t response[8];\n        uint16_t response_length;\n        UDS_SendRequest(VCU_DIAGNOSTIC_ADDR, uds_clear_dtc, 4, response, &response_length);\n    } else if (strcmp(cmd_type, \"READ_DATA\") == 0) {\n        \u002F* Read live data via UDS ReadDataByIdentifier *\u002F\n        json_object* did_obj = json_object_object_get(root, \"did\");\n        uint16_t did = json_object_get_int(did_obj);\n\n        uint8_t uds_read_data[] = {0x22, (did >> 8) & 0xFF, did & 0xFF};\n        uint8_t response[256];\n        uint16_t response_length;\n\n        if (UDS_SendRequest(VCU_DIAGNOSTIC_ADDR, uds_read_data, 3,\n                            response, &response_length)) {\n            \u002F* Send response back to cloud *\u002F\n            char response_json[512];\n            snprintf(response_json, sizeof(response_json),\n                     \"{\\\"vin\\\":\\\"%s\\\",\\\"did\\\":\\\"0x%04X\\\",\\\"data\\\":\\\"\",\n                     g_vehicle_vin, did);\n\n            for (int i = 0; i \u003C response_length; i++) {\n                char hex[4];\n                snprintf(hex, sizeof(hex), \"%02X\", response[i]);\n                strcat(response_json, hex);\n            }\n\n            strcat(response_json, \"\\\"}\");\n            TCU_Modem_HTTPPost(CLOUD_DIAGNOSTICS_URL, response_json, NULL);\n        }\n    }\n\n    json_object_put(root);\n}\n```\n\n### 4. eCall \u002F bCall Emergency Services\n```c\n\u002F* tcu_ecall.c - Automatic emergency call (eCall) - EU regulation *\u002F\n#include \"tcu_ecall.h\"\n\n#define ECALL_EMERGENCY_NUMBER \"112\"\n#define BCALL_ROADSIDE_NUMBER \"1234567890\"\n\ntypedef struct {\n    uint8_t msd_format_version;\n    uint8_t message_identifier;\n    uint32_t timestamp;\n    double latitude;\n    double longitude;\n    uint8_t vehicle_class;\n    char vin[18];\n    uint8_t propulsion_storage_type;\n    bool recent_engine_status;\n} MSD_t;  \u002F* Minimum Set of Data for eCall *\u002F\n\nvoid TCU_eCall_Trigger(bool automatic) {\n    \u002F* Build MSD (Minimum Set of Data) *\u002F\n    MSD_t msd = {0};\n    msd.msd_format_version = 1;\n    msd.message_identifier = automatic ? 1 : 2;  \u002F* 1=automatic, 2=manual *\u002F\n    msd.timestamp = GetSystemTime_ms() \u002F 1000;\n\n    \u002F* Get current GPS position *\u002F\n    GNSSPosition_t position;\n    if (TCU_GNSS_GetPosition(&position)) {\n        msd.latitude = position.latitude;\n        msd.longitude = position.longitude;\n    }\n\n    msd.vehicle_class = 1;  \u002F* M1 (passenger car) *\u002F\n    strncpy(msd.vin, g_vehicle_vin, sizeof(msd.vin));\n    msd.propulsion_storage_type = 0x05;  \u002F* Electric *\u002F\n    msd.recent_engine_status = VCU_IsVehicleOn();\n\n    \u002F* Encode MSD to ASN.1 format *\u002F\n    uint8_t msd_encoded[140];  \u002F* Max 140 bytes for MSD *\u002F\n    uint16_t msd_length = TCU_eCall_EncodeMSD(&msd, msd_encoded);\n\n    \u002F* Initiate voice call to emergency services *\u002F\n    char at_cmd[64];\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    snprintf(at_cmd, sizeof(at_cmd), \"ATD%s;\", ECALL_EMERGENCY_NUMBER);\n    TCU_Modem_SendATCommand(at_cmd, response, sizeof(response));\n\n    \u002F* Wait for call connection *\u002F\n    sleep(3);\n\n    \u002F* Send MSD over in-band modem (IVS - In-Vehicle System) *\u002F\n    TCU_eCall_SendMSDInBand(msd_encoded, msd_length);\n\n    \u002F* Keep call active for voice communication *\u002F\n    \u002F* Operator will speak with occupants if possible *\u002F\n}\n\nvoid TCU_bCall_Trigger(void) {\n    \u002F* Breakdown call: non-emergency roadside assistance *\u002F\n    char at_cmd[64];\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    snprintf(at_cmd, sizeof(at_cmd), \"ATD%s;\", BCALL_ROADSIDE_NUMBER);\n    TCU_Modem_SendATCommand(at_cmd, response, sizeof(response));\n\n    \u002F* Send vehicle data to roadside assistance *\u002F\n    char json_payload[512];\n    GNSSPosition_t position;\n    TCU_GNSS_GetPosition(&position);\n\n    snprintf(json_payload, sizeof(json_payload),\n             \"{\"\n             \"\\\"vin\\\":\\\"%s\\\",\"\n             \"\\\"latitude\\\":%.6f,\"\n             \"\\\"longitude\\\":%.6f,\"\n             \"\\\"issue\\\":\\\"Breakdown assistance requested\\\"\"\n             \"}\",\n             g_vehicle_vin,\n             position.latitude,\n             position.longitude);\n\n    TCU_Modem_HTTPPost(\"https:\u002F\u002Froadside.example.com\u002Fapi\u002Fassist\", json_payload, NULL);\n}\n```\n\n### 5. OTA Download Manager\n```c\n\u002F* tcu_ota_manager.c - Over-the-Air software updates *\u002F\n#include \"tcu_ota_manager.h\"\n\n#define OTA_SERVER_URL \"https:\u002F\u002Fota.example.com\u002Fapi\u002Fv1\u002Fupdates\"\n#define OTA_CHUNK_SIZE 4096\n\ntypedef struct {\n    char version[16];\n    char ecu_target[32];\n    uint32_t file_size;\n    char download_url[256];\n    uint8_t sha256_hash[32];\n} OTAPackage_t;\n\ntypedef struct {\n    bool update_available;\n    OTAPackage_t package;\n    uint32_t bytes_downloaded;\n    uint8_t download_progress_percent;\n    bool download_complete;\n} OTAState_t;\n\nstatic OTAState_t g_ota_state = {0};\n\nbool TCU_OTA_CheckForUpdates(void) {\n    \u002F* Query OTA server for available updates *\u002F\n    char json_request[256];\n    snprintf(json_request, sizeof(json_request),\n             \"{\\\"vin\\\":\\\"%s\\\",\\\"current_versions\\\":{\"\n             \"\\\"vcu\\\":\\\"1.2.3\\\",\\\"bms\\\":\\\"2.0.1\\\",\\\"mcu\\\":\\\"3.1.0\\\"\"\n             \"}}\",\n             g_vehicle_vin);\n\n    char response[1024];\n    if (!TCU_Modem_HTTPPost(OTA_SERVER_URL, json_request, response)) {\n        return false;\n    }\n\n    \u002F* Parse JSON response *\u002F\n    json_object* root = json_tokener_parse(response);\n    json_object* update_available_obj = json_object_object_get(root, \"update_available\");\n\n    if (json_object_get_boolean(update_available_obj)) {\n        json_object* package_obj = json_object_object_get(root, \"package\");\n\n        \u002F* Extract package info *\u002F\n        json_object* version_obj = json_object_object_get(package_obj, \"version\");\n        json_object* ecu_obj = json_object_object_get(package_obj, \"ecu\");\n        json_object* size_obj = json_object_object_get(package_obj, \"size\");\n        json_object* url_obj = json_object_object_get(package_obj, \"url\");\n\n        strncpy(g_ota_state.package.version,\n                json_object_get_string(version_obj),\n                sizeof(g_ota_state.package.version));\n\n        strncpy(g_ota_state.package.ecu_target,\n                json_object_get_string(ecu_obj),\n                sizeof(g_ota_state.package.ecu_target));\n\n        g_ota_state.package.file_size = json_object_get_int(size_obj);\n\n        strncpy(g_ota_state.package.download_url,\n                json_object_get_string(url_obj),\n                sizeof(g_ota_state.package.download_url));\n\n        g_ota_state.update_available = true;\n\n        json_object_put(root);\n        return true;\n    }\n\n    json_object_put(root);\n    return false;\n}\n\nbool TCU_OTA_DownloadPackage(void) {\n    if (!g_ota_state.update_available) {\n        return false;\n    }\n\n    \u002F* Open file for writing *\u002F\n    int fd = open(\"\u002Fdata\u002Fota\u002Fupdate.bin\", O_WRONLY | O_CREAT | O_TRUNC, 0644);\n    if (fd \u003C 0) {\n        return false;\n    }\n\n    \u002F* Download in chunks *\u002F\n    uint32_t offset = 0;\n    uint8_t buffer[OTA_CHUNK_SIZE];\n\n    while (offset \u003C g_ota_state.package.file_size) {\n        uint32_t chunk_size = (g_ota_state.package.file_size - offset) > OTA_CHUNK_SIZE ?\n                               OTA_CHUNK_SIZE : (g_ota_state.package.file_size - offset);\n\n        \u002F* HTTP range request *\u002F\n        char range_header[64];\n        snprintf(range_header, sizeof(range_header),\n                 \"Range: bytes=%u-%u\", offset, offset + chunk_size - 1);\n\n        \u002F* Download chunk (simplified - use libcurl in production) *\u002F\n        if (!TCU_HTTP_DownloadChunk(g_ota_state.package.download_url,\n                                      range_header, buffer, chunk_size)) {\n            close(fd);\n            return false;\n        }\n\n        \u002F* Write to file *\u002F\n        write(fd, buffer, chunk_size);\n\n        offset += chunk_size;\n        g_ota_state.bytes_downloaded = offset;\n        g_ota_state.download_progress_percent =\n            (offset * 100) \u002F g_ota_state.package.file_size;\n\n        \u002F* Notify user via CAN *\u002F\n        CAN_SendOTAProgress(g_ota_state.download_progress_percent);\n    }\n\n    close(fd);\n    g_ota_state.download_complete = true;\n\n    \u002F* Verify SHA256 hash *\u002F\n    uint8_t calculated_hash[32];\n    TCU_OTA_CalculateSHA256(\"\u002Fdata\u002Fota\u002Fupdate.bin\", calculated_hash);\n\n    if (memcmp(calculated_hash, g_ota_state.package.sha256_hash, 32) != 0) {\n        \u002F* Hash mismatch: corrupted download *\u002F\n        unlink(\"\u002Fdata\u002Fota\u002Fupdate.bin\");\n        return false;\n    }\n\n    return true;\n}\n\nvoid TCU_OTA_InstallPackage(void) {\n    \u002F* Flash update to target ECU *\u002F\n    if (strcmp(g_ota_state.package.ecu_target, \"VCU\") == 0) {\n        \u002F* Flash VCU via UDS RequestDownload \u002F TransferData \u002F RequestTransferExit *\u002F\n        TCU_OTA_FlashECU(VCU_DIAGNOSTIC_ADDR, \"\u002Fdata\u002Fota\u002Fupdate.bin\");\n    } else if (strcmp(g_ota_state.package.ecu_target, \"BMS\") == 0) {\n        TCU_OTA_FlashECU(BMS_DIAGNOSTIC_ADDR, \"\u002Fdata\u002Fota\u002Fupdate.bin\");\n    }\n\n    \u002F* Cleanup *\u002F\n    unlink(\"\u002Fdata\u002Fota\u002Fupdate.bin\");\n    memset(&g_ota_state, 0, sizeof(OTAState_t));\n}\n```\n\n## TCU CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: TCU VCU BCM IVI\n\n\u002F* TCU Status *\u002F\nBO_ 768 TCU_Status: 8 TCU\n SG_ TCU_ModemState : 0|8@1+ (0,0) [0|4] \"\"  VCU,IVI\n SG_ TCU_SignalStrength_dBm : 8|8@1- (-113,0) [-113|0] \"dBm\"  IVI\n SG_ TCU_DataSessionActive : 16|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ TCU_GNSSFixValid : 17|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ TCU_SatellitesUsed : 24|8@1+ (0,0) [0|32] \"\"  IVI\n SG_ TCU_OTAUpdateAvailable : 32|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ TCU_OTADownloadProgress : 40|8@1+ (0,0) [0|100] \"%\"  IVI\n\n\u002F* TCU GPS Position *\u002F\nBO_ 769 TCU_Position: 8 TCU\n SG_ TCU_Latitude : 0|32@1+ (0.0000001,-90) [-90|90] \"deg\"  VCU,IVI\n SG_ TCU_Longitude : 32|32@1+ (0.0000001,-180) [-180|180] \"deg\"  VCU,IVI\n\n\u002F* TCU Speed and Heading *\u002F\nBO_ 770 TCU_Navigation: 8 TCU\n SG_ TCU_GPSSpeed_kph : 0|16@1+ (0.01,0) [0|300] \"km\u002Fh\"  VCU,IVI\n SG_ TCU_Heading_deg : 16|16@1+ (0.01,0) [0|360] \"deg\"  VCU,IVI\n SG_ TCU_Altitude_m : 32|16@1+ (0.1,-500) [-500|9000] \"m\"  IVI\n SG_ TCU_HDOP : 48|8@1+ (0.1,0) [0|25] \"\"  IVI\n\nVAL_ 768 TCU_ModemState 0 \"Off\" 1 \"Initializing\" 2 \"Registering\" 3 \"Connected\" 4 \"Error\";\n```\n\n## References\n- 3GPP TS 24.008: Mobile radio interface Layer 3 specification\n- ETSI EN 16072: eCall Minimum Set of Data (MSD)\n- ISO 17987: Local Interconnect Network (LIN)\n- MQTT Protocol Specification v5.0\n- AWS IoT Core: Fleet Provisioning\n\n## Common Issues\n- Modem not responding to AT commands (baud rate mismatch)\n- GPS fix lost in urban canyons or underground parking\n- OTA download interrupted due to poor signal strength\n- eCall MSD encoding errors\n- Data session dropped during handover between cell towers\n\n---\n\n## Vcu Vehicle Control\n\n# VCU (Vehicle Control Unit) for Electric Vehicles\n\n## Overview\nThe Vehicle Control Unit (VCU) is the central brain for electric vehicles, managing torque arbitration, drive modes, power distribution, regenerative braking, and traction control. This skill covers production-ready VCU development with AUTOSAR BSW integration.\n\n## Core Responsibilities\n\n### 1. Torque Arbitration\n```c\n\u002F* vcu_torque_arbiter.c - Multi-source torque request arbitration *\u002F\n#include \"vcu_torque_arbiter.h\"\n#include \"autosar_rte.h\"\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n\n#define MAX_TORQUE_NM 400\n#define MIN_REGEN_TORQUE_NM -200\n#define TORQUE_RATE_LIMIT_NM_PER_100MS 50\n\ntypedef enum {\n    TORQUE_SOURCE_DRIVER = 0,\n    TORQUE_SOURCE_CRUISE_CONTROL,\n    TORQUE_SOURCE_TRACTION_CONTROL,\n    TORQUE_SOURCE_STABILITY_CONTROL,\n    TORQUE_SOURCE_POWER_LIMIT,\n    TORQUE_SOURCE_THERMAL_LIMIT,\n    TORQUE_SOURCE_COUNT\n} TorqueSource_t;\n\ntypedef struct {\n    int16_t requested_torque_nm;\n    uint8_t priority;\n    bool active;\n    uint32_t timestamp_ms;\n} TorqueRequest_t;\n\ntypedef struct {\n    TorqueRequest_t requests[TORQUE_SOURCE_COUNT];\n    int16_t arbitrated_torque_nm;\n    int16_t previous_torque_nm;\n    TorqueSource_t active_source;\n} TorqueArbiter_t;\n\nstatic TorqueArbiter_t g_torque_arbiter = {0};\n\n\u002F* Priority levels (higher number = higher priority) *\u002F\nstatic const uint8_t TORQUE_PRIORITIES[TORQUE_SOURCE_COUNT] = {\n    [TORQUE_SOURCE_DRIVER] = 1,\n    [TORQUE_SOURCE_CRUISE_CONTROL] = 2,\n    [TORQUE_SOURCE_TRACTION_CONTROL] = 5,  \u002F* Safety critical *\u002F\n    [TORQUE_SOURCE_STABILITY_CONTROL] = 6, \u002F* Highest priority *\u002F\n    [TORQUE_SOURCE_POWER_LIMIT] = 4,\n    [TORQUE_SOURCE_THERMAL_LIMIT] = 3\n};\n\nvoid VCU_TorqueArbiter_Init(void) {\n    memset(&g_torque_arbiter, 0, sizeof(TorqueArbiter_t));\n\n    \u002F* Initialize priorities *\u002F\n    for (int i = 0; i \u003C TORQUE_SOURCE_COUNT; i++) {\n        g_torque_arbiter.requests[i].priority = TORQUE_PRIORITIES[i];\n    }\n}\n\nvoid VCU_TorqueArbiter_SetRequest(TorqueSource_t source, int16_t torque_nm, bool active) {\n    if (source >= TORQUE_SOURCE_COUNT) return;\n\n    \u002F* Clamp torque to physical limits *\u002F\n    if (torque_nm > MAX_TORQUE_NM) torque_nm = MAX_TORQUE_NM;\n    if (torque_nm \u003C MIN_REGEN_TORQUE_NM) torque_nm = MIN_REGEN_TORQUE_NM;\n\n    g_torque_arbiter.requests[source].requested_torque_nm = torque_nm;\n    g_torque_arbiter.requests[source].active = active;\n    g_torque_arbiter.requests[source].timestamp_ms = GetSystemTime_ms();\n}\n\nint16_t VCU_TorqueArbiter_Arbitrate(void) {\n    int16_t result_torque = 0;\n    uint8_t highest_priority = 0;\n    TorqueSource_t active_source = TORQUE_SOURCE_DRIVER;\n\n    \u002F* Find highest priority active request *\u002F\n    for (int i = 0; i \u003C TORQUE_SOURCE_COUNT; i++) {\n        if (g_torque_arbiter.requests[i].active &&\n            g_torque_arbiter.requests[i].priority > highest_priority) {\n            highest_priority = g_torque_arbiter.requests[i].priority;\n            result_torque = g_torque_arbiter.requests[i].requested_torque_nm;\n            active_source = (TorqueSource_t)i;\n        }\n    }\n\n    \u002F* Apply rate limiter for smoothness *\u002F\n    int16_t delta = result_torque - g_torque_arbiter.previous_torque_nm;\n    if (delta > TORQUE_RATE_LIMIT_NM_PER_100MS) {\n        result_torque = g_torque_arbiter.previous_torque_nm + TORQUE_RATE_LIMIT_NM_PER_100MS;\n    } else if (delta \u003C -TORQUE_RATE_LIMIT_NM_PER_100MS) {\n        result_torque = g_torque_arbiter.previous_torque_nm - TORQUE_RATE_LIMIT_NM_PER_100MS;\n    }\n\n    g_torque_arbiter.arbitrated_torque_nm = result_torque;\n    g_torque_arbiter.previous_torque_nm = result_torque;\n    g_torque_arbiter.active_source = active_source;\n\n    \u002F* Send to motor controller via CAN *\u002F\n    Rte_Write_MotorTorqueCmd_torque(result_torque);\n\n    return result_torque;\n}\n```\n\n### 2. Drive Modes (Eco\u002FSport\u002FCustom)\n```c\n\u002F* vcu_drive_modes.c - Drive mode management *\u002F\n#include \"vcu_drive_modes.h\"\n\ntypedef enum {\n    DRIVE_MODE_ECO = 0,\n    DRIVE_MODE_NORMAL,\n    DRIVE_MODE_SPORT,\n    DRIVE_MODE_CUSTOM\n} DriveMode_t;\n\ntypedef struct {\n    uint8_t max_power_percent;       \u002F* 0-100% *\u002F\n    uint8_t throttle_response;       \u002F* 0-100%, sensitivity *\u002F\n    uint8_t regen_strength;          \u002F* 0-100%, aggressive regen *\u002F\n    uint8_t ac_power_limit_percent;  \u002F* HVAC power limit *\u002F\n} DriveModeProfile_t;\n\nstatic const DriveModeProfile_t DRIVE_MODE_PROFILES[] = {\n    [DRIVE_MODE_ECO] = {\n        .max_power_percent = 70,\n        .throttle_response = 50,\n        .regen_strength = 80,\n        .ac_power_limit_percent = 50\n    },\n    [DRIVE_MODE_NORMAL] = {\n        .max_power_percent = 90,\n        .throttle_response = 70,\n        .regen_strength = 60,\n        .ac_power_limit_percent = 80\n    },\n    [DRIVE_MODE_SPORT] = {\n        .max_power_percent = 100,\n        .throttle_response = 100,\n        .regen_strength = 40,\n        .ac_power_limit_percent = 100\n    },\n    [DRIVE_MODE_CUSTOM] = {\n        .max_power_percent = 85,\n        .throttle_response = 75,\n        .regen_strength = 65,\n        .ac_power_limit_percent = 75\n    }\n};\n\nstatic DriveMode_t g_active_mode = DRIVE_MODE_NORMAL;\nstatic DriveModeProfile_t g_custom_profile;\n\nvoid VCU_DriveMode_Set(DriveMode_t mode) {\n    if (mode >= DRIVE_MODE_CUSTOM) return;\n    g_active_mode = mode;\n\n    \u002F* Apply profile to power management *\u002F\n    const DriveModeProfile_t* profile = &DRIVE_MODE_PROFILES[mode];\n\n    VCU_PowerManagement_SetMaxPower(profile->max_power_percent);\n    VCU_ThrottleMap_SetResponse(profile->throttle_response);\n    VCU_RegenBraking_SetStrength(profile->regen_strength);\n    VCU_HVAC_SetPowerLimit(profile->ac_power_limit_percent);\n\n    \u002F* Persist to EEPROM *\u002F\n    NvM_WriteBlock(NVM_BLOCK_DRIVE_MODE, &mode);\n}\n\nDriveMode_t VCU_DriveMode_Get(void) {\n    return g_active_mode;\n}\n\n\u002F* Throttle pedal mapping with drive mode response curve *\u002F\nint16_t VCU_ThrottleMap_ApplyResponse(uint8_t pedal_position_percent) {\n    const DriveModeProfile_t* profile = &DRIVE_MODE_PROFILES[g_active_mode];\n\n    \u002F* Non-linear response curve: torque = (pedal^2) * response_factor *\u002F\n    float normalized_pedal = pedal_position_percent \u002F 100.0f;\n    float response_factor = profile->throttle_response \u002F 100.0f;\n\n    \u002F* Sport mode: more aggressive curve (pedal^1.5) *\u002F\n    \u002F* Eco mode: gentler curve (pedal^2.5) *\u002F\n    float exponent = 2.0f;\n    if (g_active_mode == DRIVE_MODE_SPORT) {\n        exponent = 1.5f;\n    } else if (g_active_mode == DRIVE_MODE_ECO) {\n        exponent = 2.5f;\n    }\n\n    float torque_factor = powf(normalized_pedal, exponent) * response_factor;\n    int16_t max_torque = (MAX_TORQUE_NM * profile->max_power_percent) \u002F 100;\n\n    return (int16_t)(torque_factor * max_torque);\n}\n```\n\n### 3. Regenerative Braking Control\n```c\n\u002F* vcu_regen_braking.c - Regenerative braking with blending *\u002F\n#include \"vcu_regen_braking.h\"\n\n#define MIN_VEHICLE_SPEED_KPH 5      \u002F* Below this, friction only *\u002F\n#define MAX_REGEN_POWER_KW 80\n#define BATTERY_HIGH_SOC_LIMIT 95    \u002F* Reduce regen above 95% SOC *\u002F\n#define REGEN_BLEND_THRESHOLD_MS 200 \u002F* Blend window for smooth transition *\u002F\n\ntypedef struct {\n    uint8_t regen_strength_percent;\n    int16_t regen_torque_nm;\n    int16_t friction_brake_request_nm;\n    bool regen_available;\n    uint32_t last_blend_timestamp_ms;\n} RegenBraking_t;\n\nstatic RegenBraking_t g_regen_state = {0};\n\nbool VCU_Regen_IsAvailable(void) {\n    \u002F* Check conditions for regen availability *\u002F\n    uint8_t battery_soc = BMS_GetSOC_percent();\n    uint8_t battery_temp_c = BMS_GetTemperature_C();\n    uint16_t vehicle_speed_kph = VCU_GetVehicleSpeed_kph();\n\n    \u002F* No regen if: SOC too high, battery too cold, vehicle too slow *\u002F\n    if (battery_soc > BATTERY_HIGH_SOC_LIMIT) return false;\n    if (battery_temp_c \u003C 0) return false;  \u002F* Below 0°C, limit regen *\u002F\n    if (vehicle_speed_kph \u003C MIN_VEHICLE_SPEED_KPH) return false;\n\n    \u002F* Check motor controller readiness *\u002F\n    if (!MCU_IsRegenReady()) return false;\n\n    return true;\n}\n\nvoid VCU_Regen_CalculateBlending(uint8_t brake_pedal_percent,\n                                  int16_t* regen_torque_out,\n                                  int16_t* friction_brake_out) {\n    *regen_torque_out = 0;\n    *friction_brake_out = 0;\n\n    if (!VCU_Regen_IsAvailable()) {\n        \u002F* Full friction braking *\u002F\n        *friction_brake_out = (brake_pedal_percent * MAX_BRAKE_TORQUE_NM) \u002F 100;\n        return;\n    }\n\n    \u002F* Calculate maximum regen torque based on battery limits *\u002F\n    uint8_t battery_soc = BMS_GetSOC_percent();\n    float soc_factor = 1.0f;\n    if (battery_soc > 90) {\n        soc_factor = (100.0f - battery_soc) \u002F 10.0f;  \u002F* Linear reduction 90-100% *\u002F\n    }\n\n    int16_t max_regen_torque = (MIN_REGEN_TORQUE_NM * g_regen_state.regen_strength_percent) \u002F 100;\n    max_regen_torque = (int16_t)(max_regen_torque * soc_factor);\n\n    \u002F* Apply regen based on brake pedal position *\u002F\n    int16_t requested_brake_torque = (brake_pedal_percent * MAX_BRAKE_TORQUE_NM) \u002F 100;\n\n    if (abs(requested_brake_torque) \u003C= abs(max_regen_torque)) {\n        \u002F* Regen can handle it all *\u002F\n        *regen_torque_out = -requested_brake_torque;  \u002F* Negative = regen *\u002F\n        *friction_brake_out = 0;\n    } else {\n        \u002F* Blend regen + friction *\u002F\n        *regen_torque_out = max_regen_torque;\n        *friction_brake_out = requested_brake_torque - abs(max_regen_torque);\n    }\n\n    g_regen_state.regen_torque_nm = *regen_torque_out;\n    g_regen_state.friction_brake_request_nm = *friction_brake_out;\n}\n\n\u002F* One-pedal driving mode (aggressive regen on throttle release) *\u002F\nvoid VCU_Regen_OnePedalMode(uint8_t throttle_percent) {\n    if (throttle_percent > 5) {\n        g_regen_state.regen_torque_nm = 0;\n        return;\n    }\n\n    \u002F* Throttle released: apply regen proportional to vehicle speed *\u002F\n    uint16_t speed_kph = VCU_GetVehicleSpeed_kph();\n    float speed_factor = (speed_kph > 100) ? 1.0f : (speed_kph \u002F 100.0f);\n\n    int16_t one_pedal_regen = (int16_t)(MIN_REGEN_TORQUE_NM * 0.7f * speed_factor);\n\n    VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_DRIVER, one_pedal_regen, true);\n}\n```\n\n### 4. Traction Control Integration\n```c\n\u002F* vcu_traction_control.c - Wheel slip detection and mitigation *\u002F\n#include \"vcu_traction_control.h\"\n\n#define WHEEL_SLIP_THRESHOLD_PERCENT 15  \u002F* 15% slip triggers intervention *\u002F\n#define TC_TORQUE_REDUCTION_STEP_NM 20\n#define TC_RECOVERY_RATE_NM_PER_100MS 10\n\ntypedef struct {\n    float wheel_speeds_kph[4];  \u002F* FL, FR, RL, RR *\u002F\n    float wheel_slip_percent[4];\n    bool tc_active;\n    int16_t torque_reduction_nm;\n} TractionControl_t;\n\nstatic TractionControl_t g_tc_state = {0};\n\nvoid VCU_TractionControl_Update(void) {\n    \u002F* Read wheel speeds from ABS sensors via CAN *\u002F\n    g_tc_state.wheel_speeds_kph[0] = ABS_GetWheelSpeed_kph(WHEEL_FL);\n    g_tc_state.wheel_speeds_kph[1] = ABS_GetWheelSpeed_kph(WHEEL_FR);\n    g_tc_state.wheel_speeds_kph[2] = ABS_GetWheelSpeed_kph(WHEEL_RL);\n    g_tc_state.wheel_speeds_kph[3] = ABS_GetWheelSpeed_kph(WHEEL_RR);\n\n    \u002F* Calculate average driven wheel speed (RWD: rear wheels) *\u002F\n    float driven_avg = (g_tc_state.wheel_speeds_kph[2] +\n                        g_tc_state.wheel_speeds_kph[3]) \u002F 2.0f;\n\n    \u002F* Calculate average non-driven wheel speed (reference) *\u002F\n    float reference_avg = (g_tc_state.wheel_speeds_kph[0] +\n                           g_tc_state.wheel_speeds_kph[1]) \u002F 2.0f;\n\n    if (reference_avg \u003C 5.0f) {\n        g_tc_state.tc_active = false;\n        return;  \u002F* Vehicle stopped *\u002F\n    }\n\n    \u002F* Calculate slip percentage *\u002F\n    float slip_percent = ((driven_avg - reference_avg) \u002F reference_avg) * 100.0f;\n\n    if (slip_percent > WHEEL_SLIP_THRESHOLD_PERCENT) {\n        \u002F* Excessive slip detected: reduce torque *\u002F\n        g_tc_state.tc_active = true;\n        g_tc_state.torque_reduction_nm += TC_TORQUE_REDUCTION_STEP_NM;\n\n        \u002F* Cap reduction at 80% of requested torque *\u002F\n        int16_t driver_torque = VCU_TorqueArbiter_GetRequest(TORQUE_SOURCE_DRIVER);\n        if (g_tc_state.torque_reduction_nm > driver_torque * 0.8f) {\n            g_tc_state.torque_reduction_nm = (int16_t)(driver_torque * 0.8f);\n        }\n\n        \u002F* Override driver request *\u002F\n        int16_t limited_torque = driver_torque - g_tc_state.torque_reduction_nm;\n        VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_TRACTION_CONTROL,\n                                      limited_torque, true);\n    } else {\n        \u002F* No slip: gradually restore torque *\u002F\n        if (g_tc_state.torque_reduction_nm > 0) {\n            g_tc_state.torque_reduction_nm -= TC_RECOVERY_RATE_NM_PER_100MS;\n            if (g_tc_state.torque_reduction_nm \u003C 0) {\n                g_tc_state.torque_reduction_nm = 0;\n                g_tc_state.tc_active = false;\n                VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_TRACTION_CONTROL, 0, false);\n            }\n        }\n    }\n}\n```\n\n## AUTOSAR BSW Configuration\n\n### VCU RTE Configuration (ARXML)\n```xml\n\u003C!-- vcu_rte_configuration.arxml -->\n\u003CAUTOSAR xmlns=\"http:\u002F\u002Fautosar.org\u002Fschema\u002Fr4.0\">\n  \u003CAR-PACKAGES>\n    \u003CAR-PACKAGE>\n      \u003CSHORT-NAME>VCU_ComponentTypes\u003C\u002FSHORT-NAME>\n      \u003CELEMENTS>\n        \u003CAPPLICATION-SW-COMPONENT-TYPE>\n          \u003CSHORT-NAME>VCU_Controller\u003C\u002FSHORT-NAME>\n          \u003CPORTS>\n            \u003C!-- Required Ports (inputs) -->\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>ThrottlePedal\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FThrottlePedal_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>BrakePedal\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FBrakePedal_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>BatteryStatus\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FBatteryStatus_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>WheelSpeeds\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FWheelSpeeds_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n\n            \u003C!-- Provided Ports (outputs) -->\n            \u003CP-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>MotorTorqueCmd\u003C\u002FSHORT-NAME>\n              \u003CPROVIDED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FMotorTorqueCmd_IF\n              \u003C\u002FPROVIDED-INTERFACE-TREF>\n            \u003C\u002FP-PORT-PROTOTYPE>\n            \u003CP-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>BrakeRequest\u003C\u002FSHORT-NAME>\n              \u003CPROVIDED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FBrakeRequest_IF\n              \u003C\u002FPROVIDED-INTERFACE-TREF>\n            \u003C\u002FP-PORT-PROTOTYPE>\n            \u003CP-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>VehicleStatus\u003C\u002FSHORT-NAME>\n              \u003CPROVIDED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FVehicleStatus_IF\n              \u003C\u002FPROVIDED-INTERFACE-TREF>\n            \u003C\u002FP-PORT-PROTOTYPE>\n          \u003C\u002FPORTS>\n\n          \u003CINTERNAL-BEHAVIORS>\n            \u003CSWC-INTERNAL-BEHAVIOR>\n              \u003CSHORT-NAME>VCU_InternalBehavior\u003C\u002FSHORT-NAME>\n              \u003CRUNNABLES>\n                \u003CRUNNABLE-ENTITY>\n                  \u003CSHORT-NAME>VCU_Main_10ms\u003C\u002FSHORT-NAME>\n                  \u003CMINIMUM-START-INTERVAL>0.01\u003C\u002FMINIMUM-START-INTERVAL>\n                  \u003CCAN-BE-INVOKED-CONCURRENTLY>false\u003C\u002FCAN-BE-INVOKED-CONCURRENTLY>\n                  \u003CSYMBOL>VCU_Main_Runnable\u003C\u002FSYMBOL>\n                \u003C\u002FRUNNABLE-ENTITY>\n              \u003C\u002FRUNNABLES>\n              \u003CEVENTS>\n                \u003CTIMING-EVENT>\n                  \u003CSHORT-NAME>TimingEvent_10ms\u003C\u002FSHORT-NAME>\n                  \u003CSTART-ON-EVENT-REF DEST=\"RUNNABLE-ENTITY\">\n                    \u002FVCU_ComponentTypes\u002FVCU_Controller\u002FVCU_InternalBehavior\u002FVCU_Main_10ms\n                  \u003C\u002FSTART-ON-EVENT-REF>\n                  \u003CPERIOD>0.01\u003C\u002FPERIOD>\n                \u003C\u002FTIMING-EVENT>\n              \u003C\u002FEVENTS>\n            \u003C\u002FSWC-INTERNAL-BEHAVIOR>\n          \u003C\u002FINTERNAL-BEHAVIORS>\n        \u003C\u002FAPPLICATION-SW-COMPONENT-TYPE>\n      \u003C\u002FELEMENTS>\n    \u003C\u002FAR-PACKAGE>\n  \u003C\u002FAR-PACKAGES>\n\u003C\u002FAUTOSAR>\n```\n\n## VCU CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n    NS_DESC_\n    CM_\n    BA_DEF_\n    BA_\n    VAL_\n    CAT_DEF_\n    CAT_\n    FILTER\n    BA_DEF_DEF_\n    EV_DATA_\n    ENVVAR_DATA_\n    SGTYPE_\n    SGTYPE_VAL_\n    BA_DEF_SGTYPE_\n    BA_SGTYPE_\n    SIG_TYPE_REF_\n    VAL_TABLE_\n    SIG_GROUP_\n    SIG_VALTYPE_\n    SIGTYPE_VALTYPE_\n    BO_TX_BU_\n    BA_DEF_REL_\n    BA_REL_\n    BA_SGTYPE_REL_\n    SG_MUL_VAL_\n\nBS_:\n\nBU_: VCU MCU BMS BCM\n\n\u002F* VCU -> MCU: Motor Torque Command *\u002F\nBO_ 256 VCU_MotorCmd: 8 VCU\n SG_ VCU_TorqueRequest : 0|16@1+ (-2000,0) [-2000|4000] \"0.1Nm\"  MCU\n SG_ VCU_SpeedLimit : 16|16@1+ (0,0) [0|18000] \"0.1rpm\"  MCU\n SG_ VCU_ControlMode : 32|8@1+ (0,0) [0|3] \"\"  MCU\n SG_ VCU_TorqueValid : 40|1@1+ (0,0) [0|1] \"\"  MCU\n SG_ VCU_TorqueSource : 41|3@1+ (0,0) [0|7] \"\"  MCU\n SG_ VCU_ChecksumTorque : 56|8@1+ (0,0) [0|255] \"\"  MCU\n\n\u002F* VCU -> BCM: Brake Request *\u002F\nBO_ 257 VCU_BrakeCmd: 8 VCU\n SG_ VCU_FrictionBrake_FL : 0|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n SG_ VCU_FrictionBrake_FR : 16|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n SG_ VCU_FrictionBrake_RL : 32|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n SG_ VCU_FrictionBrake_RR : 48|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n\n\u002F* VCU -> CAN Bus: Vehicle Status *\u002F\nBO_ 258 VCU_VehicleStatus: 8 VCU\n SG_ VCU_DriveMode : 0|8@1+ (0,0) [0|3] \"\"  BCM,MCU,BMS\n SG_ VCU_TractionControlActive : 8|1@1+ (0,0) [0|1] \"\"  BCM\n SG_ VCU_RegenAvailable : 9|1@1+ (0,0) [0|1] \"\"  BCM\n SG_ VCU_PowerLimitActive : 10|1@1+ (0,0) [0|1] \"\"  BCM\n SG_ VCU_VehicleReady : 11|1@1+ (0,0) [0|1] \"\"  BCM,MCU\n SG_ VCU_EstimatedRange_km : 16|16@1+ (0,0) [0|1000] \"km\"  BCM\n\nVAL_ 256 VCU_ControlMode 0 \"Torque_Mode\" 1 \"Speed_Mode\" 2 \"Power_Mode\" 3 \"Disabled\";\nVAL_ 256 VCU_TorqueSource 0 \"Driver\" 1 \"CruiseControl\" 2 \"TractionControl\" 3 \"StabilityControl\" 4 \"PowerLimit\" 5 \"ThermalLimit\";\nVAL_ 258 VCU_DriveMode 0 \"Eco\" 1 \"Normal\" 2 \"Sport\" 3 \"Custom\";\n```\n\n## Power Distribution Strategy\n```c\n\u002F* vcu_power_distribution.c - Energy management and power budgeting *\u002F\n#include \"vcu_power_management.h\"\n\n#define BATTERY_MAX_POWER_KW 150\n#define HVAC_MAX_POWER_KW 6\n#define DCDC_MAX_POWER_KW 3\n#define AUXILIARY_MAX_POWER_KW 2\n\ntypedef struct {\n    float available_battery_power_kw;\n    float allocated_propulsion_kw;\n    float allocated_hvac_kw;\n    float allocated_auxiliary_kw;\n    bool power_limit_active;\n} PowerBudget_t;\n\nstatic PowerBudget_t g_power_budget = {0};\n\nvoid VCU_PowerManagement_Update(void) {\n    \u002F* Get battery discharge limit from BMS *\u002F\n    g_power_budget.available_battery_power_kw = BMS_GetMaxDischargePower_kW();\n\n    \u002F* Propulsion has first priority *\u002F\n    float requested_propulsion_kw = VCU_GetRequestedPropulsionPower_kW();\n\n    \u002F* HVAC second priority (can be reduced in power-limited situations) *\u002F\n    float requested_hvac_kw = HVAC_GetRequestedPower_kW();\n\n    \u002F* Allocate power with priorities *\u002F\n    float total_requested = requested_propulsion_kw + requested_hvac_kw +\n                            DCDC_MAX_POWER_KW + AUXILIARY_MAX_POWER_KW;\n\n    if (total_requested \u003C= g_power_budget.available_battery_power_kw) {\n        \u002F* No power limiting needed *\u002F\n        g_power_budget.allocated_propulsion_kw = requested_propulsion_kw;\n        g_power_budget.allocated_hvac_kw = requested_hvac_kw;\n        g_power_budget.power_limit_active = false;\n    } else {\n        \u002F* Power limiting: reduce HVAC first, then propulsion *\u002F\n        g_power_budget.power_limit_active = true;\n\n        float available_for_hvac = g_power_budget.available_battery_power_kw -\n                                    requested_propulsion_kw - DCDC_MAX_POWER_KW -\n                                    AUXILIARY_MAX_POWER_KW;\n\n        if (available_for_hvac >= requested_hvac_kw) {\n            \u002F* Can still power HVAC fully, limit propulsion *\u002F\n            g_power_budget.allocated_hvac_kw = requested_hvac_kw;\n            g_power_budget.allocated_propulsion_kw = g_power_budget.available_battery_power_kw -\n                                                      requested_hvac_kw - DCDC_MAX_POWER_KW -\n                                                      AUXILIARY_MAX_POWER_KW;\n        } else {\n            \u002F* Limit HVAC *\u002F\n            g_power_budget.allocated_hvac_kw = available_for_hvac > 0 ? available_for_hvac : 0;\n            g_power_budget.allocated_propulsion_kw = requested_propulsion_kw;\n        }\n\n        \u002F* Apply power limit to torque command *\u002F\n        int16_t limited_torque = VCU_CalculateTorqueFromPower(\n            g_power_budget.allocated_propulsion_kw);\n        VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_POWER_LIMIT, limited_torque, true);\n    }\n}\n```\n\n## ISO 26262 Safety Mechanisms\n\n### Torque Plausibility Check\n```c\n\u002F* Safety monitor for torque command plausibility *\u002F\nvoid VCU_Safety_TorquePlausibilityCheck(void) {\n    int16_t commanded_torque = VCU_TorqueArbiter_GetArbitratedTorque();\n    int16_t measured_torque = MCU_GetActualTorque();\n\n    int16_t torque_error = abs(commanded_torque - measured_torque);\n\n    if (torque_error > TORQUE_PLAUSIBILITY_THRESHOLD_NM) {\n        \u002F* Torque mismatch detected *\u002F\n        g_safety_fault_counter++;\n\n        if (g_safety_fault_counter > SAFETY_FAULT_THRESHOLD) {\n            \u002F* Enter safe state: zero torque request *\u002F\n            VCU_EnterSafeState();\n            DTC_SetFault(DTC_TORQUE_PLAUSIBILITY_FAULT);\n        }\n    } else {\n        if (g_safety_fault_counter > 0) {\n            g_safety_fault_counter--;\n        }\n    }\n}\n```\n\n## Testing Requirements\n\n### HIL Test Cases\n```python\n# vcu_hil_test.py - Hardware-in-the-Loop test suite\nimport can\nimport pytest\nimport time\n\nclass TestVCUTorqueArbiter:\n    def test_driver_torque_request_normal(self, vcu_hil):\n        \"\"\"Verify driver torque request in normal conditions\"\"\"\n        # Set throttle pedal to 50%\n        vcu_hil.set_analog_input(\"ThrottlePedal\", 2.5)  # 0-5V\n        time.sleep(0.05)\n\n        # Read CAN message VCU_MotorCmd\n        msg = vcu_hil.can_bus.recv(timeout=0.1)\n        assert msg.arbitration_id == 0x100  # 256 decimal\n\n        torque_request = int.from_bytes(msg.data[0:2], 'little', signed=True) * 0.1\n        assert 150 \u003C torque_request \u003C 250  # Expected range for 50% throttle in Normal mode\n\n    def test_traction_control_intervention(self, vcu_hil):\n        \"\"\"Verify traction control reduces torque on wheel slip\"\"\"\n        # Simulate wheel slip: driven wheels faster than reference\n        vcu_hil.inject_can_message(0x220, [0x64, 0x00, 0x64, 0x00, 0xC8, 0x00, 0xC8, 0x00])\n        # Front wheels: 100 kph, Rear wheels: 200 kph (100% slip)\n\n        time.sleep(0.2)\n\n        # Verify VCU_VehicleStatus shows TC active\n        status_msg = vcu_hil.read_can_message(0x102)\n        tc_active = (status_msg.data[1] & 0x01) == 0x01\n        assert tc_active\n\n        # Verify torque reduction\n        torque_msg = vcu_hil.read_can_message(0x100)\n        torque_source = (torque_msg.data[5] >> 1) & 0x07\n        assert torque_source == 2  # TractionControl source\n```\n\n## References\n- ISO 26262-6: Product development at the software level\n- AUTOSAR Classic Platform R20-11: RTE Specification\n- SAE J2735: Dedicated Short Range Communications (DSRC) Message Set Dictionary\n- ECE R13: Uniform provisions concerning the approval of vehicles of categories M, N and O with regard to braking\n\n## Common Issues\n- Torque command jitter due to insufficient rate limiting\n- Regen braking not blending smoothly with friction brakes\n- Traction control oscillation from aggressive intervention\n- Drive mode changes causing torque steps\n- Power limiting not respecting HVAC comfort requirements\n\n---\n\n## Vgu Gateway Architecture\n\n# VGU (Vehicle Gateway Unit) - Network Routing and Security\n\n## Overview\nThe Vehicle Gateway Unit (VGU) acts as the central network hub, routing messages between different vehicle networks (CAN-to-Ethernet, CAN-to-CAN), implementing security firewalls, handling diagnostic access (DoIP), and managing network wake-up. This skill covers production-ready gateway development with AUTOSAR COM stack.\n\n## Core Responsibilities\n\n### 1. Network Routing (CAN-to-Ethernet, CAN-to-CAN)\n```c\n\u002F* vgu_routing_engine.c - Multi-network message routing *\u002F\n#include \"vgu_routing_engine.h\"\n#include \"Com.h\"\n#include \"PduR.h\"\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n\n#define MAX_ROUTING_ENTRIES 256\n#define MAX_NETWORKS 8\n\ntypedef enum {\n    NETWORK_CAN_POWERTRAIN = 0,\n    NETWORK_CAN_CHASSIS,\n    NETWORK_CAN_BODY,\n    NETWORK_CAN_INFOTAINMENT,\n    NETWORK_ETH_BACKBONE,\n    NETWORK_LIN_DOOR,\n    NETWORK_FLEXRAY_ADAS,\n    NETWORK_INVALID\n} NetworkID_t;\n\ntypedef enum {\n    ROUTING_MODE_UNCONDITIONAL,  \u002F* Always route *\u002F\n    ROUTING_MODE_CONDITIONAL,    \u002F* Route based on vehicle mode *\u002F\n    ROUTING_MODE_FILTERED,       \u002F* Apply gateway filter *\u002F\n    ROUTING_MODE_BLOCKED         \u002F* Never route (security) *\u002F\n} RoutingMode_t;\n\ntypedef struct {\n    uint32_t source_pdu_id;\n    NetworkID_t source_network;\n    uint32_t dest_pdu_id;\n    NetworkID_t dest_network;\n    RoutingMode_t routing_mode;\n    uint16_t cycle_time_ms;       \u002F* For cyclic routing *\u002F\n    bool transform_required;      \u002F* Endianness\u002Fscaling conversion *\u002F\n    uint32_t route_count;         \u002F* Statistics *\u002F\n} RoutingEntry_t;\n\nstatic RoutingEntry_t g_routing_table[MAX_ROUTING_ENTRIES];\nstatic uint16_t g_routing_table_size = 0;\n\n\u002F* Example routing table configuration *\u002F\nstatic const RoutingEntry_t DEFAULT_ROUTING_TABLE[] = {\n    \u002F* VCU Motor Command: CAN Powertrain -> Ethernet Backbone *\u002F\n    {\n        .source_pdu_id = 0x100,\n        .source_network = NETWORK_CAN_POWERTRAIN,\n        .dest_pdu_id = 0x100,\n        .dest_network = NETWORK_ETH_BACKBONE,\n        .routing_mode = ROUTING_MODE_UNCONDITIONAL,\n        .cycle_time_ms = 10,\n        .transform_required = false\n    },\n    \u002F* BMS Battery Status: CAN Powertrain -> CAN Infotainment (for display) *\u002F\n    {\n        .source_pdu_id = 0x300,\n        .source_network = NETWORK_CAN_POWERTRAIN,\n        .dest_pdu_id = 0x300,\n        .dest_network = NETWORK_CAN_INFOTAINMENT,\n        .routing_mode = ROUTING_MODE_FILTERED,\n        .cycle_time_ms = 100,\n        .transform_required = false\n    },\n    \u002F* IVI User Input: CAN Infotainment -> Ethernet Backbone (blocked in drive) *\u002F\n    {\n        .source_pdu_id = 0x400,\n        .source_network = NETWORK_CAN_INFOTAINMENT,\n        .dest_pdu_id = 0x400,\n        .dest_network = NETWORK_ETH_BACKBONE,\n        .routing_mode = ROUTING_MODE_CONDITIONAL,\n        .cycle_time_ms = 50,\n        .transform_required = false\n    },\n    \u002F* ADAS Camera: Ethernet -> CAN Chassis (lane keeping) *\u002F\n    {\n        .source_pdu_id = 0x500,\n        .source_network = NETWORK_ETH_BACKBONE,\n        .dest_pdu_id = 0x500,\n        .dest_network = NETWORK_CAN_CHASSIS,\n        .routing_mode = ROUTING_MODE_UNCONDITIONAL,\n        .cycle_time_ms = 20,\n        .transform_required = true  \u002F* SOME\u002FIP to CAN conversion *\u002F\n    }\n};\n\nvoid VGU_RoutingEngine_Init(void) {\n    \u002F* Load default routing table *\u002F\n    g_routing_table_size = sizeof(DEFAULT_ROUTING_TABLE) \u002F sizeof(RoutingEntry_t);\n    memcpy(g_routing_table, DEFAULT_ROUTING_TABLE, sizeof(DEFAULT_ROUTING_TABLE));\n\n    \u002F* Initialize network interfaces *\u002F\n    for (int i = 0; i \u003C MAX_NETWORKS; i++) {\n        VGU_Network_Init((NetworkID_t)i);\n    }\n\n    \u002F* Load routing table from NVM if available *\u002F\n    NvM_ReadBlock(NVM_BLOCK_ROUTING_TABLE, g_routing_table);\n}\n\nStd_ReturnType VGU_RouteMessage(uint32_t source_pdu_id,\n                                 NetworkID_t source_network,\n                                 const uint8_t* data,\n                                 uint8_t length) {\n    \u002F* Find routing entry *\u002F\n    for (uint16_t i = 0; i \u003C g_routing_table_size; i++) {\n        RoutingEntry_t* entry = &g_routing_table[i];\n\n        if (entry->source_pdu_id == source_pdu_id &&\n            entry->source_network == source_network) {\n\n            \u002F* Check routing mode *\u002F\n            if (!VGU_RoutingAllowed(entry)) {\n                return E_NOT_OK;\n            }\n\n            \u002F* Apply security filter *\u002F\n            if (!VGU_SecurityFilter_Check(entry, data, length)) {\n                VGU_SecurityEvent_Log(SECURITY_EVENT_FILTER_REJECT, source_pdu_id);\n                return E_NOT_OK;\n            }\n\n            \u002F* Transform if required *\u002F\n            uint8_t transformed_data[64];\n            uint8_t transformed_length = length;\n\n            if (entry->transform_required) {\n                VGU_DataTransform(data, length, transformed_data,\n                                   &transformed_length, entry);\n            } else {\n                memcpy(transformed_data, data, length);\n            }\n\n            \u002F* Route to destination network *\u002F\n            Std_ReturnType result = VGU_Network_Transmit(\n                entry->dest_network,\n                entry->dest_pdu_id,\n                transformed_data,\n                transformed_length);\n\n            if (result == E_OK) {\n                entry->route_count++;\n            }\n\n            return result;\n        }\n    }\n\n    \u002F* No routing entry found *\u002F\n    return E_NOT_OK;\n}\n\nbool VGU_RoutingAllowed(const RoutingEntry_t* entry) {\n    switch (entry->routing_mode) {\n        case ROUTING_MODE_UNCONDITIONAL:\n            return true;\n\n        case ROUTING_MODE_CONDITIONAL:\n            \u002F* Example: block IVI messages when vehicle is driving *\u002F\n            if (entry->source_network == NETWORK_CAN_INFOTAINMENT) {\n                uint16_t vehicle_speed = VCU_GetVehicleSpeed_kph();\n                return (vehicle_speed \u003C 5);  \u002F* Only allow when stopped *\u002F\n            }\n            return true;\n\n        case ROUTING_MODE_FILTERED:\n            \u002F* Additional filtering logic *\u002F\n            return true;\n\n        case ROUTING_MODE_BLOCKED:\n            return false;\n\n        default:\n            return false;\n    }\n}\n\n\u002F* CAN-to-Ethernet transformation (CAN frame -> SOME\u002FIP) *\u002F\nvoid VGU_DataTransform_CANtoETH(const uint8_t* can_data, uint8_t can_length,\n                                 uint8_t* eth_data, uint8_t* eth_length) {\n    \u002F* SOME\u002FIP header: Service ID, Method ID, Length, Client ID, Session ID, ... *\u002F\n    uint16_t service_id = 0x1234;\n    uint16_t method_id = 0x0001;\n\n    \u002F* Build SOME\u002FIP message *\u002F\n    eth_data[0] = (service_id >> 8) & 0xFF;\n    eth_data[1] = service_id & 0xFF;\n    eth_data[2] = (method_id >> 8) & 0xFF;\n    eth_data[3] = method_id & 0xFF;\n\n    \u002F* Length field *\u002F\n    uint32_t payload_length = can_length + 8;  \u002F* Payload + SOME\u002FIP overhead *\u002F\n    eth_data[4] = (payload_length >> 24) & 0xFF;\n    eth_data[5] = (payload_length >> 16) & 0xFF;\n    eth_data[6] = (payload_length >> 8) & 0xFF;\n    eth_data[7] = payload_length & 0xFF;\n\n    \u002F* Copy CAN payload *\u002F\n    memcpy(&eth_data[16], can_data, can_length);\n\n    *eth_length = 16 + can_length;\n}\n```\n\n### 2. Security Firewall\n```c\n\u002F* vgu_security_firewall.c - Message filtering and intrusion detection *\u002F\n#include \"vgu_security_firewall.h\"\n\n#define MAX_FIREWALL_RULES 128\n#define MAX_ALLOWED_CAN_IDS 512\n#define ANOMALY_THRESHOLD 10\n\ntypedef enum {\n    FIREWALL_ACTION_ALLOW = 0,\n    FIREWALL_ACTION_BLOCK,\n    FIREWALL_ACTION_LOG,\n    FIREWALL_ACTION_ALERT\n} FirewallAction_t;\n\ntypedef struct {\n    uint32_t can_id;\n    NetworkID_t network;\n    FirewallAction_t action;\n    uint32_t min_cycle_time_ms;  \u002F* Minimum expected cycle time *\u002F\n    uint32_t max_cycle_time_ms;  \u002F* Maximum expected cycle time *\u002F\n    uint8_t expected_dlc;\n    bool require_authentication;\n} FirewallRule_t;\n\ntypedef struct {\n    uint32_t can_id;\n    uint32_t last_rx_timestamp_ms;\n    uint32_t rx_count;\n    uint32_t anomaly_count;\n} MessageMonitor_t;\n\nstatic FirewallRule_t g_firewall_rules[MAX_FIREWALL_RULES];\nstatic MessageMonitor_t g_message_monitors[MAX_ALLOWED_CAN_IDS];\n\n\u002F* Example firewall rules *\u002F\nstatic const FirewallRule_t DEFAULT_FIREWALL_RULES[] = {\n    \u002F* VCU Motor Command: strict timing, authenticated *\u002F\n    {\n        .can_id = 0x100,\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_ALLOW,\n        .min_cycle_time_ms = 8,\n        .max_cycle_time_ms = 12,\n        .expected_dlc = 8,\n        .require_authentication = true\n    },\n    \u002F* BMS Battery Status: allow with timing check *\u002F\n    {\n        .can_id = 0x300,\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_ALLOW,\n        .min_cycle_time_ms = 90,\n        .max_cycle_time_ms = 110,\n        .expected_dlc = 8,\n        .require_authentication = false\n    },\n    \u002F* Diagnostic request: block unless diagnostic session active *\u002F\n    {\n        .can_id = 0x7DF,  \u002F* OBD-II diagnostic request *\u002F\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_LOG,\n        .min_cycle_time_ms = 0,\n        .max_cycle_time_ms = 0xFFFFFFFF,\n        .expected_dlc = 8,\n        .require_authentication = true\n    },\n    \u002F* Unknown high-priority CAN ID: block and alert *\u002F\n    {\n        .can_id = 0x000,  \u002F* High priority range 0x000-0x0FF *\u002F\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_BLOCK,\n        .min_cycle_time_ms = 0,\n        .max_cycle_time_ms = 0xFFFFFFFF,\n        .expected_dlc = 0,\n        .require_authentication = false\n    }\n};\n\nvoid VGU_SecurityFirewall_Init(void) {\n    memcpy(g_firewall_rules, DEFAULT_FIREWALL_RULES, sizeof(DEFAULT_FIREWALL_RULES));\n    memset(g_message_monitors, 0, sizeof(g_message_monitors));\n}\n\nbool VGU_SecurityFilter_Check(const RoutingEntry_t* route,\n                               const uint8_t* data,\n                               uint8_t length) {\n    uint32_t can_id = route->source_pdu_id;\n    uint32_t current_time_ms = GetSystemTime_ms();\n\n    \u002F* Find firewall rule *\u002F\n    FirewallRule_t* rule = NULL;\n    for (int i = 0; i \u003C MAX_FIREWALL_RULES; i++) {\n        if (g_firewall_rules[i].can_id == can_id &&\n            g_firewall_rules[i].network == route->source_network) {\n            rule = &g_firewall_rules[i];\n            break;\n        }\n    }\n\n    if (rule == NULL) {\n        \u002F* No rule defined: default deny *\u002F\n        return false;\n    }\n\n    \u002F* Check DLC *\u002F\n    if (rule->expected_dlc > 0 && length != rule->expected_dlc) {\n        VGU_SecurityEvent_Log(SECURITY_EVENT_DLC_MISMATCH, can_id);\n        return false;\n    }\n\n    \u002F* Find message monitor entry *\u002F\n    MessageMonitor_t* monitor = NULL;\n    for (int i = 0; i \u003C MAX_ALLOWED_CAN_IDS; i++) {\n        if (g_message_monitors[i].can_id == can_id) {\n            monitor = &g_message_monitors[i];\n            break;\n        } else if (g_message_monitors[i].can_id == 0) {\n            \u002F* Create new monitor entry *\u002F\n            monitor = &g_message_monitors[i];\n            monitor->can_id = can_id;\n            break;\n        }\n    }\n\n    if (monitor != NULL) {\n        \u002F* Check cycle time *\u002F\n        if (monitor->last_rx_timestamp_ms > 0) {\n            uint32_t delta_ms = current_time_ms - monitor->last_rx_timestamp_ms;\n\n            if (delta_ms \u003C rule->min_cycle_time_ms ||\n                delta_ms > rule->max_cycle_time_ms) {\n                monitor->anomaly_count++;\n\n                if (monitor->anomaly_count > ANOMALY_THRESHOLD) {\n                    VGU_SecurityEvent_Log(SECURITY_EVENT_TIMING_VIOLATION, can_id);\n                    \u002F* Don't block, but alert *\u002F\n                }\n            } else {\n                \u002F* Reset anomaly counter on valid timing *\u002F\n                if (monitor->anomaly_count > 0) {\n                    monitor->anomaly_count--;\n                }\n            }\n        }\n\n        monitor->last_rx_timestamp_ms = current_time_ms;\n        monitor->rx_count++;\n    }\n\n    \u002F* Check authentication if required *\u002F\n    if (rule->require_authentication) {\n        if (!VGU_Security_VerifyMAC(data, length)) {\n            VGU_SecurityEvent_Log(SECURITY_EVENT_AUTH_FAIL, can_id);\n            return false;\n        }\n    }\n\n    \u002F* Apply firewall action *\u002F\n    switch (rule->action) {\n        case FIREWALL_ACTION_ALLOW:\n            return true;\n\n        case FIREWALL_ACTION_BLOCK:\n            VGU_SecurityEvent_Log(SECURITY_EVENT_BLOCKED, can_id);\n            return false;\n\n        case FIREWALL_ACTION_LOG:\n            VGU_SecurityEvent_Log(SECURITY_EVENT_LOGGED, can_id);\n            return true;\n\n        case FIREWALL_ACTION_ALERT:\n            VGU_SecurityEvent_Log(SECURITY_EVENT_ALERT, can_id);\n            return true;\n\n        default:\n            return false;\n    }\n}\n\n\u002F* SecOC (Secure Onboard Communication) - MAC verification *\u002F\nbool VGU_Security_VerifyMAC(const uint8_t* data, uint8_t length) {\n    \u002F* Extract MAC from last 8 bytes *\u002F\n    uint64_t received_mac = 0;\n    for (int i = 0; i \u003C 8; i++) {\n        received_mac = (received_mac \u003C\u003C 8) | data[length - 8 + i];\n    }\n\n    \u002F* Calculate expected MAC using CMAC-AES *\u002F\n    uint64_t calculated_mac = VGU_Crypto_CalculateMAC(data, length - 8);\n\n    return (received_mac == calculated_mac);\n}\n```\n\n### 3. Diagnostic Gateway (DoIP - Diagnostics over IP)\n```c\n\u002F* vgu_doip_gateway.c - ISO 13400 Diagnostic over IP *\u002F\n#include \"vgu_doip_gateway.h\"\n\n#define DOIP_UDP_PORT 13400\n#define DOIP_TCP_PORT 13400\n#define MAX_DOIP_CONNECTIONS 4\n\ntypedef enum {\n    DOIP_VEHICLE_ANNOUNCEMENT = 0x0004,\n    DOIP_ROUTING_ACTIVATION_REQUEST = 0x0005,\n    DOIP_ROUTING_ACTIVATION_RESPONSE = 0x0006,\n    DOIP_DIAGNOSTIC_MESSAGE = 0x8001,\n    DOIP_DIAGNOSTIC_MESSAGE_ACK = 0x8002,\n    DOIP_DIAGNOSTIC_MESSAGE_NACK = 0x8003\n} DoIPMessageType_t;\n\ntypedef struct {\n    uint8_t protocol_version;\n    uint8_t inverse_protocol_version;\n    uint16_t payload_type;\n    uint32_t payload_length;\n} DoIPHeader_t;\n\ntypedef struct {\n    int socket_fd;\n    bool active;\n    uint16_t source_address;\n    uint16_t target_address;\n    uint8_t activation_type;\n    uint32_t last_activity_ms;\n} DoIPConnection_t;\n\nstatic DoIPConnection_t g_doip_connections[MAX_DOIP_CONNECTIONS];\n\nvoid VGU_DoIP_Init(void) {\n    \u002F* Create UDP socket for vehicle announcement *\u002F\n    int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);\n    struct sockaddr_in addr = {\n        .sin_family = AF_INET,\n        .sin_port = htons(DOIP_UDP_PORT),\n        .sin_addr.s_addr = INADDR_ANY\n    };\n    bind(udp_socket, (struct sockaddr*)&addr, sizeof(addr));\n\n    \u002F* Create TCP socket for diagnostic communication *\u002F\n    int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);\n    bind(tcp_socket, (struct sockaddr*)&addr, sizeof(addr));\n    listen(tcp_socket, MAX_DOIP_CONNECTIONS);\n\n    \u002F* Send periodic vehicle announcement *\u002F\n    VGU_DoIP_SendVehicleAnnouncement(udp_socket);\n}\n\nvoid VGU_DoIP_SendVehicleAnnouncement(int udp_socket) {\n    uint8_t announcement[32];\n    DoIPHeader_t* header = (DoIPHeader_t*)announcement;\n\n    header->protocol_version = 0x02;  \u002F* ISO 13400-2:2012 *\u002F\n    header->inverse_protocol_version = 0xFD;\n    header->payload_type = htons(DOIP_VEHICLE_ANNOUNCEMENT);\n    header->payload_length = htonl(14);\n\n    \u002F* Payload: VIN (17 bytes) + Logical Address (2 bytes) + EID (6 bytes) + GID (6 bytes) *\u002F\n    const char* vin = \"1HGBH41JXMN109186\";\n    memcpy(&announcement[8], vin, 17);\n\n    uint16_t logical_address = 0x0001;  \u002F* Gateway address *\u002F\n    memcpy(&announcement[25], &logical_address, 2);\n\n    \u002F* Broadcast announcement *\u002F\n    struct sockaddr_in broadcast_addr = {\n        .sin_family = AF_INET,\n        .sin_port = htons(DOIP_UDP_PORT),\n        .sin_addr.s_addr = htonl(INADDR_BROADCAST)\n    };\n    sendto(udp_socket, announcement, 32, 0,\n           (struct sockaddr*)&broadcast_addr, sizeof(broadcast_addr));\n}\n\nvoid VGU_DoIP_HandleRoutingActivation(int tcp_socket,\n                                       const uint8_t* request,\n                                       uint16_t length) {\n    \u002F* Parse routing activation request *\u002F\n    uint16_t source_address = (request[8] \u003C\u003C 8) | request[9];\n    uint8_t activation_type = request[10];\n\n    \u002F* Find available connection slot *\u002F\n    DoIPConnection_t* conn = NULL;\n    for (int i = 0; i \u003C MAX_DOIP_CONNECTIONS; i++) {\n        if (!g_doip_connections[i].active) {\n            conn = &g_doip_connections[i];\n            break;\n        }\n    }\n\n    uint8_t response_code;\n    if (conn != NULL) {\n        conn->socket_fd = tcp_socket;\n        conn->active = true;\n        conn->source_address = source_address;\n        conn->activation_type = activation_type;\n        conn->last_activity_ms = GetSystemTime_ms();\n\n        response_code = 0x10;  \u002F* Routing successfully activated *\u002F\n    } else {\n        response_code = 0x02;  \u002F* All sockets in use *\u002F\n    }\n\n    \u002F* Send routing activation response *\u002F\n    uint8_t response[13];\n    DoIPHeader_t* header = (DoIPHeader_t*)response;\n    header->protocol_version = 0x02;\n    header->inverse_protocol_version = 0xFD;\n    header->payload_type = htons(DOIP_ROUTING_ACTIVATION_RESPONSE);\n    header->payload_length = htonl(5);\n\n    response[8] = (source_address >> 8) & 0xFF;\n    response[9] = source_address & 0xFF;\n    response[10] = 0x00;  \u002F* Logical address of gateway *\u002F\n    response[11] = 0x01;\n    response[12] = response_code;\n\n    send(tcp_socket, response, 13, 0);\n}\n\nvoid VGU_DoIP_RouteDiagnosticMessage(const uint8_t* doip_message, uint16_t length) {\n    \u002F* Extract source and target addresses *\u002F\n    uint16_t source_addr = (doip_message[8] \u003C\u003C 8) | doip_message[9];\n    uint16_t target_addr = (doip_message[10] \u003C\u003C 8) | doip_message[11];\n\n    \u002F* Extract UDS payload *\u002F\n    const uint8_t* uds_payload = &doip_message[12];\n    uint16_t uds_length = length - 12;\n\n    \u002F* Route to target ECU based on logical address *\u002F\n    NetworkID_t target_network;\n    uint32_t target_can_id;\n\n    switch (target_addr) {\n        case 0x0010:  \u002F* VCU *\u002F\n            target_network = NETWORK_CAN_POWERTRAIN;\n            target_can_id = 0x7E0;  \u002F* VCU diagnostic address *\u002F\n            break;\n        case 0x0020:  \u002F* BMS *\u002F\n            target_network = NETWORK_CAN_POWERTRAIN;\n            target_can_id = 0x7E1;\n            break;\n        case 0x0030:  \u002F* MCU *\u002F\n            target_network = NETWORK_CAN_POWERTRAIN;\n            target_can_id = 0x7E2;\n            break;\n        default:\n            \u002F* Unknown target *\u002F\n            return;\n    }\n\n    \u002F* Send diagnostic request over CAN *\u002F\n    VGU_Network_Transmit(target_network, target_can_id, uds_payload, uds_length);\n}\n```\n\n### 4. Gateway Wake-Up Management\n```c\n\u002F* vgu_wakeup_management.c - Network wake-up and power management *\u002F\n#include \"vgu_wakeup_management.h\"\n\ntypedef enum {\n    WAKEUP_SOURCE_CAN_POWERTRAIN = 0,\n    WAKEUP_SOURCE_CAN_CHASSIS,\n    WAKEUP_SOURCE_LIN_DOOR,\n    WAKEUP_SOURCE_ETHERNET,\n    WAKEUP_SOURCE_TIMER,\n    WAKEUP_SOURCE_IGNITION,\n    WAKEUP_SOURCE_COUNT\n} WakeupSource_t;\n\ntypedef struct {\n    bool wakeup_enabled[WAKEUP_SOURCE_COUNT];\n    WakeupSource_t last_wakeup_source;\n    uint32_t wakeup_timestamp_ms;\n} WakeupState_t;\n\nstatic WakeupState_t g_wakeup_state = {0};\n\nvoid VGU_WakeupManagement_Init(void) {\n    \u002F* Enable relevant wakeup sources *\u002F\n    g_wakeup_state.wakeup_enabled[WAKEUP_SOURCE_CAN_POWERTRAIN] = true;\n    g_wakeup_state.wakeup_enabled[WAKEUP_SOURCE_LIN_DOOR] = true;\n    g_wakeup_state.wakeup_enabled[WAKEUP_SOURCE_IGNITION] = true;\n\n    \u002F* Configure CAN transceivers for selective wake-up *\u002F\n    CanTrcv_SetOpMode(CAN_POWERTRAIN, CANTRCV_WUMODE_ENABLE);\n    CanTrcv_SetOpMode(CAN_CHASSIS, CANTRCV_WUMODE_ENABLE);\n}\n\nvoid VGU_WakeupManagement_OnWakeup(WakeupSource_t source) {\n    g_wakeup_state.last_wakeup_source = source;\n    g_wakeup_state.wakeup_timestamp_ms = GetSystemTime_ms();\n\n    \u002F* Notify EcuM of wakeup event *\u002F\n    EcuM_SetWakeupEvent((EcuM_WakeupSourceType)(1 \u003C\u003C source));\n\n    \u002F* Start network initialization sequence based on wakeup source *\u002F\n    switch (source) {\n        case WAKEUP_SOURCE_CAN_POWERTRAIN:\n            \u002F* High-priority startup: VCU, BMS, MCU needed *\u002F\n            VGU_Network_Start(NETWORK_CAN_POWERTRAIN);\n            VGU_Network_Start(NETWORK_CAN_CHASSIS);\n            break;\n\n        case WAKEUP_SOURCE_LIN_DOOR:\n            \u002F* Body network startup: BCM, door modules *\u002F\n            VGU_Network_Start(NETWORK_CAN_BODY);\n            VGU_Network_Start(NETWORK_LIN_DOOR);\n            break;\n\n        case WAKEUP_SOURCE_IGNITION:\n            \u002F* Full network startup *\u002F\n            for (NetworkID_t net = 0; net \u003C NETWORK_INVALID; net++) {\n                VGU_Network_Start(net);\n            }\n            break;\n\n        default:\n            break;\n    }\n}\n\nvoid VGU_WakeupManagement_EnterSleep(void) {\n    \u002F* Shutdown sequence: least critical networks first *\u002F\n    VGU_Network_Stop(NETWORK_CAN_INFOTAINMENT);\n    VGU_Network_Stop(NETWORK_CAN_BODY);\n\n    \u002F* Wait for pending transmissions *\u002F\n    while (VGU_Network_HasPendingTx(NETWORK_CAN_CHASSIS)) {\n        OsTask_Sleep(10);\n    }\n\n    VGU_Network_Stop(NETWORK_CAN_CHASSIS);\n\n    \u002F* Powertrain network last (safety-critical) *\u002F\n    VGU_Network_Stop(NETWORK_CAN_POWERTRAIN);\n\n    \u002F* Configure transceivers for wake-up *\u002F\n    CanTrcv_SetOpMode(CAN_POWERTRAIN, CANTRCV_WUMODE_ENABLE);\n\n    \u002F* Enter low-power mode *\u002F\n    Mcu_SetMode(MCU_MODE_SLEEP);\n}\n```\n\n## AUTOSAR COM Stack Configuration\n\n### Gateway PDU Router (ARXML)\n```xml\n\u003C!-- vgu_pdur_configuration.arxml -->\n\u003CAUTOSAR xmlns=\"http:\u002F\u002Fautosar.org\u002Fschema\u002Fr4.0\">\n  \u003CAR-PACKAGES>\n    \u003CAR-PACKAGE>\n      \u003CSHORT-NAME>PduR_RoutingTables\u003C\u002FSHORT-NAME>\n      \u003CELEMENTS>\n        \u003CPDU-R-ROUTING-TABLE>\n          \u003CSHORT-NAME>VGU_RoutingTable\u003C\u002FSHORT-NAME>\n          \u003CROUTING-PATHS>\n            \u003C!-- CAN Powertrain -> Ethernet Backbone -->\n            \u003CPDU-R-ROUTING-PATH>\n              \u003CSHORT-NAME>VCU_MotorCmd_CANtoETH\u003C\u002FSHORT-NAME>\n              \u003CPDU-R-SOURCE-PDU-REF DEST=\"I-PDU\">\n                \u002FCAN_Powertrain\u002FVCU_MotorCmd\n              \u003C\u002FPDU-R-SOURCE-PDU-REF>\n              \u003CPDU-R-DESTINATION-PDU-REF DEST=\"I-PDU\">\n                \u002FETH_Backbone\u002FVCU_MotorCmd_ETH\n              \u003C\u002FPDU-R-DESTINATION-PDU-REF>\n              \u003CPDU-R-DEFAULT-VALUE>0\u003C\u002FPDU-R-DEFAULT-VALUE>\n            \u003C\u002FPDU-R-ROUTING-PATH>\n\n            \u003C!-- Ethernet -> CAN Chassis (ADAS commands) -->\n            \u003CPDU-R-ROUTING-PATH>\n              \u003CSHORT-NAME>ADAS_SteeringCmd_ETHtoGAN\u003C\u002FSHORT-NAME>\n              \u003CPDU-R-SOURCE-PDU-REF DEST=\"I-PDU\">\n                \u002FETH_Backbone\u002FADAS_SteeringCmd\n              \u003C\u002FPDU-R-SOURCE-PDU-REF>\n              \u003CPDU-R-DESTINATION-PDU-REF DEST=\"I-PDU\">\n                \u002FCAN_Chassis\u002FADAS_SteeringCmd_CAN\n              \u003C\u002FPDU-R-DESTINATION-PDU-REF>\n              \u003CPDU-R-DEFAULT-VALUE>0\u003C\u002FPDU-R-DEFAULT-VALUE>\n            \u003C\u002FPDU-R-ROUTING-PATH>\n          \u003C\u002FROUTING-PATHS>\n        \u003C\u002FPDU-R-ROUTING-TABLE>\n      \u003C\u002FELEMENTS>\n    \u003C\u002FAR-PACKAGE>\n  \u003C\u002FAR-PACKAGES>\n\u003C\u002FAUTOSAR>\n```\n\n## VGU Network Configuration (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: VGU VCU BMS MCU BCM IVI\n\n\u002F* Gateway Status Message *\u002F\nBO_ 1024 VGU_Status: 8 VGU\n SG_ VGU_NetworkStatus_Powertrain : 0|2@1+ (0,0) [0|3] \"\"  VCU,BMS,MCU\n SG_ VGU_NetworkStatus_Chassis : 2|2@1+ (0,0) [0|3] \"\"  BCM\n SG_ VGU_NetworkStatus_Body : 4|2@1+ (0,0) [0|3] \"\"  BCM\n SG_ VGU_NetworkStatus_Infotainment : 6|2@1+ (0,0) [0|3] \"\"  IVI\n SG_ VGU_NetworkStatus_Ethernet : 8|2@1+ (0,0) [0|3] \"\"  VCU,IVI\n SG_ VGU_RoutingActive : 10|1@1+ (0,0) [0|1] \"\"  ALL\n SG_ VGU_FirewallActive : 11|1@1+ (0,0) [0|1] \"\"  ALL\n SG_ VGU_DiagnosticSessionActive : 12|1@1+ (0,0) [0|1] \"\"  ALL\n SG_ VGU_SecurityAnomalyCount : 16|16@1+ (0,0) [0|65535] \"\"  ALL\n SG_ VGU_RoutedMessageCount : 32|32@1+ (0,0) [0|4294967295] \"\"  ALL\n\nVAL_ 1024 VGU_NetworkStatus_Powertrain 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Chassis 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Body 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Infotainment 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Ethernet 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\n```\n\n## Testing Requirements\n\n### Gateway HIL Test\n```python\n# vgu_hil_test.py - Hardware-in-the-Loop testing for VGU\nimport can\nimport socket\nimport pytest\n\nclass TestVGURouting:\n    def test_can_to_ethernet_routing(self, vgu_hil):\n        \"\"\"Verify CAN message is routed to Ethernet\"\"\"\n        # Send VCU_MotorCmd on CAN Powertrain\n        can_msg = can.Message(arbitration_id=0x100,\n                               data=[0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xAB],\n                               is_extended_id=False)\n        vgu_hil.can_powertrain.send(can_msg)\n\n        # Verify message appears on Ethernet backbone (SOME\u002FIP)\n        eth_packet = vgu_hil.eth_backbone.recv(timeout=0.1)\n        assert eth_packet is not None\n        assert eth_packet[0:2] == b'\\x12\\x34'  # Service ID\n\n    def test_security_firewall_blocks_invalid_dlc(self, vgu_hil):\n        \"\"\"Verify firewall blocks message with wrong DLC\"\"\"\n        # Send message with incorrect DLC\n        invalid_msg = can.Message(arbitration_id=0x100,\n                                   data=[0x64, 0x00],  # DLC=2, expected=8\n                                   is_extended_id=False)\n        vgu_hil.can_powertrain.send(invalid_msg)\n\n        # Verify VGU logs security event\n        security_log = vgu_hil.read_can_message(0x400, timeout=0.1)\n        assert security_log.data[0] == 0x01  # DLC_MISMATCH event\n\n        # Verify message NOT routed to Ethernet\n        eth_packet = vgu_hil.eth_backbone.recv(timeout=0.1)\n        assert eth_packet is None\n\n    def test_doip_routing_activation(self, vgu_hil):\n        \"\"\"Verify DoIP routing activation over TCP\"\"\"\n        # Connect to DoIP port\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        sock.connect((\"192.168.1.100\", 13400))\n\n        # Send routing activation request\n        activation_request = bytes([\n            0x02, 0xFD,  # Protocol version\n            0x00, 0x05,  # Payload type: Routing Activation Request\n            0x00, 0x00, 0x00, 0x07,  # Payload length\n            0x0E, 0x80,  # Source address (tester)\n            0x00,        # Activation type\n            0x00, 0x00, 0x00, 0x00  # Reserved\n        ])\n        sock.send(activation_request)\n\n        # Receive routing activation response\n        response = sock.recv(13)\n        assert len(response) == 13\n        assert response[2:4] == b'\\x00\\x06'  # Routing Activation Response\n        assert response[12] == 0x10  # Response code: Successfully activated\n\n        sock.close()\n```\n\n## References\n- ISO 13400: Diagnostic communication over Internet Protocol (DoIP)\n- AUTOSAR Classic Platform R20-11: PDU Router Specification\n- SAE J1939: Serial Control and Communications Heavy Duty Vehicle Network\n- IEEE 802.1Q: Virtual LANs and Network Segmentation\n- ISO 14229-1: Unified Diagnostic Services (UDS)\n\n## Common Issues\n- Message routing latency causing control delays\n- Firewall false positives blocking legitimate messages\n- DoIP connection timeout during long diagnostic sessions\n- Wake-up signal not propagating across networks\n- Ethernet packet loss during high CAN traffic bursts\n","# Automotive Ecu Systems\n\n## Bcm Body Control\n\n# BCM (Body Control Module) - Comfort and Convenience Systems\n\n## Overview\nThe Body Control Unit (BCM) manages exterior\u002Finterior lighting, HVAC integration, door locks, windows, wipers, keyless entry, anti-theft systems, and power distribution across body electronics. This skill covers production-ready BCM development with LIN bus mastering.\n\n## Core Responsibilities\n\n### 1. Exterior\u002FInterior Lighting Control\n```c\n\u002F* bcm_lighting_control.c - Comprehensive lighting management *\u002F\n#include \"bcm_lighting_control.h\"\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n\n#define PWM_FREQUENCY_HZ 1000\n#define DIM_STEP_PERCENT 5\n#define AUTO_HEADLIGHT_THRESHOLD_LUX 100\n\ntypedef enum {\n    LIGHT_MODE_OFF = 0,\n    LIGHT_MODE_PARKING,\n    LIGHT_MODE_DAYTIME_RUNNING,\n    LIGHT_MODE_LOW_BEAM,\n    LIGHT_MODE_HIGH_BEAM,\n    LIGHT_MODE_AUTO\n} HeadlightMode_t;\n\ntypedef struct {\n    bool left_turn_signal_active;\n    bool right_turn_signal_active;\n    bool hazard_active;\n    uint8_t turn_signal_phase;  \u002F* 0-100% for flashing *\u002F\n    uint32_t last_toggle_ms;\n} TurnSignalState_t;\n\ntypedef struct {\n    HeadlightMode_t mode;\n    uint8_t brightness_percent;\n    bool high_beam_assist_active;\n    bool adaptive_lighting_active;\n} HeadlightState_t;\n\nstatic TurnSignalState_t g_turn_signals = {0};\nstatic HeadlightState_t g_headlights = {0};\n\nvoid BCM_Lighting_Init(void) {\n    \u002F* Initialize PWM channels for LED control *\u002F\n    PWM_Init(PWM_CHANNEL_LEFT_HEADLIGHT, PWM_FREQUENCY_HZ);\n    PWM_Init(PWM_CHANNEL_RIGHT_HEADLIGHT, PWM_FREQUENCY_HZ);\n    PWM_Init(PWM_CHANNEL_DOME_LIGHT, PWM_FREQUENCY_HZ);\n    PWM_Init(PWM_CHANNEL_AMBIENT_LIGHT, PWM_FREQUENCY_HZ);\n\n    \u002F* Set initial state *\u002F\n    g_headlights.mode = LIGHT_MODE_OFF;\n    g_headlights.brightness_percent = 100;\n\n    \u002F* Load saved settings from EEPROM *\u002F\n    NvM_ReadBlock(NVM_BLOCK_LIGHTING_SETTINGS, &g_headlights);\n}\n\nvoid BCM_TurnSignals_Update(void) {\n    uint32_t current_time = GetSystemTime_ms();\n\n    \u002F* Flash at 1 Hz (500ms on, 500ms off) *\u002F\n    if ((current_time - g_turn_signals.last_toggle_ms) > 500) {\n        g_turn_signals.turn_signal_phase = (g_turn_signals.turn_signal_phase == 0) ? 100 : 0;\n        g_turn_signals.last_toggle_ms = current_time;\n    }\n\n    \u002F* Left turn signal *\u002F\n    if (g_turn_signals.left_turn_signal_active || g_turn_signals.hazard_active) {\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_FRONT, g_turn_signals.turn_signal_phase);\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_REAR, g_turn_signals.turn_signal_phase);\n    } else {\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_FRONT, 0);\n        PWM_SetDutyCycle(PWM_CHANNEL_LEFT_TURN_REAR, 0);\n    }\n\n    \u002F* Right turn signal *\u002F\n    if (g_turn_signals.right_turn_signal_active || g_turn_signals.hazard_active) {\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_FRONT, g_turn_signals.turn_signal_phase);\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_REAR, g_turn_signals.turn_signal_phase);\n    } else {\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_FRONT, 0);\n        PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_TURN_REAR, 0);\n    }\n}\n\nvoid BCM_Headlights_Update(void) {\n    uint16_t ambient_light_lux = BCM_LightSensor_Read();\n\n    switch (g_headlights.mode) {\n        case LIGHT_MODE_OFF:\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 0);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 0);\n            break;\n\n        case LIGHT_MODE_PARKING:\n            \u002F* 20% brightness for parking lights *\u002F\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 20);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 20);\n            break;\n\n        case LIGHT_MODE_DAYTIME_RUNNING:\n            \u002F* 50% brightness for DRL *\u002F\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 50);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 50);\n            break;\n\n        case LIGHT_MODE_LOW_BEAM:\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, g_headlights.brightness_percent);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, g_headlights.brightness_percent);\n            break;\n\n        case LIGHT_MODE_HIGH_BEAM:\n            \u002F* Full brightness for high beam *\u002F\n            PWM_SetDutyCycle(PWM_CHANNEL_LEFT_HEADLIGHT, 100);\n            PWM_SetDutyCycle(PWM_CHANNEL_RIGHT_HEADLIGHT, 100);\n            PWM_SetDutyCycle(PWM_CHANNEL_HIGH_BEAM, 100);\n            break;\n\n        case LIGHT_MODE_AUTO:\n            \u002F* Automatic headlight control based on ambient light *\u002F\n            if (ambient_light_lux \u003C AUTO_HEADLIGHT_THRESHOLD_LUX) {\n                \u002F* Dark: enable low beams *\u002F\n                g_headlights.mode = LIGHT_MODE_LOW_BEAM;\n            } else {\n                \u002F* Bright: enable DRL only *\u002F\n                g_headlights.mode = LIGHT_MODE_DAYTIME_RUNNING;\n            }\n            break;\n    }\n\n    \u002F* High beam assist: automatically switch to low beam when oncoming traffic detected *\u002F\n    if (g_headlights.high_beam_assist_active && g_headlights.mode == LIGHT_MODE_HIGH_BEAM) {\n        bool oncoming_detected = ADAS_Camera_DetectOncomingVehicle();\n        if (oncoming_detected) {\n            g_headlights.mode = LIGHT_MODE_LOW_BEAM;\n        }\n    }\n}\n\n\u002F* Interior dome light with fade-in\u002Ffade-out *\u002F\nvoid BCM_DomeLight_SetState(bool on, bool fade) {\n    static uint8_t current_brightness = 0;\n    uint8_t target_brightness = on ? 100 : 0;\n\n    if (fade) {\n        \u002F* Fade gradually *\u002F\n        while (current_brightness != target_brightness) {\n            if (current_brightness \u003C target_brightness) {\n                current_brightness += DIM_STEP_PERCENT;\n            } else {\n                current_brightness -= DIM_STEP_PERCENT;\n            }\n\n            PWM_SetDutyCycle(PWM_CHANNEL_DOME_LIGHT, current_brightness);\n            OsTask_Sleep(50);  \u002F* 50ms steps for smooth fade *\u002F\n        }\n    } else {\n        \u002F* Immediate switch *\u002F\n        current_brightness = target_brightness;\n        PWM_SetDutyCycle(PWM_CHANNEL_DOME_LIGHT, current_brightness);\n    }\n}\n```\n\n### 2. Door Lock\u002FUnlock and Keyless Entry\n```c\n\u002F* bcm_door_control.c - Central locking and keyless entry *\u002F\n#include \"bcm_door_control.h\"\n\n#define KEYFOB_UNLOCK_TIMEOUT_MS 3000\n#define AUTO_LOCK_SPEED_THRESHOLD_KPH 10\n#define PASSIVE_ENTRY_RANGE_M 2.0\n\ntypedef enum {\n    DOOR_FL = 0,\n    DOOR_FR,\n    DOOR_RL,\n    DOOR_RR,\n    DOOR_TRUNK,\n    DOOR_COUNT\n} DoorID_t;\n\ntypedef struct {\n    bool locked;\n    bool open;\n    uint32_t last_lock_timestamp_ms;\n} DoorState_t;\n\ntypedef struct {\n    uint32_t keyfob_id;\n    int8_t rssi_dbm;\n    float distance_m;  \u002F* Estimated from RSSI *\u002F\n    bool authenticated;\n} KeyFobState_t;\n\nstatic DoorState_t g_doors[DOOR_COUNT] = {0};\nstatic KeyFobState_t g_active_keyfob = {0};\n\nvoid BCM_DoorControl_Init(void) {\n    \u002F* Initialize door lock actuators *\u002F\n    for (int i = 0; i \u003C DOOR_COUNT; i++) {\n        GPIO_ConfigOutput(DOOR_LOCK_PINS[i]);\n        g_doors[i].locked = true;\n    }\n\n    \u002F* Initialize door open sensors (switches) *\u002F\n    for (int i = 0; i \u003C DOOR_COUNT; i++) {\n        GPIO_ConfigInput(DOOR_SWITCH_PINS[i], GPIO_PULL_UP);\n    }\n\n    \u002F* Initialize BLE for passive keyless entry *\u002F\n    BLE_Init();\n    BLE_StartAdvertising(\"VehicleKey\");\n}\n\nvoid BCM_DoorControl_LockAll(void) {\n    for (int i = 0; i \u003C DOOR_COUNT; i++) {\n        if (!g_doors[i].locked) {\n            \u002F* Activate lock actuator (pulse for 500ms) *\u002F\n            GPIO_Set(DOOR_LOCK_PINS[i], true);\n            OsTask_Sleep(500);\n            GPIO_Set(DOOR_LOCK_PINS[i], false);\n\n            g_doors[i].locked = true;\n            g_doors[i].last_lock_timestamp_ms = GetSystemTime_ms();\n        }\n    }\n\n    \u002F* Chirp horn once to confirm lock *\u002F\n    BCM_Horn_Chirp(1);\n\n    \u002F* Flash turn signals once *\u002F\n    BCM_TurnSignals_Flash(1);\n}\n\nvoid BCM_DoorControl_UnlockAll(void) {\n    \u002F* Unlock driver door first (common in luxury vehicles) *\u002F\n    BCM_DoorControl_UnlockSingle(DOOR_FL);\n\n    \u002F* Wait 2 seconds, then unlock all if button pressed again *\u002F\n    uint32_t start_time = GetSystemTime_ms();\n    while ((GetSystemTime_ms() - start_time) \u003C 2000) {\n        if (KeyFob_ButtonPressed(KEYFOB_BUTTON_UNLOCK)) {\n            \u002F* Second press: unlock all doors *\u002F\n            for (int i = 0; i \u003C DOOR_COUNT; i++) {\n                BCM_DoorControl_UnlockSingle((DoorID_t)i);\n            }\n            break;\n        }\n        OsTask_Sleep(10);\n    }\n\n    \u002F* Flash turn signals twice *\u002F\n    BCM_TurnSignals_Flash(2);\n}\n\nvoid BCM_DoorControl_UnlockSingle(DoorID_t door) {\n    if (g_doors[door].locked) {\n        \u002F* Activate unlock actuator *\u002F\n        GPIO_Set(DOOR_UNLOCK_PINS[door], true);\n        OsTask_Sleep(500);\n        GPIO_Set(DOOR_UNLOCK_PINS[door], false);\n\n        g_doors[door].locked = false;\n    }\n}\n\n\u002F* Passive keyless entry: unlock when approaching with authenticated key *\u002F\nvoid BCM_PassiveEntry_Update(void) {\n    \u002F* Scan for BLE key fobs *\u002F\n    if (BLE_ScanForDevice(g_active_keyfob.keyfob_id)) {\n        g_active_keyfob.rssi_dbm = BLE_GetRSSI();\n\n        \u002F* Estimate distance from RSSI (simplified model) *\u002F\n        g_active_keyfob.distance_m = pow(10, (-59 - g_active_keyfob.rssi_dbm) \u002F (10 * 2.0));\n\n        \u002F* Authenticate key fob *\u002F\n        if (!g_active_keyfob.authenticated) {\n            uint8_t challenge[16];\n            uint8_t response[16];\n\n            BCM_Crypto_GenerateChallenge(challenge);\n            BLE_SendChallenge(challenge);\n\n            if (BLE_ReceiveResponse(response) &&\n                BCM_Crypto_VerifyResponse(challenge, response)) {\n                g_active_keyfob.authenticated = true;\n            }\n        }\n\n        \u002F* Unlock if authenticated and within range *\u002F\n        if (g_active_keyfob.authenticated &&\n            g_active_keyfob.distance_m \u003C PASSIVE_ENTRY_RANGE_M) {\n            \u002F* Check if door handle touched (capacitive sensor) *\u002F\n            if (GPIO_Read(DOOR_HANDLE_SENSOR_FL)) {\n                BCM_DoorControl_UnlockSingle(DOOR_FL);\n            }\n        }\n    }\n}\n\n\u002F* Auto-lock when driving *\u002F\nvoid BCM_AutoLock_Update(void) {\n    uint16_t vehicle_speed = VCU_GetVehicleSpeed_kph();\n\n    if (vehicle_speed > AUTO_LOCK_SPEED_THRESHOLD_KPH) {\n        \u002F* Vehicle is moving: auto-lock all doors *\u002F\n        bool any_unlocked = false;\n        for (int i = 0; i \u003C DOOR_COUNT; i++) {\n            if (!g_doors[i].locked) {\n                any_unlocked = true;\n                break;\n            }\n        }\n\n        if (any_unlocked) {\n            BCM_DoorControl_LockAll();\n        }\n    }\n}\n```\n\n### 3. Window Control with Anti-Pinch\n```c\n\u002F* bcm_window_control.c - Power window management with anti-pinch *\u002F\n#include \"bcm_window_control.h\"\n\n#define WINDOW_FL 0\n#define WINDOW_FR 1\n#define WINDOW_RL 2\n#define WINDOW_RR 3\n#define WINDOW_COUNT 4\n\n#define ANTI_PINCH_FORCE_THRESHOLD_N 100\n#define WINDOW_POSITION_SAMPLES 10\n\ntypedef enum {\n    WINDOW_STATE_STOPPED = 0,\n    WINDOW_STATE_MOVING_UP,\n    WINDOW_STATE_MOVING_DOWN,\n    WINDOW_STATE_PINCH_DETECTED\n} WindowState_t;\n\ntypedef struct {\n    WindowState_t state;\n    uint8_t position_percent;  \u002F* 0=closed, 100=fully open *\u002F\n    uint16_t motor_current_ma;\n    bool one_touch_up_active;\n    bool one_touch_down_active;\n} WindowControl_t;\n\nstatic WindowControl_t g_windows[WINDOW_COUNT] = {0};\n\nvoid BCM_WindowControl_Init(void) {\n    \u002F* Initialize window motor drivers (H-bridge) *\u002F\n    for (int i = 0; i \u003C WINDOW_COUNT; i++) {\n        GPIO_ConfigOutput(WINDOW_MOTOR_UP_PINS[i]);\n        GPIO_ConfigOutput(WINDOW_MOTOR_DOWN_PINS[i]);\n    }\n\n    \u002F* Initialize window position sensors (Hall effect) *\u002F\n    for (int i = 0; i \u003C WINDOW_COUNT; i++) {\n        ADC_ConfigChannel(WINDOW_POSITION_ADC_CHANNELS[i]);\n    }\n\n    \u002F* Initialize current sensing for anti-pinch *\u002F\n    for (int i = 0; i \u003C WINDOW_COUNT; i++) {\n        ADC_ConfigChannel(WINDOW_CURRENT_ADC_CHANNELS[i]);\n    }\n}\n\nvoid BCM_Window_MoveUp(uint8_t window_id) {\n    if (window_id >= WINDOW_COUNT) return;\n\n    WindowControl_t* window = &g_windows[window_id];\n\n    if (window->position_percent == 0) {\n        return;  \u002F* Already fully closed *\u002F\n    }\n\n    \u002F* Activate motor upward *\u002F\n    GPIO_Set(WINDOW_MOTOR_UP_PINS[window_id], true);\n    GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], false);\n\n    window->state = WINDOW_STATE_MOVING_UP;\n}\n\nvoid BCM_Window_MoveDown(uint8_t window_id) {\n    if (window_id >= WINDOW_COUNT) return;\n\n    WindowControl_t* window = &g_windows[window_id];\n\n    if (window->position_percent == 100) {\n        return;  \u002F* Already fully open *\u002F\n    }\n\n    \u002F* Activate motor downward *\u002F\n    GPIO_Set(WINDOW_MOTOR_UP_PINS[window_id], false);\n    GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], true);\n\n    window->state = WINDOW_STATE_MOVING_DOWN;\n}\n\nvoid BCM_Window_Stop(uint8_t window_id) {\n    if (window_id >= WINDOW_COUNT) return;\n\n    \u002F* Stop motor *\u002F\n    GPIO_Set(WINDOW_MOTOR_UP_PINS[window_id], false);\n    GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], false);\n\n    g_windows[window_id].state = WINDOW_STATE_STOPPED;\n}\n\n\u002F* Anti-pinch detection: monitor motor current during closing *\u002F\nvoid BCM_Window_AntiPinchUpdate(uint8_t window_id) {\n    WindowControl_t* window = &g_windows[window_id];\n\n    if (window->state != WINDOW_STATE_MOVING_UP) {\n        return;  \u002F* Only check during closing *\u002F\n    }\n\n    \u002F* Read motor current *\u002F\n    uint16_t adc_value = ADC_Read(WINDOW_CURRENT_ADC_CHANNELS[window_id]);\n    window->motor_current_ma = (adc_value * 5000) \u002F 4096;  \u002F* 12-bit ADC, 0-5A range *\u002F\n\n    \u002F* Detect excessive current (indicates obstruction) *\u002F\n    if (window->motor_current_ma > ANTI_PINCH_FORCE_THRESHOLD_N) {\n        \u002F* Pinch detected: reverse window *\u002F\n        window->state = WINDOW_STATE_PINCH_DETECTED;\n\n        BCM_Window_Stop(window_id);\n        OsTask_Sleep(100);\n\n        \u002F* Move down slightly to release obstruction *\u002F\n        GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], true);\n        OsTask_Sleep(500);\n        GPIO_Set(WINDOW_MOTOR_DOWN_PINS[window_id], false);\n\n        window->state = WINDOW_STATE_STOPPED;\n\n        \u002F* Log event *\u002F\n        DTC_SetFault(DTC_WINDOW_ANTI_PINCH_TRIGGERED + window_id);\n    }\n}\n\n\u002F* One-touch up\u002Fdown *\u002F\nvoid BCM_Window_OneTouchUp(uint8_t window_id) {\n    g_windows[window_id].one_touch_up_active = true;\n\n    while (g_windows[window_id].position_percent > 0 &&\n           g_windows[window_id].state != WINDOW_STATE_PINCH_DETECTED) {\n        BCM_Window_MoveUp(window_id);\n        BCM_Window_UpdatePosition(window_id);\n        BCM_Window_AntiPinchUpdate(window_id);\n        OsTask_Sleep(10);\n    }\n\n    BCM_Window_Stop(window_id);\n    g_windows[window_id].one_touch_up_active = false;\n}\n```\n\n### 4. LIN Bus Mastering (Door Modules)\n```c\n\u002F* bcm_lin_master.c - LIN bus control for door modules *\u002F\n#include \"bcm_lin_master.h\"\n\n#define LIN_BAUDRATE 19200\n#define LIN_BREAK_DURATION_US 750\n#define LIN_FRAME_TIMEOUT_MS 50\n\ntypedef struct {\n    uint8_t frame_id;\n    uint8_t data[8];\n    uint8_t length;\n    uint8_t checksum;\n} LINFrame_t;\n\n\u002F* Door module addresses *\u002F\n#define LIN_DOOR_FL_ID 0x01\n#define LIN_DOOR_FR_ID 0x02\n#define LIN_DOOR_RL_ID 0x03\n#define LIN_DOOR_RR_ID 0x04\n\nvoid BCM_LIN_Init(void) {\n    \u002F* Configure UART for LIN *\u002F\n    UART_Init(LIN_UART_PORT, LIN_BAUDRATE);\n    UART_SetMode(LIN_UART_PORT, UART_MODE_LIN);\n}\n\nvoid BCM_LIN_SendBreak(void) {\n    \u002F* Generate LIN break field (dominant for 750µs) *\u002F\n    GPIO_Set(LIN_TX_PIN, false);\n    usleep(LIN_BREAK_DURATION_US);\n    GPIO_Set(LIN_TX_PIN, true);\n}\n\nbool BCM_LIN_SendFrame(const LINFrame_t* frame) {\n    \u002F* Send break + sync byte + frame ID *\u002F\n    BCM_LIN_SendBreak();\n    UART_WriteByte(LIN_UART_PORT, 0x55);  \u002F* Sync byte *\u002F\n    UART_WriteByte(LIN_UART_PORT, frame->frame_id);\n\n    \u002F* Send data *\u002F\n    for (int i = 0; i \u003C frame->length; i++) {\n        UART_WriteByte(LIN_UART_PORT, frame->data[i]);\n    }\n\n    \u002F* Send checksum *\u002F\n    UART_WriteByte(LIN_UART_PORT, frame->checksum);\n\n    return true;\n}\n\n\u002F* Command door module to lock\u002Funlock *\u002F\nvoid BCM_LIN_DoorLockCommand(uint8_t door_module_id, bool lock) {\n    LINFrame_t frame;\n    frame.frame_id = door_module_id;\n    frame.length = 2;\n    frame.data[0] = lock ? 0x01 : 0x02;  \u002F* 0x01=lock, 0x02=unlock *\u002F\n    frame.data[1] = 0x00;\n    frame.checksum = BCM_LIN_CalculateChecksum(&frame);\n\n    BCM_LIN_SendFrame(&frame);\n}\n\n\u002F* Read door status from LIN module *\u002F\nbool BCM_LIN_ReadDoorStatus(uint8_t door_module_id, bool* door_open, bool* window_position) {\n    LINFrame_t request;\n    request.frame_id = door_module_id | 0x40;  \u002F* Read request *\u002F\n    request.length = 0;\n    request.checksum = BCM_LIN_CalculateChecksum(&request);\n\n    BCM_LIN_SendFrame(&request);\n\n    \u002F* Wait for response *\u002F\n    LINFrame_t response;\n    if (BCM_LIN_ReceiveFrame(&response, LIN_FRAME_TIMEOUT_MS)) {\n        *door_open = (response.data[0] & 0x01) != 0;\n        *window_position = response.data[1];\n        return true;\n    }\n\n    return false;\n}\n```\n\n## BCM CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: BCM VCU IVI\n\n\u002F* BCM Lighting Status *\u002F\nBO_ 512 BCM_LightingStatus: 8 BCM\n SG_ BCM_HeadlightMode : 0|8@1+ (0,0) [0|5] \"\"  IVI\n SG_ BCM_LeftTurnSignal : 8|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_RightTurnSignal : 9|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_HazardActive : 10|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_HighBeamActive : 11|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_BrakeLight : 12|1@1+ (0,0) [0|1] \"\"  VCU\n\n\u002F* BCM Door Status *\u002F\nBO_ 513 BCM_DoorStatus: 8 BCM\n SG_ BCM_DoorLocked_FL : 0|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorLocked_FR : 1|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorLocked_RL : 2|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorLocked_RR : 3|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ BCM_DoorOpen_FL : 8|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_DoorOpen_FR : 9|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_DoorOpen_RL : 10|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_DoorOpen_RR : 11|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ BCM_TrunkOpen : 12|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n\nVAL_ 512 BCM_HeadlightMode 0 \"Off\" 1 \"Parking\" 2 \"DRL\" 3 \"LowBeam\" 4 \"HighBeam\" 5 \"Auto\";\n```\n\n## References\n- SAE J1850: Class B Data Communication Network Interface\n- ISO 17987: Local Interconnect Network (LIN) Protocol\n- IEC 60529: IP Rating (Ingress Protection)\n- ECE R48: Installation of lighting devices\n\n## Common Issues\n- LIN bus communication errors due to incorrect timing\n- Anti-pinch false triggers from motor current spikes\n- Keyless entry authentication failures\n- Door lock actuators jamming in cold weather\n- PWM flicker at low brightness levels\n\n---\n\n## Bms Battery Management\n\n# BMS (Battery Management System) for EVs\u002FHEVs\n\n## Overview\nThe Battery Management System (BMS) monitors cell voltages, estimates SOC\u002FSOH, performs cell balancing, manages thermal systems, controls contactors, and ensures ISO 26262 ASIL-D safety compliance for high-voltage battery packs.\n\n## Core Responsibilities\n\n### 1. Cell Voltage Monitoring\n```c\n\u002F* bms_cell_monitoring.c - Multi-cell voltage acquisition *\u002F\n#include \"bms_cell_monitoring.h\"\n\n#define MAX_CELLS_PER_MODULE 12\n#define MAX_MODULES 10\n#define TOTAL_CELLS (MAX_CELLS_PER_MODULE * MAX_MODULES)\n\n#define CELL_OVERVOLTAGE_MV 4200\n#define CELL_UNDERVOLTAGE_MV 2500\n\ntypedef struct {\n    uint16_t voltage_mv;\n    int16_t temperature_c_x10;  \u002F* 0.1°C resolution *\u002F\n    bool balancing_active;\n} CellData_t;\n\ntypedef struct {\n    CellData_t cells[MAX_CELLS_PER_MODULE];\n    uint8_t module_id;\n    int16_t module_temperature_c_x10;\n    bool communication_ok;\n} ModuleData_t;\n\nstatic ModuleData_t g_modules[MAX_MODULES];\n\n\u002F* LTC6811 Battery Monitor IC interface *\u002F\nvoid BMS_CellMonitoring_Init(void) {\n    \u002F* Initialize SPI for LTC6811 daisy chain *\u002F\n    SPI_Init(SPI_BMS, 1000000);  \u002F* 1 MHz *\u002F\n\n    \u002F* Wake up all LTC6811 ICs *\u002F\n    BMS_LTC6811_Wakeup();\n\n    \u002F* Configure cell measurement mode *\u002F\n    uint8_t config[6] = {\n        0xF8,  \u002F* GPIO pull-downs off, REFON=1 *\u002F\n        0x00,  \u002F* Discharge switches off *\u002F\n        0x00, 0x00, 0x00, 0x00\n    };\n    BMS_LTC6811_WriteConfig(config);\n}\n\nvoid BMS_CellMonitoring_Update(void) {\n    \u002F* Start cell voltage conversion (all cells, all modules) *\u002F\n    BMS_LTC6811_StartCellConversion(ADC_MODE_NORMAL, ADC_FILTER_7KHZ);\n\n    \u002F* Wait for conversion (2.3ms for normal mode) *\u002F\n    OsTask_Sleep(3);\n\n    \u002F* Read cell voltages from all modules *\u002F\n    for (uint8_t module = 0; module \u003C MAX_MODULES; module++) {\n        uint16_t cell_voltages[MAX_CELLS_PER_MODULE];\n\n        if (BMS_LTC6811_ReadCellVoltages(module, cell_voltages)) {\n            for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n                g_modules[module].cells[cell].voltage_mv = cell_voltages[cell] \u002F 10;  \u002F* 100µV resolution *\u002F\n\n                \u002F* Check overvoltage\u002Fundervoltage *\u002F\n                if (cell_voltages[cell] > CELL_OVERVOLTAGE_MV) {\n                    BMS_Fault_SetOvervoltage(module, cell);\n                }\n                if (cell_voltages[cell] \u003C CELL_UNDERVOLTAGE_MV) {\n                    BMS_Fault_SetUndervoltage(module, cell);\n                }\n            }\n            g_modules[module].communication_ok = true;\n        } else {\n            g_modules[module].communication_ok = false;\n            BMS_Fault_SetCommunicationLoss(module);\n        }\n    }\n\n    \u002F* Read temperatures via GPIO (NTC thermistors) *\u002F\n    BMS_LTC6811_ReadGPIO();\n}\n\nuint16_t BMS_GetMinCellVoltage_mV(void) {\n    uint16_t min_voltage = 0xFFFF;\n\n    for (uint8_t mod = 0; mod \u003C MAX_MODULES; mod++) {\n        for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n            if (g_modules[mod].cells[cell].voltage_mv \u003C min_voltage) {\n                min_voltage = g_modules[mod].cells[cell].voltage_mv;\n            }\n        }\n    }\n\n    return min_voltage;\n}\n\nuint16_t BMS_GetMaxCellVoltage_mV(void) {\n    uint16_t max_voltage = 0;\n\n    for (uint8_t mod = 0; mod \u003C MAX_MODULES; mod++) {\n        for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n            if (g_modules[mod].cells[cell].voltage_mv > max_voltage) {\n                max_voltage = g_modules[mod].cells[cell].voltage_mv;\n            }\n        }\n    }\n\n    return max_voltage;\n}\n```\n\n### 2. SOC\u002FSOH Estimation (Coulomb Counting + Kalman Filter)\n```c\n\u002F* bms_soc_estimation.c - State of Charge \u002F State of Health algorithms *\u002F\n#include \"bms_soc_estimation.h\"\n#include \u003Cmath.h>\n\n#define BATTERY_CAPACITY_AH 75.0\n#define COULOMB_EFFICIENCY 0.98  \u002F* Charge efficiency *\u002F\n\ntypedef struct {\n    float soc_percent;           \u002F* 0-100% *\u002F\n    float soh_percent;           \u002F* 0-100%, degrades over time *\u002F\n    float coulomb_count_ah;      \u002F* Accumulated amp-hours *\u002F\n    float ocv_voltage_v;         \u002F* Open circuit voltage *\u002F\n    uint32_t cycle_count;        \u002F* Full charge\u002Fdischarge cycles *\u002F\n    float remaining_capacity_ah;\n} SOCState_t;\n\nstatic SOCState_t g_soc_state = {\n    .soc_percent = 50.0,\n    .soh_percent = 100.0,\n    .coulomb_count_ah = BATTERY_CAPACITY_AH \u002F 2.0,\n    .remaining_capacity_ah = BATTERY_CAPACITY_AH\n};\n\n\u002F* OCV-SOC lookup table (Open Circuit Voltage to SOC mapping) *\u002F\nstatic const struct {\n    float voltage_v;\n    float soc_percent;\n} OCV_SOC_TABLE[] = {\n    {3.27, 0.0},\n    {3.61, 10.0},\n    {3.69, 20.0},\n    {3.71, 30.0},\n    {3.73, 40.0},\n    {3.77, 50.0},\n    {3.83, 60.0},\n    {3.92, 70.0},\n    {4.01, 80.0},\n    {4.08, 90.0},\n    {4.20, 100.0}\n};\n\nvoid BMS_SOC_Init(void) {\n    \u002F* Load last known SOC from EEPROM *\u002F\n    NvM_ReadBlock(NVM_BLOCK_SOC_STATE, &g_soc_state);\n\n    \u002F* Initialize Kalman filter for SOC estimation *\u002F\n    BMS_KalmanFilter_Init();\n}\n\nvoid BMS_SOC_Update(float current_a, uint32_t delta_time_ms) {\n    \u002F* Coulomb counting: integrate current over time *\u002F\n    float delta_time_h = delta_time_ms \u002F 3600000.0;\n    float delta_ah = current_a * delta_time_h;\n\n    \u002F* Positive current = discharge, negative = charge *\u002F\n    if (current_a > 0) {\n        g_soc_state.coulomb_count_ah -= delta_ah;\n    } else {\n        g_soc_state.coulomb_count_ah -= delta_ah * COULOMB_EFFICIENCY;\n    }\n\n    \u002F* Clamp to capacity limits *\u002F\n    if (g_soc_state.coulomb_count_ah \u003C 0) {\n        g_soc_state.coulomb_count_ah = 0;\n    }\n    if (g_soc_state.coulomb_count_ah > g_soc_state.remaining_capacity_ah) {\n        g_soc_state.coulomb_count_ah = g_soc_state.remaining_capacity_ah;\n    }\n\n    \u002F* Calculate SOC from coulomb count *\u002F\n    g_soc_state.soc_percent = (g_soc_state.coulomb_count_ah \u002F\n                                g_soc_state.remaining_capacity_ah) * 100.0;\n\n    \u002F* Kalman filter fusion with OCV-based SOC (when current near zero) *\u002F\n    if (fabs(current_a) \u003C 1.0) {  \u002F* Low current: use OCV *\u002F\n        float pack_voltage_v = BMS_GetPackVoltage() \u002F 1000.0;\n        float avg_cell_voltage_v = pack_voltage_v \u002F TOTAL_CELLS;\n\n        float ocv_soc = BMS_SOC_LookupOCV(avg_cell_voltage_v);\n\n        \u002F* Kalman filter update *\u002F\n        g_soc_state.soc_percent = BMS_KalmanFilter_Update(\n            g_soc_state.soc_percent,\n            ocv_soc);\n    }\n\n    \u002F* Persist SOC every 1% change *\u002F\n    static float last_saved_soc = 0;\n    if (fabs(g_soc_state.soc_percent - last_saved_soc) > 1.0) {\n        NvM_WriteBlock(NVM_BLOCK_SOC_STATE, &g_soc_state);\n        last_saved_soc = g_soc_state.soc_percent;\n    }\n}\n\nfloat BMS_SOC_LookupOCV(float voltage_v) {\n    \u002F* Linear interpolation in OCV-SOC table *\u002F\n    for (int i = 0; i \u003C (sizeof(OCV_SOC_TABLE) \u002F sizeof(OCV_SOC_TABLE[0])) - 1; i++) {\n        if (voltage_v >= OCV_SOC_TABLE[i].voltage_v &&\n            voltage_v \u003C= OCV_SOC_TABLE[i+1].voltage_v) {\n\n            float v_range = OCV_SOC_TABLE[i+1].voltage_v - OCV_SOC_TABLE[i].voltage_v;\n            float soc_range = OCV_SOC_TABLE[i+1].soc_percent - OCV_SOC_TABLE[i].soc_percent;\n            float v_delta = voltage_v - OCV_SOC_TABLE[i].voltage_v;\n\n            return OCV_SOC_TABLE[i].soc_percent + (v_delta \u002F v_range) * soc_range;\n        }\n    }\n\n    return 50.0;  \u002F* Default fallback *\u002F\n}\n\n\u002F* SOH estimation based on capacity fade *\u002F\nvoid BMS_SOH_Update(void) {\n    \u002F* Detect full charge cycle: SOC goes 100% -> 0% -> 100% *\u002F\n    static bool charging = false;\n    static bool discharged = false;\n\n    if (g_soc_state.soc_percent > 99.0 && !charging) {\n        charging = true;\n\n        if (discharged) {\n            \u002F* Full cycle completed *\u002F\n            g_soc_state.cycle_count++;\n\n            \u002F* Estimate capacity fade: 80% at 1000 cycles (linear model) *\u002F\n            g_soc_state.remaining_capacity_ah =\n                BATTERY_CAPACITY_AH * (1.0 - (g_soc_state.cycle_count \u002F 5000.0));\n\n            g_soc_state.soh_percent = (g_soc_state.remaining_capacity_ah \u002F\n                                       BATTERY_CAPACITY_AH) * 100.0;\n\n            discharged = false;\n        }\n    }\n\n    if (g_soc_state.soc_percent \u003C 5.0) {\n        discharged = true;\n        charging = false;\n    }\n}\n```\n\n### 3. Cell Balancing (Active\u002FPassive)\n```c\n\u002F* bms_cell_balancing.c - Cell voltage equalization *\u002F\n#include \"bms_cell_balancing.h\"\n\n#define BALANCE_THRESHOLD_MV 10  \u002F* Start balancing if cell delta > 10mV *\u002F\n#define BALANCE_TARGET_MV 5      \u002F* Stop when delta \u003C 5mV *\u002F\n#define MAX_BALANCE_CURRENT_MA 200\n\nvoid BMS_CellBalancing_Update(void) {\n    uint16_t min_voltage = BMS_GetMinCellVoltage_mV();\n    uint16_t max_voltage = BMS_GetMaxCellVoltage_mV();\n\n    if ((max_voltage - min_voltage) \u003C BALANCE_THRESHOLD_MV) {\n        \u002F* Cells well balanced: disable all balancing *\u002F\n        BMS_CellBalancing_DisableAll();\n        return;\n    }\n\n    \u002F* Passive balancing: discharge high cells through resistors *\u002F\n    for (uint8_t mod = 0; mod \u003C MAX_MODULES; mod++) {\n        uint16_t balance_mask = 0;\n\n        for (uint8_t cell = 0; cell \u003C MAX_CELLS_PER_MODULE; cell++) {\n            uint16_t cell_voltage = g_modules[mod].cells[cell].voltage_mv;\n\n            \u002F* Balance if above minimum + threshold *\u002F\n            if (cell_voltage > (min_voltage + BALANCE_TARGET_MV)) {\n                balance_mask |= (1 \u003C\u003C cell);\n                g_modules[mod].cells[cell].balancing_active = true;\n            } else {\n                g_modules[mod].cells[cell].balancing_active = false;\n            }\n        }\n\n        \u002F* Write balance control register to LTC6811 *\u002F\n        BMS_LTC6811_SetBalancing(mod, balance_mask);\n    }\n}\n```\n\n### 4. Contactor Control (Safety-Critical)\n```c\n\u002F* bms_contactor_control.c - High-voltage contactor sequencing *\u002F\n#include \"bms_contactor_control.h\"\n\n#define PRECHARGE_TIMEOUT_MS 5000\n#define PRECHARGE_THRESHOLD_PERCENT 95\n\ntypedef enum {\n    CONTACTOR_STATE_OPEN = 0,\n    CONTACTOR_STATE_PRECHARGING,\n    CONTACTOR_STATE_CLOSED,\n    CONTACTOR_STATE_FAULT\n} ContactorState_t;\n\nstatic ContactorState_t g_contactor_state = CONTACTOR_STATE_OPEN;\n\nvoid BMS_Contactor_Close(void) {\n    \u002F* Safety checks before closing *\u002F\n    if (!BMS_Safety_PreCloseCheck()) {\n        g_contactor_state = CONTACTOR_STATE_FAULT;\n        return;\n    }\n\n    \u002F* Step 1: Close negative contactor *\u002F\n    GPIO_Set(GPIO_CONTACTOR_NEGATIVE, true);\n    OsTask_Sleep(50);\n\n    \u002F* Step 2: Precharge positive side through resistor *\u002F\n    g_contactor_state = CONTACTOR_STATE_PRECHARGING;\n    GPIO_Set(GPIO_PRECHARGE_RELAY, true);\n\n    uint32_t start_time = GetSystemTime_ms();\n    uint16_t pack_voltage_v = BMS_GetPackVoltage();\n    uint16_t link_voltage_v = ADC_ReadHVLinkVoltage();\n\n    \u002F* Wait for DC link to charge to 95% of pack voltage *\u002F\n    while ((GetSystemTime_ms() - start_time) \u003C PRECHARGE_TIMEOUT_MS) {\n        link_voltage_v = ADC_ReadHVLinkVoltage();\n\n        if (link_voltage_v > (pack_voltage_v * PRECHARGE_THRESHOLD_PERCENT \u002F 100)) {\n            break;  \u002F* Precharge complete *\u002F\n        }\n\n        OsTask_Sleep(10);\n    }\n\n    if (link_voltage_v \u003C (pack_voltage_v * PRECHARGE_THRESHOLD_PERCENT \u002F 100)) {\n        \u002F* Precharge timeout: fault *\u002F\n        GPIO_Set(GPIO_PRECHARGE_RELAY, false);\n        GPIO_Set(GPIO_CONTACTOR_NEGATIVE, false);\n        g_contactor_state = CONTACTOR_STATE_FAULT;\n        DTC_SetFault(DTC_PRECHARGE_TIMEOUT);\n        return;\n    }\n\n    \u002F* Step 3: Close positive contactor *\u002F\n    GPIO_Set(GPIO_CONTACTOR_POSITIVE, true);\n    OsTask_Sleep(50);\n\n    \u002F* Step 4: Open precharge relay *\u002F\n    GPIO_Set(GPIO_PRECHARGE_RELAY, false);\n\n    g_contactor_state = CONTACTOR_STATE_CLOSED;\n}\n\nvoid BMS_Contactor_Open(void) {\n    \u002F* Open positive first, then negative *\u002F\n    GPIO_Set(GPIO_CONTACTOR_POSITIVE, false);\n    OsTask_Sleep(50);\n    GPIO_Set(GPIO_CONTACTOR_NEGATIVE, false);\n\n    g_contactor_state = CONTACTOR_STATE_OPEN;\n}\n```\n\n## BMS CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: BMS VCU MCU\n\n\u002F* BMS Battery Status *\u002F\nBO_ 768 BMS_BatteryStatus: 8 BMS\n SG_ BMS_PackVoltage_V : 0|16@1+ (0.1,0) [0|600] \"V\"  VCU,MCU\n SG_ BMS_PackCurrent_A : 16|16@1- (0.1,-320) [-320|320] \"A\"  VCU,MCU\n SG_ BMS_SOC_percent : 32|8@1+ (0.5,0) [0|100] \"%\"  VCU,MCU\n SG_ BMS_SOH_percent : 40|8@1+ (0.5,0) [0|100] \"%\"  VCU\n SG_ BMS_MaxCellTemp_C : 48|8@1+ (1,-40) [-40|100] \"C\"  VCU,MCU\n SG_ BMS_ContactorState : 56|8@1+ (0,0) [0|3] \"\"  VCU,MCU\n\nVAL_ 768 BMS_ContactorState 0 \"Open\" 1 \"Precharging\" 2 \"Closed\" 3 \"Fault\";\n```\n\n## ISO 26262 ASIL-D Safety Mechanisms\n- Dual voltage measurement paths with cross-checking\n- Watchdog timer for contactor control\n- Cell voltage plausibility checks\n- Safe state transition on fault detection\n\n## References\n- ISO 26262: Functional Safety for Road Vehicles\n- UL 2580: Batteries for Use in Electric Vehicles\n- IEC 62133: Safety Requirements for Portable Sealed Secondary Cells\n- SAE J2464: EV Battery Systems Crashworthiness\n\n## Common Issues\n- SOC drift from coulomb counting errors\n- Cell balancing inefficiency at low SOC\n- Precharge relay welding from inrush current\n- Temperature sensor failures affecting thermal management\n\n---\n\n## Domain Controller Integration\n\n# Domain Controller Architecture - Next-Gen Vehicle E\u002FE Architecture\n\n## Overview\nDomain Controller architecture centralizes ECU functions into fewer, more powerful computing platforms: Chassis Domain, Powertrain Domain, Body\u002FComfort Domain, ADAS Domain, with cross-domain communication via service-oriented architecture (SOA) and resource sharing.\n\n## Domain Controller Concepts\n\n### 1. Chassis Domain Controller\n```c\n\u002F* chassis_domain_controller.c - Integrated chassis functions *\u002F\n#include \"chassis_domain.h\"\n\n\u002F* Consolidated functions: ESC, ABS, TCS, EPS, ADAS braking *\u002F\ntypedef struct {\n    \u002F* Electronic Stability Control *\u002F\n    bool esc_active;\n    float yaw_rate_deg_s;\n    float lateral_acceleration_g;\n\n    \u002F* Anti-lock Braking System *\u002F\n    uint8_t wheel_speeds_kph[4];\n    bool abs_active[4];\n\n    \u002F* Traction Control System *\u002F\n    bool tcs_active;\n    uint16_t tcs_torque_reduction_nm;\n\n    \u002F* Electric Power Steering *\u002F\n    float steering_angle_deg;\n    float steering_torque_nm;\n\n    \u002F* ADAS Braking Interface *\u002F\n    bool adas_brake_request;\n    float adas_decel_mps2;\n} ChassisDomain_t;\n\nstatic ChassisDomain_t g_chassis = {0};\n\nvoid ChassisDomain_Main_10ms(void) {\n    \u002F* Read sensors from CAN\u002FFlexRay *\u002F\n    ChassisDomain_ReadSensors();\n\n    \u002F* ESC control loop *\u002F\n    ChassisDomain_ESC_Update();\n\n    \u002F* ABS control per wheel *\u002F\n    for (int i = 0; i \u003C 4; i++) {\n        ChassisDomain_ABS_UpdateWheel(i);\n    }\n\n    \u002F* TCS integration with powertrain domain *\u002F\n    if (g_chassis.tcs_active) {\n        \u002F* Send torque reduction request to powertrain domain *\u002F\n        SOMEIP_SendRequest(POWERTRAIN_DOMAIN_SERVICE_ID,\n                           METHOD_REDUCE_TORQUE,\n                           &g_chassis.tcs_torque_reduction_nm,\n                           sizeof(uint16_t));\n    }\n\n    \u002F* ADAS brake arbitration *\u002F\n    if (g_chassis.adas_brake_request) {\n        ChassisDomain_ADAS_BrakeControl();\n    }\n\n    \u002F* Publish chassis status to Ethernet backbone *\u002F\n    ChassisDomain_PublishStatus();\n}\n\nvoid ChassisDomain_ESC_Update(void) {\n    \u002F* Read IMU (gyroscope + accelerometer) *\u002F\n    float yaw_rate = IMU_GetYawRate();\n    float lat_accel = IMU_GetLateralAcceleration();\n\n    \u002F* Calculate desired yaw rate from steering angle *\u002F\n    float desired_yaw = (g_chassis.steering_angle_deg * VCU_GetVehicleSpeed_kph()) \u002F 15.0;\n\n    \u002F* ESC intervention if yaw error exceeds threshold *\u002F\n    float yaw_error = desired_yaw - yaw_rate;\n\n    if (fabs(yaw_error) > 5.0) {\n        g_chassis.esc_active = true;\n\n        \u002F* Apply differential braking to correct yaw *\u002F\n        if (yaw_error > 0) {\n            \u002F* Understeer: brake inside rear wheel *\u002F\n            ChassisDomain_ApplyBrake(WHEEL_RL, 30);\n        } else {\n            \u002F* Oversteer: brake outside front wheel *\u002F\n            ChassisDomain_ApplyBrake(WHEEL_FL, 30);\n        }\n\n        \u002F* Reduce engine torque *\u002F\n        SOMEIP_SendRequest(POWERTRAIN_DOMAIN_SERVICE_ID,\n                           METHOD_REDUCE_TORQUE,\n                           &(uint16_t){100}, 2);\n    } else {\n        g_chassis.esc_active = false;\n    }\n}\n```\n\n### 2. Powertrain Domain Controller\n```c\n\u002F* powertrain_domain_controller.c - EV powertrain integration *\u002F\n#include \"powertrain_domain.h\"\n\n\u002F* Consolidated: VCU, BMS, MCU functions *\u002F\ntypedef struct {\n    \u002F* Motor control *\u002F\n    int16_t motor_torque_cmd_nm;\n    uint16_t motor_speed_rpm;\n    float motor_temperature_c;\n\n    \u002F* Battery management *\u002F\n    float battery_soc_percent;\n    uint16_t battery_voltage_v;\n    float battery_current_a;\n\n    \u002F* Thermal management *\u002F\n    bool cooling_pump_active;\n    uint8_t radiator_fan_speed_percent;\n} PowertrainDomain_t;\n\nstatic PowertrainDomain_t g_powertrain = {0};\n\nvoid PowertrainDomain_Main_10ms(void) {\n    \u002F* Motor control *\u002F\n    PowertrainDomain_MotorControl();\n\n    \u002F* Battery management *\u002F\n    PowertrainDomain_BMS_Update();\n\n    \u002F* Thermal management *\u002F\n    PowertrainDomain_ThermalControl();\n\n    \u002F* Service-oriented communication *\u002F\n    PowertrainDomain_HandleSOARequests();\n}\n\nvoid PowertrainDomain_HandleSOARequests(void) {\n    \u002F* Handle SOME\u002FIP service requests from other domains *\u002F\n    SOMEIP_Request_t req;\n\n    if (SOMEIP_ReceiveRequest(&req)) {\n        switch (req.method_id) {\n            case METHOD_REDUCE_TORQUE: {\n                uint16_t reduction_nm = *(uint16_t*)req.payload;\n                g_powertrain.motor_torque_cmd_nm -= reduction_nm;\n\n                \u002F* Send response *\u002F\n                SOMEIP_SendResponse(&req, RESPONSE_OK, NULL, 0);\n                break;\n            }\n\n            case METHOD_GET_SOC: {\n                uint8_t soc = (uint8_t)g_powertrain.battery_soc_percent;\n                SOMEIP_SendResponse(&req, RESPONSE_OK, &soc, 1);\n                break;\n            }\n\n            case METHOD_SET_CHARGING_LIMIT: {\n                uint8_t limit_percent = *(uint8_t*)req.payload;\n                PowertrainDomain_SetChargingLimit(limit_percent);\n                SOMEIP_SendResponse(&req, RESPONSE_OK, NULL, 0);\n                break;\n            }\n        }\n    }\n}\n```\n\n### 3. Body\u002FComfort Domain Controller\n```c\n\u002F* body_domain_controller.c - Comfort and convenience functions *\u002F\n#include \"body_domain.h\"\n\n\u002F* Consolidated: BCM, HVAC, seats, ambient lighting *\u002F\ntypedef struct {\n    \u002F* Climate control *\u002F\n    float cabin_temperature_c;\n    uint8_t hvac_fan_speed;\n    bool ac_compressor_active;\n\n    \u002F* Lighting *\u002F\n    HeadlightMode_t headlight_mode;\n    uint8_t ambient_light_brightness;\n\n    \u002F* Seats *\u002F\n    uint8_t driver_seat_heating_level;\n    uint8_t passenger_seat_heating_level;\n} BodyDomain_t;\n\nstatic BodyDomain_t g_body = {0};\n\nvoid BodyDomain_Main_50ms(void) {\n    \u002F* Climate control *\u002F\n    BodyDomain_HVAC_Update();\n\n    \u002F* Lighting control *\u002F\n    BodyDomain_Lighting_Update();\n\n    \u002F* Seat control *\u002F\n    BodyDomain_Seats_Update();\n\n    \u002F* User preference synchronization (cloud) *\u002F\n    BodyDomain_SyncUserPreferences();\n}\n\nvoid BodyDomain_SyncUserPreferences(void) {\n    \u002F* Load user profile from cloud (via TCU) *\u002F\n    UserProfile_t profile;\n\n    if (Cloud_GetUserProfile(g_authenticated_user_id, &profile)) {\n        \u002F* Apply preferences *\u002F\n        g_body.driver_seat_heating_level = profile.seat_heat_pref;\n        g_body.ambient_light_brightness = profile.ambient_light_pref;\n        g_body.headlight_mode = profile.headlight_mode_pref;\n\n        \u002F* Adjust seat position (via LIN to seat ECU) *\u002F\n        LIN_SendSeatPosition(profile.seat_position);\n    }\n}\n```\n\n### 4. ADAS Domain Controller\n```c\n\u002F* adas_domain_controller.c - Perception, planning, control *\u002F\n#include \"adas_domain.h\"\n\n\u002F* Consolidated: camera, radar, lidar fusion, path planning *\u002F\ntypedef struct {\n    \u002F* Perception *\u002F\n    Object_t detected_objects[32];\n    uint8_t object_count;\n\n    \u002F* Localization *\u002F\n    float ego_position_x;\n    float ego_position_y;\n    float ego_heading_deg;\n\n    \u002F* Path planning *\u002F\n    Trajectory_t planned_path;\n\n    \u002F* Control *\u002F\n    float target_acceleration_mps2;\n    float target_steering_angle_deg;\n} ADASDomain_t;\n\nstatic ADASDomain_t g_adas = {0};\n\nvoid ADASDomain_Main_20ms(void) {\n    \u002F* Sensor fusion *\u002F\n    ADASDomain_SensorFusion();\n\n    \u002F* Object detection and tracking *\u002F\n    ADASDomain_ObjectTracking();\n\n    \u002F* Path planning *\u002F\n    ADASDomain_PathPlanning();\n\n    \u002F* Send control commands to chassis\u002Fpowertrain domains *\u002F\n    ADASDomain_SendControlCommands();\n}\n\nvoid ADASDomain_SendControlCommands(void) {\n    \u002F* Request steering via chassis domain *\u002F\n    SOMEIP_SendRequest(CHASSIS_DOMAIN_SERVICE_ID,\n                       METHOD_SET_STEERING_ANGLE,\n                       &g_adas.target_steering_angle_deg,\n                       sizeof(float));\n\n    \u002F* Request acceleration via powertrain domain *\u002F\n    if (g_adas.target_acceleration_mps2 > 0) {\n        \u002F* Acceleration *\u002F\n        int16_t torque_nm = (int16_t)(g_adas.target_acceleration_mps2 * 50);\n        SOMEIP_SendRequest(POWERTRAIN_DOMAIN_SERVICE_ID,\n                           METHOD_SET_TORQUE,\n                           &torque_nm,\n                           sizeof(int16_t));\n    } else {\n        \u002F* Braking *\u002F\n        float decel_mps2 = -g_adas.target_acceleration_mps2;\n        SOMEIP_SendRequest(CHASSIS_DOMAIN_SERVICE_ID,\n                           METHOD_APPLY_BRAKE,\n                           &decel_mps2,\n                           sizeof(float));\n    }\n}\n```\n\n## Service-Oriented Architecture (SOME\u002FIP)\n\n### SOME\u002FIP Service Definition (ARXML)\n```xml\n\u003C!-- adas_services.arxml -->\n\u003CAUTOSAR>\n  \u003CAR-PACKAGES>\n    \u003CAR-PACKAGE>\n      \u003CSHORT-NAME>ADAS_Services\u003C\u002FSHORT-NAME>\n      \u003CELEMENTS>\n        \u003CSOMEIP-SERVICE-INTERFACE>\n          \u003CSHORT-NAME>ADAS_Control_Service\u003C\u002FSHORT-NAME>\n          \u003CSERVICE-INTERFACE-ID>0x1234\u003C\u002FSERVICE-INTERFACE-ID>\n          \u003CMAJOR-VERSION>1\u003C\u002FMAJOR-VERSION>\n          \u003CMINOR-VERSION>0\u003C\u002FMINOR-VERSION>\n\n          \u003CMETHODS>\n            \u003CSOMEIP-METHOD>\n              \u003CSHORT-NAME>SetSteeringAngle\u003C\u002FSHORT-NAME>\n              \u003CMETHOD-ID>0x0001\u003C\u002FMETHOD-ID>\n              \u003CCALL-SEMANTIC>REQUEST-RESPONSE\u003C\u002FCALL-SEMANTIC>\n            \u003C\u002FSOMEIP-METHOD>\n            \u003CSOMEIP-METHOD>\n              \u003CSHORT-NAME>ApplyBrake\u003C\u002FSHORT-NAME>\n              \u003CMETHOD-ID>0x0002\u003C\u002FMETHOD-ID>\n              \u003CCALL-SEMANTIC>REQUEST-RESPONSE\u003C\u002FCALL-SEMANTIC>\n            \u003C\u002FSOMEIP-METHOD>\n          \u003C\u002FMETHODS>\n\n          \u003CEVENTS>\n            \u003CSOMEIP-EVENT>\n              \u003CSHORT-NAME>ObjectDetected\u003C\u002FSHORT-NAME>\n              \u003CEVENT-ID>0x8001\u003C\u002FEVENT-ID>\n            \u003C\u002FSOMEIP-EVENT>\n          \u003C\u002FEVENTS>\n        \u003C\u002FSOMEIP-SERVICE-INTERFACE>\n      \u003C\u002FELEMENTS>\n    \u003C\u002FAR-PACKAGE>\n  \u003C\u002FAR-PACKAGES>\n\u003C\u002FAUTOSAR>\n```\n\n### Cross-Domain Communication Example\n```c\n\u002F* domain_communication.c - SOME\u002FIP client\u002Fserver example *\u002F\n#include \"someip.h\"\n\n\u002F* Client: ADAS domain requests torque from powertrain domain *\u002F\nvoid ADAS_RequestTorque(int16_t torque_nm) {\n    SOMEIP_Message_t msg;\n    msg.service_id = POWERTRAIN_SERVICE_ID;\n    msg.method_id = METHOD_SET_TORQUE;\n    msg.client_id = ADAS_DOMAIN_CLIENT_ID;\n    msg.session_id = GetNextSessionID();\n    msg.payload_length = sizeof(int16_t);\n    memcpy(msg.payload, &torque_nm, sizeof(int16_t));\n\n    SOMEIP_Send(&msg);\n\n    \u002F* Wait for response *\u002F\n    SOMEIP_Message_t response;\n    if (SOMEIP_WaitForResponse(&response, 100)) {\n        if (response.return_code == SOMEIP_RETURN_OK) {\n            \u002F* Request acknowledged *\u002F\n        }\n    }\n}\n\n\u002F* Server: Powertrain domain handles torque request *\u002F\nvoid Powertrain_SOMEIP_Handler(const SOMEIP_Message_t* request) {\n    if (request->method_id == METHOD_SET_TORQUE) {\n        int16_t requested_torque = *(int16_t*)request->payload;\n\n        \u002F* Apply safety limits *\u002F\n        if (requested_torque > MAX_TORQUE_NM) {\n            requested_torque = MAX_TORQUE_NM;\n        }\n\n        \u002F* Set motor torque *\u002F\n        VCU_SetMotorTorque(requested_torque);\n\n        \u002F* Send response *\u002F\n        SOMEIP_Message_t response;\n        response.service_id = request->service_id;\n        response.method_id = request->method_id;\n        response.client_id = request->client_id;\n        response.session_id = request->session_id;\n        response.return_code = SOMEIP_RETURN_OK;\n        response.payload_length = 0;\n\n        SOMEIP_Send(&response);\n    }\n}\n```\n\n## Resource Sharing and Timing\n\n### Hypervisor-Based Domain Isolation\n```c\n\u002F* hypervisor_config.h - QNX Hypervisor partition configuration *\u002F\n\n\u002F* Chassis Domain - Guest VM #1 *\u002F\n#define CHASSIS_DOMAIN_RAM_BASE 0x80000000\n#define CHASSIS_DOMAIN_RAM_SIZE 512MB\n#define CHASSIS_DOMAIN_CPU_MASK 0x03  \u002F* CPU 0-1 *\u002F\n#define CHASSIS_DOMAIN_PRIORITY CRITICAL\n\n\u002F* Powertrain Domain - Guest VM #2 *\u002F\n#define POWERTRAIN_DOMAIN_RAM_BASE 0xA0000000\n#define POWERTRAIN_DOMAIN_RAM_SIZE 512MB\n#define POWERTRAIN_DOMAIN_CPU_MASK 0x0C  \u002F* CPU 2-3 *\u002F\n#define POWERTRAIN_DOMAIN_PRIORITY CRITICAL\n\n\u002F* Body Domain - Guest VM #3 *\u002F\n#define BODY_DOMAIN_RAM_BASE 0xC0000000\n#define BODY_DOMAIN_RAM_SIZE 256MB\n#define BODY_DOMAIN_CPU_MASK 0x10  \u002F* CPU 4 *\u002F\n#define BODY_DOMAIN_PRIORITY NORMAL\n\n\u002F* ADAS Domain - Guest VM #4 (highest compute) *\u002F\n#define ADAS_DOMAIN_RAM_BASE 0xD0000000\n#define ADAS_DOMAIN_RAM_SIZE 2GB\n#define ADAS_DOMAIN_CPU_MASK 0xE0  \u002F* CPU 5-7 *\u002F\n#define ADAS_DOMAIN_PRIORITY HIGH\n```\n\n## Benefits of Domain Controller Architecture\n- **Reduced wiring harness complexity**: Fewer ECUs = less copper\n- **Centralized computing**: More powerful processors, better performance\n- **OTA update efficiency**: Update entire domain instead of individual ECUs\n- **Cost reduction**: Consolidation reduces hardware costs\n- **Scalability**: Easier to add features without new ECUs\n\n## References\n- AUTOSAR Adaptive Platform R22-11\n- SOME\u002FIP Protocol Specification v1.3\n- QNX Hypervisor for Automotive\n- ISO 21434: Road Vehicles - Cybersecurity Engineering\n- ASAM OpenX: Service-Oriented Communication\n\n## Common Issues\n- Inter-domain latency exceeding real-time requirements\n- Resource contention between domains on shared CPU cores\n- SOME\u002FIP service discovery failures\n- Hypervisor overhead impacting deterministic timing\n- Cross-domain debugging complexity\n\n---\n\n## Ivi Infotainment Systems\n\n# IVI (In-Vehicle Infotainment) Systems\n\n## Overview\nThe In-Vehicle Infotainment (IVI) system manages navigation, multimedia, connectivity (CarPlay\u002FAndroid Auto), voice assistant, HMI frameworks (Qt\u002FFlutter), and runs on Android Automotive OS, QNX, or Linux platforms.\n\n## Platform Architectures\n\n### 1. Android Automotive OS (AAOS)\n```java\n\u002F\u002F VehicleHalService.java - Android Automotive HAL integration\npackage com.example.ivi;\n\nimport android.car.Car;\nimport android.car.VehiclePropertyIds;\nimport android.car.hardware.CarPropertyValue;\nimport android.car.hardware.property.CarPropertyManager;\n\npublic class VehicleHalService {\n    private CarPropertyManager mCarPropertyManager;\n\n    public void init(Context context) {\n        Car car = Car.createCar(context);\n        mCarPropertyManager = (CarPropertyManager) car.getCarManager(Car.PROPERTY_SERVICE);\n\n        \u002F\u002F Subscribe to vehicle speed updates\n        mCarPropertyManager.registerCallback(\n            new CarPropertyManager.CarPropertyEventCallback() {\n                @Override\n                public void onChangeEvent(CarPropertyValue value) {\n                    if (value.getPropertyId() == VehiclePropertyIds.PERF_VEHICLE_SPEED) {\n                        float speedMs = (Float) value.getValue();\n                        updateSpeedUI(speedMs * 3.6f);  \u002F\u002F Convert to km\u002Fh\n                    }\n                }\n\n                @Override\n                public void onErrorEvent(int propId, int zone) {\n                    Log.e(\"VehicleHal\", \"Property error: \" + propId);\n                }\n            },\n            VehiclePropertyIds.PERF_VEHICLE_SPEED,\n            CarPropertyManager.SENSOR_RATE_NORMAL);\n    }\n\n    public void setHvacTemperature(float tempCelsius) {\n        mCarPropertyManager.setFloatProperty(\n            VehiclePropertyIds.HVAC_TEMPERATURE_SET,\n            VehicleAreaType.VEHICLE_AREA_TYPE_SEAT,\n            tempCelsius);\n    }\n}\n```\n\n### 2. QNX-Based IVI\n```c\n\u002F* qnx_ivi_service.c - QNX CAR platform integration *\u002F\n#include \u003Cqnxcar\u002Fcarcontrol.h>\n#include \u003Cscreen\u002Fscreen.h>\n\nvoid IVI_QNX_Init(void) {\n    \u002F* Initialize QNX CAR framework *\u002F\n    car_control_t *control = car_control_create();\n\n    \u002F* Register for CAN message callbacks *\u002F\n    car_control_set_can_callback(control, IVI_CAN_MessageHandler);\n\n    \u002F* Initialize Screen Graphics Subsystem *\u002F\n    screen_context_t screen_ctx;\n    screen_create_context(&screen_ctx, SCREEN_APPLICATION_CONTEXT);\n\n    \u002F* Create display window *\u002F\n    screen_window_t window;\n    screen_create_window(&window, screen_ctx);\n    screen_set_window_property_iv(window, SCREEN_PROPERTY_SIZE, (int[]){1920, 1080});\n}\n\nvoid IVI_CAN_MessageHandler(car_can_message_t *msg) {\n    if (msg->id == 0x100) {  \u002F* VCU Motor Command *\u002F\n        uint16_t torque = (msg->data[0] \u003C\u003C 8) | msg->data[1];\n        IVI_UpdatePowerMeter(torque);\n    }\n}\n```\n\n### 3. Navigation Integration (HERE\u002FTomTom)\n```kotlin\n\u002F\u002F NavigationService.kt - HERE SDK integration\npackage com.example.ivi.navigation\n\nimport com.here.sdk.core.GeoCoordinates\nimport com.here.sdk.routing.CalculateRouteCallback\nimport com.here.sdk.routing.Route\nimport com.here.sdk.routing.RoutingEngine\n\nclass NavigationService {\n    private lateinit var routingEngine: RoutingEngine\n\n    fun initialize() {\n        routingEngine = RoutingEngine()\n    }\n\n    fun calculateRoute(\n        origin: GeoCoordinates,\n        destination: GeoCoordinates,\n        callback: (Route?) -> Unit\n    ) {\n        val waypoints = listOf(\n            Waypoint(origin),\n            Waypoint(destination)\n        )\n\n        val carOptions = CarOptions().apply {\n            routeOptions.alternatives = 3\n            avoidanceOptions.avoidTollRoads = false\n            optimizationMode = OptimizationMode.FASTEST\n        }\n\n        routingEngine.calculateRoute(waypoints, carOptions) { routingError, routes ->\n            if (routingError == null && routes?.isNotEmpty() == true) {\n                callback(routes[0])\n            } else {\n                callback(null)\n            }\n        }\n    }\n}\n```\n\n### 4. CarPlay\u002FAndroid Auto Integration\n```java\n\u002F\u002F AndroidAutoService.java - Android Auto projection\npackage com.example.ivi.projection;\n\nimport android.content.Intent;\nimport com.google.android.apps.auto.sdk.CarActivity;\n\npublic class AndroidAutoService extends CarActivity {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n\n        \u002F\u002F Start Android Auto projection\n        Intent intent = new Intent(\"com.google.android.gms.car.PROJECTION_SERVICE\");\n        startService(intent);\n    }\n\n    @Override\n    public void onCarConnectionStateChanged(int state) {\n        if (state == CarConnection.STATE_CONNECTED) {\n            \u002F\u002F Phone connected: mirror Android Auto UI\n            enableProjectionMode();\n        }\n    }\n}\n```\n\n### 5. Voice Assistant Integration (Alexa\u002FGoogle Assistant)\n```python\n# voice_assistant.py - Voice command handler\nimport speech_recognition as sr\nimport pyttsx3\n\nclass VoiceAssistant:\n    def __init__(self):\n        self.recognizer = sr.Recognizer()\n        self.tts = pyttsx3.init()\n\n    def listen_for_command(self):\n        with sr.Microphone() as source:\n            print(\"Listening...\")\n            audio = self.recognizer.listen(source)\n\n        try:\n            command = self.recognizer.recognize_google(audio)\n            self.process_command(command)\n        except sr.UnknownValueError:\n            self.speak(\"Sorry, I didn't understand that.\")\n\n    def process_command(self, command):\n        if \"navigate to\" in command.lower():\n            destination = command.lower().replace(\"navigate to\", \"\").strip()\n            self.navigate(destination)\n        elif \"set temperature\" in command.lower():\n            temp = int(command.split()[-1])\n            self.set_hvac_temperature(temp)\n\n    def speak(self, text):\n        self.tts.say(text)\n        self.tts.runAndWait()\n```\n\n## HMI Framework (Qt QML)\n```qml\n\u002F* DashboardView.qml - Main instrument cluster *\u002F\nimport QtQuick 2.15\nimport QtQuick.Controls 2.15\n\nRectangle {\n    width: 1920\n    height: 720\n\n    \u002F\u002F Speedometer\n    Item {\n        id: speedometer\n        x: 100\n        y: 100\n\n        Canvas {\n            id: speedArc\n            width: 400\n            height: 400\n\n            onPaint: {\n                var ctx = getContext(\"2d\");\n                ctx.clearRect(0, 0, width, height);\n\n                \u002F\u002F Draw arc for speed (0-240 km\u002Fh)\n                ctx.beginPath();\n                ctx.arc(200, 200, 150, 0.75 * Math.PI, (0.75 + 1.5 * (vehicleSpeed \u002F 240)) * Math.PI);\n                ctx.lineWidth = 20;\n                ctx.strokeStyle = \"#00FF00\";\n                ctx.stroke();\n            }\n\n            Connections {\n                target: vehicleData\n                onSpeedChanged: speedArc.requestPaint()\n            }\n        }\n\n        Text {\n            text: vehicleData.speed + \" km\u002Fh\"\n            font.pixelSize: 48\n            color: \"white\"\n            anchors.centerIn: parent\n        }\n    }\n\n    \u002F\u002F Battery SOC gauge\n    Rectangle {\n        x: 600\n        y: 100\n        width: 300\n        height: 50\n        color: \"transparent\"\n        border.color: \"white\"\n\n        Rectangle {\n            width: parent.width * (vehicleData.batterySOC \u002F 100)\n            height: parent.height\n            color: vehicleData.batterySOC > 20 ? \"#00FF00\" : \"#FF0000\"\n        }\n\n        Text {\n            text: vehicleData.batterySOC + \"%\"\n            color: \"white\"\n            anchors.centerIn: parent\n        }\n    }\n}\n```\n\n## IVI CAN Interface (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: IVI VCU BCM BMS\n\n\u002F* IVI User Commands *\u002F\nBO_ 1024 IVI_UserCommand: 8 IVI\n SG_ IVI_DriveMode : 0|8@1+ (0,0) [0|3] \"\"  VCU\n SG_ IVI_ACTempSet : 8|8@1+ (0.5,10) [10|35] \"C\"  BCM\n SG_ IVI_ACFanSpeed : 16|8@1+ (0,0) [0|7] \"\"  BCM\n\nVAL_ 1024 IVI_DriveMode 0 \"Eco\" 1 \"Normal\" 2 \"Sport\" 3 \"Custom\";\n```\n\n## References\n- Android Automotive OS Developer Guide\n- QNX CAR Platform API Reference\n- HERE SDK for Automotive\n- CarPlay App Programming Guide\n- W3C Automotive Web Platform Specification\n\n## Common Issues\n- High CPU usage from rendering complex 3D gauges\n- CarPlay\u002FAndroid Auto disconnection during navigation\n- Voice recognition accuracy in noisy cabin\n- Slow boot time (> 10 seconds)\n\n---\n\n## Pdu Power Distribution\n\n# PDU (Power Distribution Unit) - High\u002FLow Voltage Power Management\n\n## Overview\nThe Power Distribution Unit (PDU) manages high-voltage DC\u002FDC converters, low-voltage power distribution, fuse\u002Frelay control, load shedding, power budgeting, battery voltage monitoring, and wake-up source management.\n\n## Core Responsibilities\n\n### 1. High-Voltage DC\u002FDC Converter\n```c\n\u002F* pdu_hv_dcdc.c - High-voltage to 12V DC\u002FDC conversion *\u002F\n#include \"pdu_hv_dcdc.h\"\n\n#define HV_INPUT_MIN_V 200\n#define HV_INPUT_MAX_V 450\n#define LV_OUTPUT_TARGET_V 14.0\n#define MAX_OUTPUT_CURRENT_A 150\n\ntypedef struct {\n    uint16_t hv_input_voltage_v;\n    float lv_output_voltage_v;\n    float output_current_a;\n    float efficiency_percent;\n    bool enabled;\n    bool fault_active;\n} DCDC_State_t;\n\nstatic DCDC_State_t g_dcdc = {0};\n\nvoid PDU_DCDC_Init(void) {\n    \u002F* Configure PWM for DC\u002FDC converter control *\u002F\n    PWM_Init(PWM_CHANNEL_DCDC, 100000);  \u002F* 100 kHz switching *\u002F\n\n    \u002F* Set initial duty cycle to 0 *\u002F\n    PWM_SetDutyCycle(PWM_CHANNEL_DCDC, 0);\n\n    g_dcdc.enabled = false;\n}\n\nvoid PDU_DCDC_Enable(void) {\n    \u002F* Safety checks *\u002F\n    g_dcdc.hv_input_voltage_v = ADC_ReadHVInput();\n\n    if (g_dcdc.hv_input_voltage_v \u003C HV_INPUT_MIN_V ||\n        g_dcdc.hv_input_voltage_v > HV_INPUT_MAX_V) {\n        g_dcdc.fault_active = true;\n        return;\n    }\n\n    \u002F* Enable DC\u002FDC converter *\u002F\n    GPIO_Set(GPIO_DCDC_ENABLE, true);\n    g_dcdc.enabled = true;\n\n    \u002F* Start voltage regulation loop *\u002F\n    PDU_DCDC_RegulationLoop();\n}\n\nvoid PDU_DCDC_RegulationLoop(void) {\n    \u002F* PI controller for output voltage regulation *\u002F\n    static float integral = 0;\n    const float Kp = 0.5;\n    const float Ki = 0.1;\n\n    while (g_dcdc.enabled) {\n        \u002F* Read output voltage and current *\u002F\n        g_dcdc.lv_output_voltage_v = ADC_ReadLVOutput();\n        g_dcdc.output_current_a = ADC_ReadOutputCurrent();\n\n        \u002F* Calculate error *\u002F\n        float error = LV_OUTPUT_TARGET_V - g_dcdc.lv_output_voltage_v;\n\n        \u002F* PI control *\u002F\n        integral += error * 0.01;  \u002F* 10ms loop time *\u002F\n        float duty_cycle = (Kp * error) + (Ki * integral);\n\n        \u002F* Clamp duty cycle *\u002F\n        if (duty_cycle > 95) duty_cycle = 95;\n        if (duty_cycle \u003C 5) duty_cycle = 5;\n\n        PWM_SetDutyCycle(PWM_CHANNEL_DCDC, duty_cycle);\n\n        \u002F* Overcurrent protection *\u002F\n        if (g_dcdc.output_current_a > MAX_OUTPUT_CURRENT_A) {\n            PDU_DCDC_Disable();\n            g_dcdc.fault_active = true;\n            DTC_SetFault(DTC_DCDC_OVERCURRENT);\n            break;\n        }\n\n        OsTask_Sleep(10);\n    }\n}\n\nvoid PDU_DCDC_Disable(void) {\n    PWM_SetDutyCycle(PWM_CHANNEL_DCDC, 0);\n    GPIO_Set(GPIO_DCDC_ENABLE, false);\n    g_dcdc.enabled = false;\n}\n```\n\n### 2. Low-Voltage Power Distribution (Fuse\u002FRelay Control)\n```c\n\u002F* pdu_lv_distribution.c - 12V power distribution and load management *\u002F\n#include \"pdu_lv_distribution.h\"\n\n#define MAX_POWER_CHANNELS 16\n\ntypedef enum {\n    LOAD_PRIORITY_CRITICAL = 0,    \u002F* Safety: always on *\u002F\n    LOAD_PRIORITY_HIGH,             \u002F* Powertrain *\u002F\n    LOAD_PRIORITY_MEDIUM,           \u002F* Comfort *\u002F\n    LOAD_PRIORITY_LOW               \u002F* Infotainment *\u002F\n} LoadPriority_t;\n\ntypedef struct {\n    const char* name;\n    uint8_t relay_pin;\n    uint8_t current_sense_adc;\n    float max_current_a;\n    LoadPriority_t priority;\n    bool enabled;\n    float measured_current_a;\n} PowerChannel_t;\n\nstatic PowerChannel_t g_power_channels[MAX_POWER_CHANNELS] = {\n    {\"BCM\", GPIO_RELAY_BCM, ADC_CH_BCM_CURRENT, 15.0, LOAD_PRIORITY_CRITICAL, true, 0},\n    {\"VCU\", GPIO_RELAY_VCU, ADC_CH_VCU_CURRENT, 10.0, LOAD_PRIORITY_CRITICAL, true, 0},\n    {\"BMS\", GPIO_RELAY_BMS, ADC_CH_BMS_CURRENT, 8.0, LOAD_PRIORITY_CRITICAL, true, 0},\n    {\"MCU\", GPIO_RELAY_MCU, ADC_CH_MCU_CURRENT, 12.0, LOAD_PRIORITY_HIGH, true, 0},\n    {\"IVI\", GPIO_RELAY_IVI, ADC_CH_IVI_CURRENT, 20.0, LOAD_PRIORITY_LOW, true, 0},\n    {\"HVAC\", GPIO_RELAY_HVAC, ADC_CH_HVAC_CURRENT, 25.0, LOAD_PRIORITY_MEDIUM, true, 0},\n    {\"Headlights\", GPIO_RELAY_LIGHTS, ADC_CH_LIGHTS_CURRENT, 10.0, LOAD_PRIORITY_HIGH, false, 0},\n    {\"USB_Ports\", GPIO_RELAY_USB, ADC_CH_USB_CURRENT, 5.0, LOAD_PRIORITY_LOW, false, 0}\n};\n\nvoid PDU_LV_Init(void) {\n    \u002F* Initialize all relay control pins *\u002F\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        GPIO_ConfigOutput(g_power_channels[i].relay_pin);\n\n        \u002F* Enable critical and high priority loads by default *\u002F\n        if (g_power_channels[i].priority \u003C= LOAD_PRIORITY_HIGH) {\n            PDU_LV_EnableChannel(i);\n        }\n    }\n}\n\nvoid PDU_LV_EnableChannel(uint8_t channel_id) {\n    if (channel_id >= MAX_POWER_CHANNELS) return;\n\n    GPIO_Set(g_power_channels[channel_id].relay_pin, true);\n    g_power_channels[channel_id].enabled = true;\n}\n\nvoid PDU_LV_DisableChannel(uint8_t channel_id) {\n    if (channel_id >= MAX_POWER_CHANNELS) return;\n\n    GPIO_Set(g_power_channels[channel_id].relay_pin, false);\n    g_power_channels[channel_id].enabled = false;\n}\n\n\u002F* Monitor current and detect overcurrent faults *\u002F\nvoid PDU_LV_MonitorCurrents(void) {\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        if (!g_power_channels[i].enabled) continue;\n\n        \u002F* Read current sensor (Hall effect sensor, 185mV\u002FA) *\u002F\n        uint16_t adc_value = ADC_Read(g_power_channels[i].current_sense_adc);\n        float voltage_mv = (adc_value * 5000.0) \u002F 4096.0;\n\n        g_power_channels[i].measured_current_a = (voltage_mv - 2500.0) \u002F 185.0;\n\n        \u002F* Check for overcurrent *\u002F\n        if (g_power_channels[i].measured_current_a > g_power_channels[i].max_current_a) {\n            \u002F* Overcurrent detected: disable channel *\u002F\n            PDU_LV_DisableChannel(i);\n            DTC_SetFault(DTC_OVERCURRENT_BASE + i);\n\n            \u002F* Log event *\u002F\n            Log(\"Overcurrent on %s: %.2f A (max %.2f A)\",\n                g_power_channels[i].name,\n                g_power_channels[i].measured_current_a,\n                g_power_channels[i].max_current_a);\n        }\n    }\n}\n```\n\n### 3. Load Shedding (Power Budget Management)\n```c\n\u002F* pdu_load_shedding.c - Intelligent load management under power constraints *\u002F\n#include \"pdu_load_shedding.h\"\n\n#define BATTERY_CRITICAL_VOLTAGE_V 11.0\n#define BATTERY_LOW_VOLTAGE_V 11.5\n\nvoid PDU_LoadShedding_Update(void) {\n    float battery_voltage = ADC_ReadBatteryVoltage();\n    float total_current = 0;\n\n    \u002F* Calculate total current draw *\u002F\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        if (g_power_channels[i].enabled) {\n            total_current += g_power_channels[i].measured_current_a;\n        }\n    }\n\n    \u002F* Check if battery voltage is low *\u002F\n    if (battery_voltage \u003C BATTERY_CRITICAL_VOLTAGE_V) {\n        \u002F* Critical: shed all non-critical loads *\u002F\n        for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n            if (g_power_channels[i].priority > LOAD_PRIORITY_CRITICAL) {\n                PDU_LV_DisableChannel(i);\n            }\n        }\n\n        Log(\"Critical battery voltage: %.2f V - load shedding active\", battery_voltage);\n\n    } else if (battery_voltage \u003C BATTERY_LOW_VOLTAGE_V) {\n        \u002F* Low: shed low-priority loads *\u002F\n        for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n            if (g_power_channels[i].priority >= LOAD_PRIORITY_LOW) {\n                PDU_LV_DisableChannel(i);\n            }\n        }\n\n        Log(\"Low battery voltage: %.2f V - reducing load\", battery_voltage);\n    }\n\n    \u002F* Check DC\u002FDC converter output current limit *\u002F\n    if (total_current > (MAX_OUTPUT_CURRENT_A * 0.9)) {\n        \u002F* Approaching limit: shed lowest priority loads *\u002F\n        for (int i = MAX_POWER_CHANNELS - 1; i >= 0; i--) {\n            if (g_power_channels[i].priority == LOAD_PRIORITY_LOW &&\n                g_power_channels[i].enabled) {\n                PDU_LV_DisableChannel(i);\n\n                \u002F* Recalculate total current *\u002F\n                total_current -= g_power_channels[i].measured_current_a;\n\n                if (total_current \u003C (MAX_OUTPUT_CURRENT_A * 0.85)) {\n                    break;  \u002F* Sufficient headroom *\u002F\n                }\n            }\n        }\n    }\n}\n```\n\n### 4. Wake-Up Source Management\n```c\n\u002F* pdu_wakeup_sources.c - Network wake-up coordination *\u002F\n#include \"pdu_wakeup_sources.h\"\n\n#define WAKEUP_CAN_TIMEOUT_MS 100\n#define SLEEP_DELAY_MS 5000\n\ntypedef enum {\n    WAKEUP_SOURCE_CAN = 0,\n    WAKEUP_SOURCE_LIN,\n    WAKEUP_SOURCE_IGNITION,\n    WAKEUP_SOURCE_DOOR,\n    WAKEUP_SOURCE_TIMER,\n    WAKEUP_SOURCE_COUNT\n} WakeupSource_t;\n\nstatic bool g_wakeup_pending[WAKEUP_SOURCE_COUNT] = {false};\n\nvoid PDU_Wakeup_OnCANActivity(void) {\n    g_wakeup_pending[WAKEUP_SOURCE_CAN] = true;\n\n    \u002F* Power up CAN transceivers *\u002F\n    GPIO_Set(GPIO_CAN_POWERTRAIN_ENABLE, true);\n    GPIO_Set(GPIO_CAN_CHASSIS_ENABLE, true);\n\n    \u002F* Notify ECUs of wake-up *\u002F\n    CAN_SendWakeupNotification();\n}\n\nvoid PDU_Sleep_Prepare(void) {\n    \u002F* Wait for all ECUs to enter sleep *\u002F\n    uint32_t start_time = GetSystemTime_ms();\n\n    while ((GetSystemTime_ms() - start_time) \u003C SLEEP_DELAY_MS) {\n        \u002F* Check for wake-up requests *\u002F\n        for (int i = 0; i \u003C WAKEUP_SOURCE_COUNT; i++) {\n            if (g_wakeup_pending[i]) {\n                \u002F* Wake-up requested: abort sleep *\u002F\n                return;\n            }\n        }\n        OsTask_Sleep(10);\n    }\n\n    \u002F* Enter sleep mode *\u002F\n    PDU_EnterSleep();\n}\n\nvoid PDU_EnterSleep(void) {\n    \u002F* Disable non-critical power channels *\u002F\n    for (int i = 0; i \u003C MAX_POWER_CHANNELS; i++) {\n        if (g_power_channels[i].priority > LOAD_PRIORITY_CRITICAL) {\n            PDU_LV_DisableChannel(i);\n        }\n    }\n\n    \u002F* Configure wake-up sources *\u002F\n    CAN_ConfigureWakeup(CAN_WAKEUP_ENABLED);\n    GPIO_ConfigureWakeup(GPIO_IGNITION, GPIO_WAKEUP_RISING_EDGE);\n\n    \u002F* Enter low-power mode *\u002F\n    Mcu_SetMode(MCU_MODE_SLEEP);\n}\n```\n\n## PDU CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: PDU VCU BMS BCM\n\n\u002F* PDU Power Status *\u002F\nBO_ 896 PDU_PowerStatus: 8 PDU\n SG_ PDU_BatteryVoltage_V : 0|16@1+ (0.01,0) [0|16] \"V\"  VCU,BMS\n SG_ PDU_DCDCOutputCurrent_A : 16|16@1+ (0.1,0) [0|200] \"A\"  VCU\n SG_ PDU_LoadSheddingActive : 32|1@1+ (0,0) [0|1] \"\"  VCU,BCM\n SG_ PDU_PowerChannelStatus : 40|16@1+ (0,0) [0|65535] \"\"  VCU\n\n\u002F* Each bit in PowerChannelStatus represents one load (0=off, 1=on) *\u002F\n```\n\n## References\n- LTC3780: High-Voltage Buck-Boost DC\u002FDC Controller\n- ISO 16750: Road vehicles - Environmental conditions and testing for electrical and electronic equipment\n- SAE J1455: Recommended Environmental Practices for Electronic Equipment Design\n- IEC 61000-4-2: EMC Immunity to Electrostatic Discharge\n\n## Common Issues\n- DC\u002FDC converter instability at high loads\n- Relay contact welding from inrush current\n- False overcurrent detection from current sensor noise\n- Wake-up failures due to CAN transceiver not powered\n\n---\n\n## Tcu Telematics Connectivity\n\n# TCU (Telematics Control Unit) - Connectivity and Remote Services\n\n## Overview\nThe Telematics Control Unit (TCU) provides 4G\u002F5G cellular connectivity, GNSS positioning, remote diagnostics, OTA updates, eCall\u002FbCall emergency services, and fleet management integration. This skill covers production-ready TCU development with modem integration.\n\n## Core Responsibilities\n\n### 1. 4G\u002F5G Modem Integration\n```c\n\u002F* tcu_modem_manager.c - Cellular modem control (Quectel\u002FSierra Wireless) *\u002F\n#include \"tcu_modem_manager.h\"\n#include \u003Cstring.h>\n#include \u003Cstdio.h>\n\n#define MODEM_UART_PORT \"\u002Fdev\u002FttyUSB2\"\n#define MODEM_BAUD_RATE 115200\n#define AT_COMMAND_TIMEOUT_MS 5000\n#define MAX_AT_RESPONSE_LENGTH 512\n\ntypedef enum {\n    MODEM_STATE_OFF = 0,\n    MODEM_STATE_INITIALIZING,\n    MODEM_STATE_REGISTERING,\n    MODEM_STATE_CONNECTED,\n    MODEM_STATE_ERROR\n} ModemState_t;\n\ntypedef struct {\n    int uart_fd;\n    ModemState_t state;\n    char imei[16];\n    char iccid[21];\n    int signal_strength_dbm;\n    char network_operator[32];\n    char ip_address[16];\n    bool data_session_active;\n} ModemContext_t;\n\nstatic ModemContext_t g_modem = {0};\n\n\u002F* AT command send\u002Freceive *\u002F\nbool TCU_Modem_SendATCommand(const char* cmd, char* response, uint16_t response_size) {\n    \u002F* Send AT command *\u002F\n    char cmd_buffer[128];\n    snprintf(cmd_buffer, sizeof(cmd_buffer), \"%s\\r\\n\", cmd);\n\n    int bytes_written = write(g_modem.uart_fd, cmd_buffer, strlen(cmd_buffer));\n    if (bytes_written \u003C 0) {\n        return false;\n    }\n\n    \u002F* Wait for response *\u002F\n    uint32_t start_time = GetSystemTime_ms();\n    int total_bytes = 0;\n\n    while ((GetSystemTime_ms() - start_time) \u003C AT_COMMAND_TIMEOUT_MS) {\n        int bytes_available = 0;\n        ioctl(g_modem.uart_fd, FIONREAD, &bytes_available);\n\n        if (bytes_available > 0) {\n            int bytes_read = read(g_modem.uart_fd,\n                                   &response[total_bytes],\n                                   response_size - total_bytes - 1);\n            if (bytes_read > 0) {\n                total_bytes += bytes_read;\n                response[total_bytes] = '\\0';\n\n                \u002F* Check for \"OK\" or \"ERROR\" *\u002F\n                if (strstr(response, \"OK\\r\\n\") != NULL) {\n                    return true;\n                }\n                if (strstr(response, \"ERROR\\r\\n\") != NULL) {\n                    return false;\n                }\n            }\n        }\n\n        usleep(10000);  \u002F* 10ms polling interval *\u002F\n    }\n\n    return false;  \u002F* Timeout *\u002F\n}\n\nvoid TCU_Modem_Init(void) {\n    \u002F* Open UART port *\u002F\n    g_modem.uart_fd = open(MODEM_UART_PORT, O_RDWR | O_NOCTTY);\n    if (g_modem.uart_fd \u003C 0) {\n        g_modem.state = MODEM_STATE_ERROR;\n        return;\n    }\n\n    \u002F* Configure UART: 115200 8N1 *\u002F\n    struct termios tty;\n    tcgetattr(g_modem.uart_fd, &tty);\n    cfsetospeed(&tty, B115200);\n    cfsetispeed(&tty, B115200);\n    tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;\n    tty.c_cflag &= ~PARENB;\n    tty.c_cflag &= ~CSTOPB;\n    tcsetattr(g_modem.uart_fd, TCSANOW, &tty);\n\n    g_modem.state = MODEM_STATE_INITIALIZING;\n\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Basic AT command check *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT\", response, sizeof(response))) {\n        g_modem.state = MODEM_STATE_ERROR;\n        return;\n    }\n\n    \u002F* Disable echo *\u002F\n    TCU_Modem_SendATCommand(\"ATE0\", response, sizeof(response));\n\n    \u002F* Get IMEI *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+GSN\", response, sizeof(response))) {\n        sscanf(response, \"%15s\", g_modem.imei);\n    }\n\n    \u002F* Get ICCID (SIM card ID) *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+CCID\", response, sizeof(response))) {\n        sscanf(response, \"+CCID: %20s\", g_modem.iccid);\n    }\n\n    \u002F* Check SIM status *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT+CPIN?\", response, sizeof(response))) {\n        g_modem.state = MODEM_STATE_ERROR;\n        return;\n    }\n\n    \u002F* Start network registration *\u002F\n    TCU_Modem_StartNetworkRegistration();\n}\n\nvoid TCU_Modem_StartNetworkRegistration(void) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Set network mode: LTE only for 4G, NR+LTE for 5G *\u002F\n    TCU_Modem_SendATCommand(\"AT+QCFG=\\\"nwscanmode\\\",3\", response, sizeof(response));\n\n    \u002F* Enable network registration URC *\u002F\n    TCU_Modem_SendATCommand(\"AT+CREG=2\", response, sizeof(response));\n\n    \u002F* Check registration status *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+CREG?\", response, sizeof(response))) {\n        int n, stat;\n        if (sscanf(response, \"+CREG: %d,%d\", &n, &stat) == 2) {\n            if (stat == 1 || stat == 5) {  \u002F* Registered (home or roaming) *\u002F\n                g_modem.state = MODEM_STATE_REGISTERED;\n                TCU_Modem_GetNetworkInfo();\n            } else {\n                g_modem.state = MODEM_STATE_REGISTERING;\n            }\n        }\n    }\n}\n\nvoid TCU_Modem_GetNetworkInfo(void) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Get signal strength *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+CSQ\", response, sizeof(response))) {\n        int rssi, ber;\n        if (sscanf(response, \"+CSQ: %d,%d\", &rssi, &ber) == 2) {\n            \u002F* Convert RSSI to dBm: dBm = -113 + 2*rssi *\u002F\n            g_modem.signal_strength_dbm = -113 + (2 * rssi);\n        }\n    }\n\n    \u002F* Get operator name *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+COPS?\", response, sizeof(response))) {\n        char operator_name[32];\n        if (sscanf(response, \"+COPS: 0,0,\\\"%31[^\\\"]\\\"\", operator_name) == 1) {\n            strncpy(g_modem.network_operator, operator_name, sizeof(g_modem.network_operator));\n        }\n    }\n}\n\nbool TCU_Modem_StartDataSession(const char* apn) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n    char cmd[128];\n\n    \u002F* Configure PDP context *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QICSGP=1,1,\\\"%s\\\",\\\"\\\",\\\"\\\",1\", apn);\n    if (!TCU_Modem_SendATCommand(cmd, response, sizeof(response))) {\n        return false;\n    }\n\n    \u002F* Activate PDP context *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT+QIACT=1\", response, sizeof(response))) {\n        return false;\n    }\n\n    \u002F* Get IP address *\u002F\n    if (TCU_Modem_SendATCommand(\"AT+QIACT?\", response, sizeof(response))) {\n        char ip_addr[16];\n        if (sscanf(response, \"+QIACT: 1,1,1,\\\"%15[^\\\"]\\\"\", ip_addr) == 1) {\n            strncpy(g_modem.ip_address, ip_addr, sizeof(g_modem.ip_address));\n            g_modem.data_session_active = true;\n            g_modem.state = MODEM_STATE_CONNECTED;\n            return true;\n        }\n    }\n\n    return false;\n}\n\n\u002F* HTTP client for cloud connectivity *\u002F\nbool TCU_Modem_HTTPPost(const char* url, const char* json_payload, char* response) {\n    char cmd[256];\n    char at_response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Configure HTTP context *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QHTTPCFG=\\\"contextid\\\",1\");\n    TCU_Modem_SendATCommand(cmd, at_response, sizeof(at_response));\n\n    \u002F* Set URL *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QHTTPURL=%zu,80\", strlen(url));\n    TCU_Modem_SendATCommand(cmd, at_response, sizeof(at_response));\n\n    \u002F* Send URL *\u002F\n    write(g_modem.uart_fd, url, strlen(url));\n    usleep(100000);\n\n    \u002F* POST data *\u002F\n    snprintf(cmd, sizeof(cmd), \"AT+QHTTPPOST=%zu,80,80\", strlen(json_payload));\n    TCU_Modem_SendATCommand(cmd, at_response, sizeof(at_response));\n\n    \u002F* Send payload *\u002F\n    write(g_modem.uart_fd, json_payload, strlen(json_payload));\n\n    \u002F* Wait for response *\u002F\n    sleep(2);\n\n    \u002F* Read response *\u002F\n    TCU_Modem_SendATCommand(\"AT+QHTTPREAD=80\", response, MAX_AT_RESPONSE_LENGTH);\n\n    return true;\n}\n```\n\n### 2. GNSS\u002FGPS Position Tracking\n```c\n\u002F* tcu_gnss_manager.c - GPS\u002FGLONASS\u002FBeiDou positioning *\u002F\n#include \"tcu_gnss_manager.h\"\n#include \u003Cmath.h>\n\n#define EARTH_RADIUS_KM 6371.0\n\ntypedef struct {\n    double latitude;\n    double longitude;\n    float altitude_m;\n    float speed_kph;\n    float heading_deg;\n    uint8_t satellites_used;\n    float hdop;  \u002F* Horizontal dilution of precision *\u002F\n    bool fix_valid;\n    uint32_t timestamp_ms;\n} GNSSPosition_t;\n\nstatic GNSSPosition_t g_gnss_position = {0};\n\nvoid TCU_GNSS_Init(void) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Enable GNSS *\u002F\n    TCU_Modem_SendATCommand(\"AT+QGPS=1\", response, sizeof(response));\n\n    \u002F* Configure GNSS to use GPS+GLONASS+BeiDou *\u002F\n    TCU_Modem_SendATCommand(\"AT+QGPSCFG=\\\"gnssconfig\\\",7\", response, sizeof(response));\n}\n\nbool TCU_GNSS_GetPosition(GNSSPosition_t* position) {\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    \u002F* Query GNSS position *\u002F\n    if (!TCU_Modem_SendATCommand(\"AT+QGPSLOC=2\", response, sizeof(response))) {\n        return false;\n    }\n\n    \u002F* Parse NMEA-like response: +QGPSLOC: \u003Ctime>,\u003Clat>,\u003Clon>,\u003Chdop>,\u003Calt>,\u003Cfix>,\u003Ccog>,\u003Cspkm>,\u003Cspkn>,\u003Cdate>,\u003Cnsat> *\u002F\n    char time_str[16], date_str[16];\n    int fix_type, nsat;\n\n    int parsed = sscanf(response,\n                        \"+QGPSLOC: %15[^,],%lf,%lf,%f,%f,%d,%f,%f,%*f,%15[^,],%d\",\n                        time_str,\n                        &position->latitude,\n                        &position->longitude,\n                        &position->hdop,\n                        &position->altitude_m,\n                        &fix_type,\n                        &position->heading_deg,\n                        &position->speed_kph,\n                        date_str,\n                        &nsat);\n\n    if (parsed >= 9) {\n        position->satellites_used = nsat;\n        position->fix_valid = (fix_type >= 2);  \u002F* 2D or 3D fix *\u002F\n        position->timestamp_ms = GetSystemTime_ms();\n\n        \u002F* Update global position *\u002F\n        memcpy(&g_gnss_position, position, sizeof(GNSSPosition_t));\n\n        return true;\n    }\n\n    return false;\n}\n\n\u002F* Calculate distance between two GPS coordinates (Haversine formula) *\u002F\nfloat TCU_GNSS_CalculateDistance_km(double lat1, double lon1, double lat2, double lon2) {\n    double dLat = (lat2 - lat1) * M_PI \u002F 180.0;\n    double dLon = (lon2 - lon1) * M_PI \u002F 180.0;\n\n    lat1 = lat1 * M_PI \u002F 180.0;\n    lat2 = lat2 * M_PI \u002F 180.0;\n\n    double a = sin(dLat \u002F 2) * sin(dLat \u002F 2) +\n               sin(dLon \u002F 2) * sin(dLon \u002F 2) * cos(lat1) * cos(lat2);\n\n    double c = 2 * atan2(sqrt(a), sqrt(1 - a));\n\n    return EARTH_RADIUS_KM * c;\n}\n\n\u002F* Geofencing: check if vehicle is inside defined boundary *\u002F\nbool TCU_GNSS_IsInsideGeofence(double center_lat, double center_lon, float radius_km) {\n    if (!g_gnss_position.fix_valid) {\n        return false;\n    }\n\n    float distance = TCU_GNSS_CalculateDistance_km(\n        g_gnss_position.latitude,\n        g_gnss_position.longitude,\n        center_lat,\n        center_lon);\n\n    return (distance \u003C= radius_km);\n}\n```\n\n### 3. Remote Diagnostics (UDS over HTTP)\n```c\n\u002F* tcu_remote_diagnostics.c - Cloud-based diagnostic services *\u002F\n#include \"tcu_remote_diagnostics.h\"\n#include \"json.h\"\n\n#define CLOUD_DIAGNOSTICS_URL \"https:\u002F\u002Ftelemetry.example.com\u002Fapi\u002Fv1\u002Fdiagnostics\"\n\ntypedef struct {\n    uint32_t dtc_code;\n    uint8_t status;\n    uint32_t occurrence_count;\n    uint32_t first_occurrence_timestamp;\n} DTC_Entry_t;\n\nvoid TCU_RemoteDiagnostics_SendDTCs(void) {\n    \u002F* Read DTCs from all ECUs via CAN *\u002F\n    DTC_Entry_t dtc_list[32];\n    uint8_t dtc_count = 0;\n\n    \u002F* Query VCU for DTCs *\u002F\n    uint8_t uds_request[] = {0x19, 0x02, 0xFF};  \u002F* ReadDTCByStatusMask *\u002F\n    uint8_t uds_response[256];\n    uint16_t response_length;\n\n    if (UDS_SendRequest(VCU_DIAGNOSTIC_ADDR, uds_request, 3,\n                        uds_response, &response_length)) {\n        \u002F* Parse DTC response *\u002F\n        for (int i = 3; i \u003C response_length; i += 4) {\n            dtc_list[dtc_count].dtc_code = (uds_response[i] \u003C\u003C 16) |\n                                            (uds_response[i+1] \u003C\u003C 8) |\n                                            uds_response[i+2];\n            dtc_list[dtc_count].status = uds_response[i+3];\n            dtc_count++;\n        }\n    }\n\n    \u002F* Build JSON payload *\u002F\n    char json_payload[1024];\n    snprintf(json_payload, sizeof(json_payload),\n             \"{\"\n             \"\\\"vin\\\":\\\"%s\\\",\"\n             \"\\\"timestamp\\\":%u,\"\n             \"\\\"dtcs\\\":[\",\n             g_vehicle_vin,\n             GetSystemTime_ms());\n\n    for (int i = 0; i \u003C dtc_count; i++) {\n        char dtc_entry[128];\n        snprintf(dtc_entry, sizeof(dtc_entry),\n                 \"{\\\"code\\\":\\\"0x%06X\\\",\\\"status\\\":0x%02X}%s\",\n                 dtc_list[i].dtc_code,\n                 dtc_list[i].status,\n                 (i \u003C dtc_count - 1) ? \",\" : \"\");\n        strcat(json_payload, dtc_entry);\n    }\n\n    strcat(json_payload, \"]}\");\n\n    \u002F* Send to cloud via HTTPS *\u002F\n    char response[512];\n    TCU_Modem_HTTPPost(CLOUD_DIAGNOSTICS_URL, json_payload, response);\n}\n\nvoid TCU_RemoteDiagnostics_ExecuteCommand(const char* command_json) {\n    \u002F* Parse remote diagnostic command *\u002F\n    json_object* root = json_tokener_parse(command_json);\n    json_object* cmd_type_obj = json_object_object_get(root, \"command\");\n\n    const char* cmd_type = json_object_get_string(cmd_type_obj);\n\n    if (strcmp(cmd_type, \"READ_DTC\") == 0) {\n        TCU_RemoteDiagnostics_SendDTCs();\n    } else if (strcmp(cmd_type, \"CLEAR_DTC\") == 0) {\n        \u002F* Send UDS ClearDiagnosticInformation *\u002F\n        uint8_t uds_clear_dtc[] = {0x14, 0xFF, 0xFF, 0xFF};\n        uint8_t response[8];\n        uint16_t response_length;\n        UDS_SendRequest(VCU_DIAGNOSTIC_ADDR, uds_clear_dtc, 4, response, &response_length);\n    } else if (strcmp(cmd_type, \"READ_DATA\") == 0) {\n        \u002F* Read live data via UDS ReadDataByIdentifier *\u002F\n        json_object* did_obj = json_object_object_get(root, \"did\");\n        uint16_t did = json_object_get_int(did_obj);\n\n        uint8_t uds_read_data[] = {0x22, (did >> 8) & 0xFF, did & 0xFF};\n        uint8_t response[256];\n        uint16_t response_length;\n\n        if (UDS_SendRequest(VCU_DIAGNOSTIC_ADDR, uds_read_data, 3,\n                            response, &response_length)) {\n            \u002F* Send response back to cloud *\u002F\n            char response_json[512];\n            snprintf(response_json, sizeof(response_json),\n                     \"{\\\"vin\\\":\\\"%s\\\",\\\"did\\\":\\\"0x%04X\\\",\\\"data\\\":\\\"\",\n                     g_vehicle_vin, did);\n\n            for (int i = 0; i \u003C response_length; i++) {\n                char hex[4];\n                snprintf(hex, sizeof(hex), \"%02X\", response[i]);\n                strcat(response_json, hex);\n            }\n\n            strcat(response_json, \"\\\"}\");\n            TCU_Modem_HTTPPost(CLOUD_DIAGNOSTICS_URL, response_json, NULL);\n        }\n    }\n\n    json_object_put(root);\n}\n```\n\n### 4. eCall \u002F bCall Emergency Services\n```c\n\u002F* tcu_ecall.c - Automatic emergency call (eCall) - EU regulation *\u002F\n#include \"tcu_ecall.h\"\n\n#define ECALL_EMERGENCY_NUMBER \"112\"\n#define BCALL_ROADSIDE_NUMBER \"1234567890\"\n\ntypedef struct {\n    uint8_t msd_format_version;\n    uint8_t message_identifier;\n    uint32_t timestamp;\n    double latitude;\n    double longitude;\n    uint8_t vehicle_class;\n    char vin[18];\n    uint8_t propulsion_storage_type;\n    bool recent_engine_status;\n} MSD_t;  \u002F* Minimum Set of Data for eCall *\u002F\n\nvoid TCU_eCall_Trigger(bool automatic) {\n    \u002F* Build MSD (Minimum Set of Data) *\u002F\n    MSD_t msd = {0};\n    msd.msd_format_version = 1;\n    msd.message_identifier = automatic ? 1 : 2;  \u002F* 1=automatic, 2=manual *\u002F\n    msd.timestamp = GetSystemTime_ms() \u002F 1000;\n\n    \u002F* Get current GPS position *\u002F\n    GNSSPosition_t position;\n    if (TCU_GNSS_GetPosition(&position)) {\n        msd.latitude = position.latitude;\n        msd.longitude = position.longitude;\n    }\n\n    msd.vehicle_class = 1;  \u002F* M1 (passenger car) *\u002F\n    strncpy(msd.vin, g_vehicle_vin, sizeof(msd.vin));\n    msd.propulsion_storage_type = 0x05;  \u002F* Electric *\u002F\n    msd.recent_engine_status = VCU_IsVehicleOn();\n\n    \u002F* Encode MSD to ASN.1 format *\u002F\n    uint8_t msd_encoded[140];  \u002F* Max 140 bytes for MSD *\u002F\n    uint16_t msd_length = TCU_eCall_EncodeMSD(&msd, msd_encoded);\n\n    \u002F* Initiate voice call to emergency services *\u002F\n    char at_cmd[64];\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    snprintf(at_cmd, sizeof(at_cmd), \"ATD%s;\", ECALL_EMERGENCY_NUMBER);\n    TCU_Modem_SendATCommand(at_cmd, response, sizeof(response));\n\n    \u002F* Wait for call connection *\u002F\n    sleep(3);\n\n    \u002F* Send MSD over in-band modem (IVS - In-Vehicle System) *\u002F\n    TCU_eCall_SendMSDInBand(msd_encoded, msd_length);\n\n    \u002F* Keep call active for voice communication *\u002F\n    \u002F* Operator will speak with occupants if possible *\u002F\n}\n\nvoid TCU_bCall_Trigger(void) {\n    \u002F* Breakdown call: non-emergency roadside assistance *\u002F\n    char at_cmd[64];\n    char response[MAX_AT_RESPONSE_LENGTH];\n\n    snprintf(at_cmd, sizeof(at_cmd), \"ATD%s;\", BCALL_ROADSIDE_NUMBER);\n    TCU_Modem_SendATCommand(at_cmd, response, sizeof(response));\n\n    \u002F* Send vehicle data to roadside assistance *\u002F\n    char json_payload[512];\n    GNSSPosition_t position;\n    TCU_GNSS_GetPosition(&position);\n\n    snprintf(json_payload, sizeof(json_payload),\n             \"{\"\n             \"\\\"vin\\\":\\\"%s\\\",\"\n             \"\\\"latitude\\\":%.6f,\"\n             \"\\\"longitude\\\":%.6f,\"\n             \"\\\"issue\\\":\\\"Breakdown assistance requested\\\"\"\n             \"}\",\n             g_vehicle_vin,\n             position.latitude,\n             position.longitude);\n\n    TCU_Modem_HTTPPost(\"https:\u002F\u002Froadside.example.com\u002Fapi\u002Fassist\", json_payload, NULL);\n}\n```\n\n### 5. OTA Download Manager\n```c\n\u002F* tcu_ota_manager.c - Over-the-Air software updates *\u002F\n#include \"tcu_ota_manager.h\"\n\n#define OTA_SERVER_URL \"https:\u002F\u002Fota.example.com\u002Fapi\u002Fv1\u002Fupdates\"\n#define OTA_CHUNK_SIZE 4096\n\ntypedef struct {\n    char version[16];\n    char ecu_target[32];\n    uint32_t file_size;\n    char download_url[256];\n    uint8_t sha256_hash[32];\n} OTAPackage_t;\n\ntypedef struct {\n    bool update_available;\n    OTAPackage_t package;\n    uint32_t bytes_downloaded;\n    uint8_t download_progress_percent;\n    bool download_complete;\n} OTAState_t;\n\nstatic OTAState_t g_ota_state = {0};\n\nbool TCU_OTA_CheckForUpdates(void) {\n    \u002F* Query OTA server for available updates *\u002F\n    char json_request[256];\n    snprintf(json_request, sizeof(json_request),\n             \"{\\\"vin\\\":\\\"%s\\\",\\\"current_versions\\\":{\"\n             \"\\\"vcu\\\":\\\"1.2.3\\\",\\\"bms\\\":\\\"2.0.1\\\",\\\"mcu\\\":\\\"3.1.0\\\"\"\n             \"}}\",\n             g_vehicle_vin);\n\n    char response[1024];\n    if (!TCU_Modem_HTTPPost(OTA_SERVER_URL, json_request, response)) {\n        return false;\n    }\n\n    \u002F* Parse JSON response *\u002F\n    json_object* root = json_tokener_parse(response);\n    json_object* update_available_obj = json_object_object_get(root, \"update_available\");\n\n    if (json_object_get_boolean(update_available_obj)) {\n        json_object* package_obj = json_object_object_get(root, \"package\");\n\n        \u002F* Extract package info *\u002F\n        json_object* version_obj = json_object_object_get(package_obj, \"version\");\n        json_object* ecu_obj = json_object_object_get(package_obj, \"ecu\");\n        json_object* size_obj = json_object_object_get(package_obj, \"size\");\n        json_object* url_obj = json_object_object_get(package_obj, \"url\");\n\n        strncpy(g_ota_state.package.version,\n                json_object_get_string(version_obj),\n                sizeof(g_ota_state.package.version));\n\n        strncpy(g_ota_state.package.ecu_target,\n                json_object_get_string(ecu_obj),\n                sizeof(g_ota_state.package.ecu_target));\n\n        g_ota_state.package.file_size = json_object_get_int(size_obj);\n\n        strncpy(g_ota_state.package.download_url,\n                json_object_get_string(url_obj),\n                sizeof(g_ota_state.package.download_url));\n\n        g_ota_state.update_available = true;\n\n        json_object_put(root);\n        return true;\n    }\n\n    json_object_put(root);\n    return false;\n}\n\nbool TCU_OTA_DownloadPackage(void) {\n    if (!g_ota_state.update_available) {\n        return false;\n    }\n\n    \u002F* Open file for writing *\u002F\n    int fd = open(\"\u002Fdata\u002Fota\u002Fupdate.bin\", O_WRONLY | O_CREAT | O_TRUNC, 0644);\n    if (fd \u003C 0) {\n        return false;\n    }\n\n    \u002F* Download in chunks *\u002F\n    uint32_t offset = 0;\n    uint8_t buffer[OTA_CHUNK_SIZE];\n\n    while (offset \u003C g_ota_state.package.file_size) {\n        uint32_t chunk_size = (g_ota_state.package.file_size - offset) > OTA_CHUNK_SIZE ?\n                               OTA_CHUNK_SIZE : (g_ota_state.package.file_size - offset);\n\n        \u002F* HTTP range request *\u002F\n        char range_header[64];\n        snprintf(range_header, sizeof(range_header),\n                 \"Range: bytes=%u-%u\", offset, offset + chunk_size - 1);\n\n        \u002F* Download chunk (simplified - use libcurl in production) *\u002F\n        if (!TCU_HTTP_DownloadChunk(g_ota_state.package.download_url,\n                                      range_header, buffer, chunk_size)) {\n            close(fd);\n            return false;\n        }\n\n        \u002F* Write to file *\u002F\n        write(fd, buffer, chunk_size);\n\n        offset += chunk_size;\n        g_ota_state.bytes_downloaded = offset;\n        g_ota_state.download_progress_percent =\n            (offset * 100) \u002F g_ota_state.package.file_size;\n\n        \u002F* Notify user via CAN *\u002F\n        CAN_SendOTAProgress(g_ota_state.download_progress_percent);\n    }\n\n    close(fd);\n    g_ota_state.download_complete = true;\n\n    \u002F* Verify SHA256 hash *\u002F\n    uint8_t calculated_hash[32];\n    TCU_OTA_CalculateSHA256(\"\u002Fdata\u002Fota\u002Fupdate.bin\", calculated_hash);\n\n    if (memcmp(calculated_hash, g_ota_state.package.sha256_hash, 32) != 0) {\n        \u002F* Hash mismatch: corrupted download *\u002F\n        unlink(\"\u002Fdata\u002Fota\u002Fupdate.bin\");\n        return false;\n    }\n\n    return true;\n}\n\nvoid TCU_OTA_InstallPackage(void) {\n    \u002F* Flash update to target ECU *\u002F\n    if (strcmp(g_ota_state.package.ecu_target, \"VCU\") == 0) {\n        \u002F* Flash VCU via UDS RequestDownload \u002F TransferData \u002F RequestTransferExit *\u002F\n        TCU_OTA_FlashECU(VCU_DIAGNOSTIC_ADDR, \"\u002Fdata\u002Fota\u002Fupdate.bin\");\n    } else if (strcmp(g_ota_state.package.ecu_target, \"BMS\") == 0) {\n        TCU_OTA_FlashECU(BMS_DIAGNOSTIC_ADDR, \"\u002Fdata\u002Fota\u002Fupdate.bin\");\n    }\n\n    \u002F* Cleanup *\u002F\n    unlink(\"\u002Fdata\u002Fota\u002Fupdate.bin\");\n    memset(&g_ota_state, 0, sizeof(OTAState_t));\n}\n```\n\n## TCU CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: TCU VCU BCM IVI\n\n\u002F* TCU Status *\u002F\nBO_ 768 TCU_Status: 8 TCU\n SG_ TCU_ModemState : 0|8@1+ (0,0) [0|4] \"\"  VCU,IVI\n SG_ TCU_SignalStrength_dBm : 8|8@1- (-113,0) [-113|0] \"dBm\"  IVI\n SG_ TCU_DataSessionActive : 16|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ TCU_GNSSFixValid : 17|1@1+ (0,0) [0|1] \"\"  VCU,IVI\n SG_ TCU_SatellitesUsed : 24|8@1+ (0,0) [0|32] \"\"  IVI\n SG_ TCU_OTAUpdateAvailable : 32|1@1+ (0,0) [0|1] \"\"  IVI\n SG_ TCU_OTADownloadProgress : 40|8@1+ (0,0) [0|100] \"%\"  IVI\n\n\u002F* TCU GPS Position *\u002F\nBO_ 769 TCU_Position: 8 TCU\n SG_ TCU_Latitude : 0|32@1+ (0.0000001,-90) [-90|90] \"deg\"  VCU,IVI\n SG_ TCU_Longitude : 32|32@1+ (0.0000001,-180) [-180|180] \"deg\"  VCU,IVI\n\n\u002F* TCU Speed and Heading *\u002F\nBO_ 770 TCU_Navigation: 8 TCU\n SG_ TCU_GPSSpeed_kph : 0|16@1+ (0.01,0) [0|300] \"km\u002Fh\"  VCU,IVI\n SG_ TCU_Heading_deg : 16|16@1+ (0.01,0) [0|360] \"deg\"  VCU,IVI\n SG_ TCU_Altitude_m : 32|16@1+ (0.1,-500) [-500|9000] \"m\"  IVI\n SG_ TCU_HDOP : 48|8@1+ (0.1,0) [0|25] \"\"  IVI\n\nVAL_ 768 TCU_ModemState 0 \"Off\" 1 \"Initializing\" 2 \"Registering\" 3 \"Connected\" 4 \"Error\";\n```\n\n## References\n- 3GPP TS 24.008: Mobile radio interface Layer 3 specification\n- ETSI EN 16072: eCall Minimum Set of Data (MSD)\n- ISO 17987: Local Interconnect Network (LIN)\n- MQTT Protocol Specification v5.0\n- AWS IoT Core: Fleet Provisioning\n\n## Common Issues\n- Modem not responding to AT commands (baud rate mismatch)\n- GPS fix lost in urban canyons or underground parking\n- OTA download interrupted due to poor signal strength\n- eCall MSD encoding errors\n- Data session dropped during handover between cell towers\n\n---\n\n## Vcu Vehicle Control\n\n# VCU (Vehicle Control Unit) for Electric Vehicles\n\n## Overview\nThe Vehicle Control Unit (VCU) is the central brain for electric vehicles, managing torque arbitration, drive modes, power distribution, regenerative braking, and traction control. This skill covers production-ready VCU development with AUTOSAR BSW integration.\n\n## Core Responsibilities\n\n### 1. Torque Arbitration\n```c\n\u002F* vcu_torque_arbiter.c - Multi-source torque request arbitration *\u002F\n#include \"vcu_torque_arbiter.h\"\n#include \"autosar_rte.h\"\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n\n#define MAX_TORQUE_NM 400\n#define MIN_REGEN_TORQUE_NM -200\n#define TORQUE_RATE_LIMIT_NM_PER_100MS 50\n\ntypedef enum {\n    TORQUE_SOURCE_DRIVER = 0,\n    TORQUE_SOURCE_CRUISE_CONTROL,\n    TORQUE_SOURCE_TRACTION_CONTROL,\n    TORQUE_SOURCE_STABILITY_CONTROL,\n    TORQUE_SOURCE_POWER_LIMIT,\n    TORQUE_SOURCE_THERMAL_LIMIT,\n    TORQUE_SOURCE_COUNT\n} TorqueSource_t;\n\ntypedef struct {\n    int16_t requested_torque_nm;\n    uint8_t priority;\n    bool active;\n    uint32_t timestamp_ms;\n} TorqueRequest_t;\n\ntypedef struct {\n    TorqueRequest_t requests[TORQUE_SOURCE_COUNT];\n    int16_t arbitrated_torque_nm;\n    int16_t previous_torque_nm;\n    TorqueSource_t active_source;\n} TorqueArbiter_t;\n\nstatic TorqueArbiter_t g_torque_arbiter = {0};\n\n\u002F* Priority levels (higher number = higher priority) *\u002F\nstatic const uint8_t TORQUE_PRIORITIES[TORQUE_SOURCE_COUNT] = {\n    [TORQUE_SOURCE_DRIVER] = 1,\n    [TORQUE_SOURCE_CRUISE_CONTROL] = 2,\n    [TORQUE_SOURCE_TRACTION_CONTROL] = 5,  \u002F* Safety critical *\u002F\n    [TORQUE_SOURCE_STABILITY_CONTROL] = 6, \u002F* Highest priority *\u002F\n    [TORQUE_SOURCE_POWER_LIMIT] = 4,\n    [TORQUE_SOURCE_THERMAL_LIMIT] = 3\n};\n\nvoid VCU_TorqueArbiter_Init(void) {\n    memset(&g_torque_arbiter, 0, sizeof(TorqueArbiter_t));\n\n    \u002F* Initialize priorities *\u002F\n    for (int i = 0; i \u003C TORQUE_SOURCE_COUNT; i++) {\n        g_torque_arbiter.requests[i].priority = TORQUE_PRIORITIES[i];\n    }\n}\n\nvoid VCU_TorqueArbiter_SetRequest(TorqueSource_t source, int16_t torque_nm, bool active) {\n    if (source >= TORQUE_SOURCE_COUNT) return;\n\n    \u002F* Clamp torque to physical limits *\u002F\n    if (torque_nm > MAX_TORQUE_NM) torque_nm = MAX_TORQUE_NM;\n    if (torque_nm \u003C MIN_REGEN_TORQUE_NM) torque_nm = MIN_REGEN_TORQUE_NM;\n\n    g_torque_arbiter.requests[source].requested_torque_nm = torque_nm;\n    g_torque_arbiter.requests[source].active = active;\n    g_torque_arbiter.requests[source].timestamp_ms = GetSystemTime_ms();\n}\n\nint16_t VCU_TorqueArbiter_Arbitrate(void) {\n    int16_t result_torque = 0;\n    uint8_t highest_priority = 0;\n    TorqueSource_t active_source = TORQUE_SOURCE_DRIVER;\n\n    \u002F* Find highest priority active request *\u002F\n    for (int i = 0; i \u003C TORQUE_SOURCE_COUNT; i++) {\n        if (g_torque_arbiter.requests[i].active &&\n            g_torque_arbiter.requests[i].priority > highest_priority) {\n            highest_priority = g_torque_arbiter.requests[i].priority;\n            result_torque = g_torque_arbiter.requests[i].requested_torque_nm;\n            active_source = (TorqueSource_t)i;\n        }\n    }\n\n    \u002F* Apply rate limiter for smoothness *\u002F\n    int16_t delta = result_torque - g_torque_arbiter.previous_torque_nm;\n    if (delta > TORQUE_RATE_LIMIT_NM_PER_100MS) {\n        result_torque = g_torque_arbiter.previous_torque_nm + TORQUE_RATE_LIMIT_NM_PER_100MS;\n    } else if (delta \u003C -TORQUE_RATE_LIMIT_NM_PER_100MS) {\n        result_torque = g_torque_arbiter.previous_torque_nm - TORQUE_RATE_LIMIT_NM_PER_100MS;\n    }\n\n    g_torque_arbiter.arbitrated_torque_nm = result_torque;\n    g_torque_arbiter.previous_torque_nm = result_torque;\n    g_torque_arbiter.active_source = active_source;\n\n    \u002F* Send to motor controller via CAN *\u002F\n    Rte_Write_MotorTorqueCmd_torque(result_torque);\n\n    return result_torque;\n}\n```\n\n### 2. Drive Modes (Eco\u002FSport\u002FCustom)\n```c\n\u002F* vcu_drive_modes.c - Drive mode management *\u002F\n#include \"vcu_drive_modes.h\"\n\ntypedef enum {\n    DRIVE_MODE_ECO = 0,\n    DRIVE_MODE_NORMAL,\n    DRIVE_MODE_SPORT,\n    DRIVE_MODE_CUSTOM\n} DriveMode_t;\n\ntypedef struct {\n    uint8_t max_power_percent;       \u002F* 0-100% *\u002F\n    uint8_t throttle_response;       \u002F* 0-100%, sensitivity *\u002F\n    uint8_t regen_strength;          \u002F* 0-100%, aggressive regen *\u002F\n    uint8_t ac_power_limit_percent;  \u002F* HVAC power limit *\u002F\n} DriveModeProfile_t;\n\nstatic const DriveModeProfile_t DRIVE_MODE_PROFILES[] = {\n    [DRIVE_MODE_ECO] = {\n        .max_power_percent = 70,\n        .throttle_response = 50,\n        .regen_strength = 80,\n        .ac_power_limit_percent = 50\n    },\n    [DRIVE_MODE_NORMAL] = {\n        .max_power_percent = 90,\n        .throttle_response = 70,\n        .regen_strength = 60,\n        .ac_power_limit_percent = 80\n    },\n    [DRIVE_MODE_SPORT] = {\n        .max_power_percent = 100,\n        .throttle_response = 100,\n        .regen_strength = 40,\n        .ac_power_limit_percent = 100\n    },\n    [DRIVE_MODE_CUSTOM] = {\n        .max_power_percent = 85,\n        .throttle_response = 75,\n        .regen_strength = 65,\n        .ac_power_limit_percent = 75\n    }\n};\n\nstatic DriveMode_t g_active_mode = DRIVE_MODE_NORMAL;\nstatic DriveModeProfile_t g_custom_profile;\n\nvoid VCU_DriveMode_Set(DriveMode_t mode) {\n    if (mode >= DRIVE_MODE_CUSTOM) return;\n    g_active_mode = mode;\n\n    \u002F* Apply profile to power management *\u002F\n    const DriveModeProfile_t* profile = &DRIVE_MODE_PROFILES[mode];\n\n    VCU_PowerManagement_SetMaxPower(profile->max_power_percent);\n    VCU_ThrottleMap_SetResponse(profile->throttle_response);\n    VCU_RegenBraking_SetStrength(profile->regen_strength);\n    VCU_HVAC_SetPowerLimit(profile->ac_power_limit_percent);\n\n    \u002F* Persist to EEPROM *\u002F\n    NvM_WriteBlock(NVM_BLOCK_DRIVE_MODE, &mode);\n}\n\nDriveMode_t VCU_DriveMode_Get(void) {\n    return g_active_mode;\n}\n\n\u002F* Throttle pedal mapping with drive mode response curve *\u002F\nint16_t VCU_ThrottleMap_ApplyResponse(uint8_t pedal_position_percent) {\n    const DriveModeProfile_t* profile = &DRIVE_MODE_PROFILES[g_active_mode];\n\n    \u002F* Non-linear response curve: torque = (pedal^2) * response_factor *\u002F\n    float normalized_pedal = pedal_position_percent \u002F 100.0f;\n    float response_factor = profile->throttle_response \u002F 100.0f;\n\n    \u002F* Sport mode: more aggressive curve (pedal^1.5) *\u002F\n    \u002F* Eco mode: gentler curve (pedal^2.5) *\u002F\n    float exponent = 2.0f;\n    if (g_active_mode == DRIVE_MODE_SPORT) {\n        exponent = 1.5f;\n    } else if (g_active_mode == DRIVE_MODE_ECO) {\n        exponent = 2.5f;\n    }\n\n    float torque_factor = powf(normalized_pedal, exponent) * response_factor;\n    int16_t max_torque = (MAX_TORQUE_NM * profile->max_power_percent) \u002F 100;\n\n    return (int16_t)(torque_factor * max_torque);\n}\n```\n\n### 3. Regenerative Braking Control\n```c\n\u002F* vcu_regen_braking.c - Regenerative braking with blending *\u002F\n#include \"vcu_regen_braking.h\"\n\n#define MIN_VEHICLE_SPEED_KPH 5      \u002F* Below this, friction only *\u002F\n#define MAX_REGEN_POWER_KW 80\n#define BATTERY_HIGH_SOC_LIMIT 95    \u002F* Reduce regen above 95% SOC *\u002F\n#define REGEN_BLEND_THRESHOLD_MS 200 \u002F* Blend window for smooth transition *\u002F\n\ntypedef struct {\n    uint8_t regen_strength_percent;\n    int16_t regen_torque_nm;\n    int16_t friction_brake_request_nm;\n    bool regen_available;\n    uint32_t last_blend_timestamp_ms;\n} RegenBraking_t;\n\nstatic RegenBraking_t g_regen_state = {0};\n\nbool VCU_Regen_IsAvailable(void) {\n    \u002F* Check conditions for regen availability *\u002F\n    uint8_t battery_soc = BMS_GetSOC_percent();\n    uint8_t battery_temp_c = BMS_GetTemperature_C();\n    uint16_t vehicle_speed_kph = VCU_GetVehicleSpeed_kph();\n\n    \u002F* No regen if: SOC too high, battery too cold, vehicle too slow *\u002F\n    if (battery_soc > BATTERY_HIGH_SOC_LIMIT) return false;\n    if (battery_temp_c \u003C 0) return false;  \u002F* Below 0°C, limit regen *\u002F\n    if (vehicle_speed_kph \u003C MIN_VEHICLE_SPEED_KPH) return false;\n\n    \u002F* Check motor controller readiness *\u002F\n    if (!MCU_IsRegenReady()) return false;\n\n    return true;\n}\n\nvoid VCU_Regen_CalculateBlending(uint8_t brake_pedal_percent,\n                                  int16_t* regen_torque_out,\n                                  int16_t* friction_brake_out) {\n    *regen_torque_out = 0;\n    *friction_brake_out = 0;\n\n    if (!VCU_Regen_IsAvailable()) {\n        \u002F* Full friction braking *\u002F\n        *friction_brake_out = (brake_pedal_percent * MAX_BRAKE_TORQUE_NM) \u002F 100;\n        return;\n    }\n\n    \u002F* Calculate maximum regen torque based on battery limits *\u002F\n    uint8_t battery_soc = BMS_GetSOC_percent();\n    float soc_factor = 1.0f;\n    if (battery_soc > 90) {\n        soc_factor = (100.0f - battery_soc) \u002F 10.0f;  \u002F* Linear reduction 90-100% *\u002F\n    }\n\n    int16_t max_regen_torque = (MIN_REGEN_TORQUE_NM * g_regen_state.regen_strength_percent) \u002F 100;\n    max_regen_torque = (int16_t)(max_regen_torque * soc_factor);\n\n    \u002F* Apply regen based on brake pedal position *\u002F\n    int16_t requested_brake_torque = (brake_pedal_percent * MAX_BRAKE_TORQUE_NM) \u002F 100;\n\n    if (abs(requested_brake_torque) \u003C= abs(max_regen_torque)) {\n        \u002F* Regen can handle it all *\u002F\n        *regen_torque_out = -requested_brake_torque;  \u002F* Negative = regen *\u002F\n        *friction_brake_out = 0;\n    } else {\n        \u002F* Blend regen + friction *\u002F\n        *regen_torque_out = max_regen_torque;\n        *friction_brake_out = requested_brake_torque - abs(max_regen_torque);\n    }\n\n    g_regen_state.regen_torque_nm = *regen_torque_out;\n    g_regen_state.friction_brake_request_nm = *friction_brake_out;\n}\n\n\u002F* One-pedal driving mode (aggressive regen on throttle release) *\u002F\nvoid VCU_Regen_OnePedalMode(uint8_t throttle_percent) {\n    if (throttle_percent > 5) {\n        g_regen_state.regen_torque_nm = 0;\n        return;\n    }\n\n    \u002F* Throttle released: apply regen proportional to vehicle speed *\u002F\n    uint16_t speed_kph = VCU_GetVehicleSpeed_kph();\n    float speed_factor = (speed_kph > 100) ? 1.0f : (speed_kph \u002F 100.0f);\n\n    int16_t one_pedal_regen = (int16_t)(MIN_REGEN_TORQUE_NM * 0.7f * speed_factor);\n\n    VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_DRIVER, one_pedal_regen, true);\n}\n```\n\n### 4. Traction Control Integration\n```c\n\u002F* vcu_traction_control.c - Wheel slip detection and mitigation *\u002F\n#include \"vcu_traction_control.h\"\n\n#define WHEEL_SLIP_THRESHOLD_PERCENT 15  \u002F* 15% slip triggers intervention *\u002F\n#define TC_TORQUE_REDUCTION_STEP_NM 20\n#define TC_RECOVERY_RATE_NM_PER_100MS 10\n\ntypedef struct {\n    float wheel_speeds_kph[4];  \u002F* FL, FR, RL, RR *\u002F\n    float wheel_slip_percent[4];\n    bool tc_active;\n    int16_t torque_reduction_nm;\n} TractionControl_t;\n\nstatic TractionControl_t g_tc_state = {0};\n\nvoid VCU_TractionControl_Update(void) {\n    \u002F* Read wheel speeds from ABS sensors via CAN *\u002F\n    g_tc_state.wheel_speeds_kph[0] = ABS_GetWheelSpeed_kph(WHEEL_FL);\n    g_tc_state.wheel_speeds_kph[1] = ABS_GetWheelSpeed_kph(WHEEL_FR);\n    g_tc_state.wheel_speeds_kph[2] = ABS_GetWheelSpeed_kph(WHEEL_RL);\n    g_tc_state.wheel_speeds_kph[3] = ABS_GetWheelSpeed_kph(WHEEL_RR);\n\n    \u002F* Calculate average driven wheel speed (RWD: rear wheels) *\u002F\n    float driven_avg = (g_tc_state.wheel_speeds_kph[2] +\n                        g_tc_state.wheel_speeds_kph[3]) \u002F 2.0f;\n\n    \u002F* Calculate average non-driven wheel speed (reference) *\u002F\n    float reference_avg = (g_tc_state.wheel_speeds_kph[0] +\n                           g_tc_state.wheel_speeds_kph[1]) \u002F 2.0f;\n\n    if (reference_avg \u003C 5.0f) {\n        g_tc_state.tc_active = false;\n        return;  \u002F* Vehicle stopped *\u002F\n    }\n\n    \u002F* Calculate slip percentage *\u002F\n    float slip_percent = ((driven_avg - reference_avg) \u002F reference_avg) * 100.0f;\n\n    if (slip_percent > WHEEL_SLIP_THRESHOLD_PERCENT) {\n        \u002F* Excessive slip detected: reduce torque *\u002F\n        g_tc_state.tc_active = true;\n        g_tc_state.torque_reduction_nm += TC_TORQUE_REDUCTION_STEP_NM;\n\n        \u002F* Cap reduction at 80% of requested torque *\u002F\n        int16_t driver_torque = VCU_TorqueArbiter_GetRequest(TORQUE_SOURCE_DRIVER);\n        if (g_tc_state.torque_reduction_nm > driver_torque * 0.8f) {\n            g_tc_state.torque_reduction_nm = (int16_t)(driver_torque * 0.8f);\n        }\n\n        \u002F* Override driver request *\u002F\n        int16_t limited_torque = driver_torque - g_tc_state.torque_reduction_nm;\n        VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_TRACTION_CONTROL,\n                                      limited_torque, true);\n    } else {\n        \u002F* No slip: gradually restore torque *\u002F\n        if (g_tc_state.torque_reduction_nm > 0) {\n            g_tc_state.torque_reduction_nm -= TC_RECOVERY_RATE_NM_PER_100MS;\n            if (g_tc_state.torque_reduction_nm \u003C 0) {\n                g_tc_state.torque_reduction_nm = 0;\n                g_tc_state.tc_active = false;\n                VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_TRACTION_CONTROL, 0, false);\n            }\n        }\n    }\n}\n```\n\n## AUTOSAR BSW Configuration\n\n### VCU RTE Configuration (ARXML)\n```xml\n\u003C!-- vcu_rte_configuration.arxml -->\n\u003CAUTOSAR xmlns=\"http:\u002F\u002Fautosar.org\u002Fschema\u002Fr4.0\">\n  \u003CAR-PACKAGES>\n    \u003CAR-PACKAGE>\n      \u003CSHORT-NAME>VCU_ComponentTypes\u003C\u002FSHORT-NAME>\n      \u003CELEMENTS>\n        \u003CAPPLICATION-SW-COMPONENT-TYPE>\n          \u003CSHORT-NAME>VCU_Controller\u003C\u002FSHORT-NAME>\n          \u003CPORTS>\n            \u003C!-- Required Ports (inputs) -->\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>ThrottlePedal\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FThrottlePedal_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>BrakePedal\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FBrakePedal_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>BatteryStatus\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FBatteryStatus_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n            \u003CR-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>WheelSpeeds\u003C\u002FSHORT-NAME>\n              \u003CREQUIRED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FWheelSpeeds_IF\n              \u003C\u002FREQUIRED-INTERFACE-TREF>\n            \u003C\u002FR-PORT-PROTOTYPE>\n\n            \u003C!-- Provided Ports (outputs) -->\n            \u003CP-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>MotorTorqueCmd\u003C\u002FSHORT-NAME>\n              \u003CPROVIDED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FMotorTorqueCmd_IF\n              \u003C\u002FPROVIDED-INTERFACE-TREF>\n            \u003C\u002FP-PORT-PROTOTYPE>\n            \u003CP-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>BrakeRequest\u003C\u002FSHORT-NAME>\n              \u003CPROVIDED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FBrakeRequest_IF\n              \u003C\u002FPROVIDED-INTERFACE-TREF>\n            \u003C\u002FP-PORT-PROTOTYPE>\n            \u003CP-PORT-PROTOTYPE>\n              \u003CSHORT-NAME>VehicleStatus\u003C\u002FSHORT-NAME>\n              \u003CPROVIDED-INTERFACE-TREF DEST=\"SENDER-RECEIVER-INTERFACE\">\n                \u002FInterfaces\u002FVehicleStatus_IF\n              \u003C\u002FPROVIDED-INTERFACE-TREF>\n            \u003C\u002FP-PORT-PROTOTYPE>\n          \u003C\u002FPORTS>\n\n          \u003CINTERNAL-BEHAVIORS>\n            \u003CSWC-INTERNAL-BEHAVIOR>\n              \u003CSHORT-NAME>VCU_InternalBehavior\u003C\u002FSHORT-NAME>\n              \u003CRUNNABLES>\n                \u003CRUNNABLE-ENTITY>\n                  \u003CSHORT-NAME>VCU_Main_10ms\u003C\u002FSHORT-NAME>\n                  \u003CMINIMUM-START-INTERVAL>0.01\u003C\u002FMINIMUM-START-INTERVAL>\n                  \u003CCAN-BE-INVOKED-CONCURRENTLY>false\u003C\u002FCAN-BE-INVOKED-CONCURRENTLY>\n                  \u003CSYMBOL>VCU_Main_Runnable\u003C\u002FSYMBOL>\n                \u003C\u002FRUNNABLE-ENTITY>\n              \u003C\u002FRUNNABLES>\n              \u003CEVENTS>\n                \u003CTIMING-EVENT>\n                  \u003CSHORT-NAME>TimingEvent_10ms\u003C\u002FSHORT-NAME>\n                  \u003CSTART-ON-EVENT-REF DEST=\"RUNNABLE-ENTITY\">\n                    \u002FVCU_ComponentTypes\u002FVCU_Controller\u002FVCU_InternalBehavior\u002FVCU_Main_10ms\n                  \u003C\u002FSTART-ON-EVENT-REF>\n                  \u003CPERIOD>0.01\u003C\u002FPERIOD>\n                \u003C\u002FTIMING-EVENT>\n              \u003C\u002FEVENTS>\n            \u003C\u002FSWC-INTERNAL-BEHAVIOR>\n          \u003C\u002FINTERNAL-BEHAVIORS>\n        \u003C\u002FAPPLICATION-SW-COMPONENT-TYPE>\n      \u003C\u002FELEMENTS>\n    \u003C\u002FAR-PACKAGE>\n  \u003C\u002FAR-PACKAGES>\n\u003C\u002FAUTOSAR>\n```\n\n## VCU CAN Database (DBC)\n```\nVERSION \"\"\n\nNS_ :\n    NS_DESC_\n    CM_\n    BA_DEF_\n    BA_\n    VAL_\n    CAT_DEF_\n    CAT_\n    FILTER\n    BA_DEF_DEF_\n    EV_DATA_\n    ENVVAR_DATA_\n    SGTYPE_\n    SGTYPE_VAL_\n    BA_DEF_SGTYPE_\n    BA_SGTYPE_\n    SIG_TYPE_REF_\n    VAL_TABLE_\n    SIG_GROUP_\n    SIG_VALTYPE_\n    SIGTYPE_VALTYPE_\n    BO_TX_BU_\n    BA_DEF_REL_\n    BA_REL_\n    BA_SGTYPE_REL_\n    SG_MUL_VAL_\n\nBS_:\n\nBU_: VCU MCU BMS BCM\n\n\u002F* VCU -> MCU: Motor Torque Command *\u002F\nBO_ 256 VCU_MotorCmd: 8 VCU\n SG_ VCU_TorqueRequest : 0|16@1+ (-2000,0) [-2000|4000] \"0.1Nm\"  MCU\n SG_ VCU_SpeedLimit : 16|16@1+ (0,0) [0|18000] \"0.1rpm\"  MCU\n SG_ VCU_ControlMode : 32|8@1+ (0,0) [0|3] \"\"  MCU\n SG_ VCU_TorqueValid : 40|1@1+ (0,0) [0|1] \"\"  MCU\n SG_ VCU_TorqueSource : 41|3@1+ (0,0) [0|7] \"\"  MCU\n SG_ VCU_ChecksumTorque : 56|8@1+ (0,0) [0|255] \"\"  MCU\n\n\u002F* VCU -> BCM: Brake Request *\u002F\nBO_ 257 VCU_BrakeCmd: 8 VCU\n SG_ VCU_FrictionBrake_FL : 0|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n SG_ VCU_FrictionBrake_FR : 16|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n SG_ VCU_FrictionBrake_RL : 32|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n SG_ VCU_FrictionBrake_RR : 48|16@1+ (0,0) [0|3000] \"0.1Nm\"  BCM\n\n\u002F* VCU -> CAN Bus: Vehicle Status *\u002F\nBO_ 258 VCU_VehicleStatus: 8 VCU\n SG_ VCU_DriveMode : 0|8@1+ (0,0) [0|3] \"\"  BCM,MCU,BMS\n SG_ VCU_TractionControlActive : 8|1@1+ (0,0) [0|1] \"\"  BCM\n SG_ VCU_RegenAvailable : 9|1@1+ (0,0) [0|1] \"\"  BCM\n SG_ VCU_PowerLimitActive : 10|1@1+ (0,0) [0|1] \"\"  BCM\n SG_ VCU_VehicleReady : 11|1@1+ (0,0) [0|1] \"\"  BCM,MCU\n SG_ VCU_EstimatedRange_km : 16|16@1+ (0,0) [0|1000] \"km\"  BCM\n\nVAL_ 256 VCU_ControlMode 0 \"Torque_Mode\" 1 \"Speed_Mode\" 2 \"Power_Mode\" 3 \"Disabled\";\nVAL_ 256 VCU_TorqueSource 0 \"Driver\" 1 \"CruiseControl\" 2 \"TractionControl\" 3 \"StabilityControl\" 4 \"PowerLimit\" 5 \"ThermalLimit\";\nVAL_ 258 VCU_DriveMode 0 \"Eco\" 1 \"Normal\" 2 \"Sport\" 3 \"Custom\";\n```\n\n## Power Distribution Strategy\n```c\n\u002F* vcu_power_distribution.c - Energy management and power budgeting *\u002F\n#include \"vcu_power_management.h\"\n\n#define BATTERY_MAX_POWER_KW 150\n#define HVAC_MAX_POWER_KW 6\n#define DCDC_MAX_POWER_KW 3\n#define AUXILIARY_MAX_POWER_KW 2\n\ntypedef struct {\n    float available_battery_power_kw;\n    float allocated_propulsion_kw;\n    float allocated_hvac_kw;\n    float allocated_auxiliary_kw;\n    bool power_limit_active;\n} PowerBudget_t;\n\nstatic PowerBudget_t g_power_budget = {0};\n\nvoid VCU_PowerManagement_Update(void) {\n    \u002F* Get battery discharge limit from BMS *\u002F\n    g_power_budget.available_battery_power_kw = BMS_GetMaxDischargePower_kW();\n\n    \u002F* Propulsion has first priority *\u002F\n    float requested_propulsion_kw = VCU_GetRequestedPropulsionPower_kW();\n\n    \u002F* HVAC second priority (can be reduced in power-limited situations) *\u002F\n    float requested_hvac_kw = HVAC_GetRequestedPower_kW();\n\n    \u002F* Allocate power with priorities *\u002F\n    float total_requested = requested_propulsion_kw + requested_hvac_kw +\n                            DCDC_MAX_POWER_KW + AUXILIARY_MAX_POWER_KW;\n\n    if (total_requested \u003C= g_power_budget.available_battery_power_kw) {\n        \u002F* No power limiting needed *\u002F\n        g_power_budget.allocated_propulsion_kw = requested_propulsion_kw;\n        g_power_budget.allocated_hvac_kw = requested_hvac_kw;\n        g_power_budget.power_limit_active = false;\n    } else {\n        \u002F* Power limiting: reduce HVAC first, then propulsion *\u002F\n        g_power_budget.power_limit_active = true;\n\n        float available_for_hvac = g_power_budget.available_battery_power_kw -\n                                    requested_propulsion_kw - DCDC_MAX_POWER_KW -\n                                    AUXILIARY_MAX_POWER_KW;\n\n        if (available_for_hvac >= requested_hvac_kw) {\n            \u002F* Can still power HVAC fully, limit propulsion *\u002F\n            g_power_budget.allocated_hvac_kw = requested_hvac_kw;\n            g_power_budget.allocated_propulsion_kw = g_power_budget.available_battery_power_kw -\n                                                      requested_hvac_kw - DCDC_MAX_POWER_KW -\n                                                      AUXILIARY_MAX_POWER_KW;\n        } else {\n            \u002F* Limit HVAC *\u002F\n            g_power_budget.allocated_hvac_kw = available_for_hvac > 0 ? available_for_hvac : 0;\n            g_power_budget.allocated_propulsion_kw = requested_propulsion_kw;\n        }\n\n        \u002F* Apply power limit to torque command *\u002F\n        int16_t limited_torque = VCU_CalculateTorqueFromPower(\n            g_power_budget.allocated_propulsion_kw);\n        VCU_TorqueArbiter_SetRequest(TORQUE_SOURCE_POWER_LIMIT, limited_torque, true);\n    }\n}\n```\n\n## ISO 26262 Safety Mechanisms\n\n### Torque Plausibility Check\n```c\n\u002F* Safety monitor for torque command plausibility *\u002F\nvoid VCU_Safety_TorquePlausibilityCheck(void) {\n    int16_t commanded_torque = VCU_TorqueArbiter_GetArbitratedTorque();\n    int16_t measured_torque = MCU_GetActualTorque();\n\n    int16_t torque_error = abs(commanded_torque - measured_torque);\n\n    if (torque_error > TORQUE_PLAUSIBILITY_THRESHOLD_NM) {\n        \u002F* Torque mismatch detected *\u002F\n        g_safety_fault_counter++;\n\n        if (g_safety_fault_counter > SAFETY_FAULT_THRESHOLD) {\n            \u002F* Enter safe state: zero torque request *\u002F\n            VCU_EnterSafeState();\n            DTC_SetFault(DTC_TORQUE_PLAUSIBILITY_FAULT);\n        }\n    } else {\n        if (g_safety_fault_counter > 0) {\n            g_safety_fault_counter--;\n        }\n    }\n}\n```\n\n## Testing Requirements\n\n### HIL Test Cases\n```python\n# vcu_hil_test.py - Hardware-in-the-Loop test suite\nimport can\nimport pytest\nimport time\n\nclass TestVCUTorqueArbiter:\n    def test_driver_torque_request_normal(self, vcu_hil):\n        \"\"\"Verify driver torque request in normal conditions\"\"\"\n        # Set throttle pedal to 50%\n        vcu_hil.set_analog_input(\"ThrottlePedal\", 2.5)  # 0-5V\n        time.sleep(0.05)\n\n        # Read CAN message VCU_MotorCmd\n        msg = vcu_hil.can_bus.recv(timeout=0.1)\n        assert msg.arbitration_id == 0x100  # 256 decimal\n\n        torque_request = int.from_bytes(msg.data[0:2], 'little', signed=True) * 0.1\n        assert 150 \u003C torque_request \u003C 250  # Expected range for 50% throttle in Normal mode\n\n    def test_traction_control_intervention(self, vcu_hil):\n        \"\"\"Verify traction control reduces torque on wheel slip\"\"\"\n        # Simulate wheel slip: driven wheels faster than reference\n        vcu_hil.inject_can_message(0x220, [0x64, 0x00, 0x64, 0x00, 0xC8, 0x00, 0xC8, 0x00])\n        # Front wheels: 100 kph, Rear wheels: 200 kph (100% slip)\n\n        time.sleep(0.2)\n\n        # Verify VCU_VehicleStatus shows TC active\n        status_msg = vcu_hil.read_can_message(0x102)\n        tc_active = (status_msg.data[1] & 0x01) == 0x01\n        assert tc_active\n\n        # Verify torque reduction\n        torque_msg = vcu_hil.read_can_message(0x100)\n        torque_source = (torque_msg.data[5] >> 1) & 0x07\n        assert torque_source == 2  # TractionControl source\n```\n\n## References\n- ISO 26262-6: Product development at the software level\n- AUTOSAR Classic Platform R20-11: RTE Specification\n- SAE J2735: Dedicated Short Range Communications (DSRC) Message Set Dictionary\n- ECE R13: Uniform provisions concerning the approval of vehicles of categories M, N and O with regard to braking\n\n## Common Issues\n- Torque command jitter due to insufficient rate limiting\n- Regen braking not blending smoothly with friction brakes\n- Traction control oscillation from aggressive intervention\n- Drive mode changes causing torque steps\n- Power limiting not respecting HVAC comfort requirements\n\n---\n\n## Vgu Gateway Architecture\n\n# VGU (Vehicle Gateway Unit) - Network Routing and Security\n\n## Overview\nThe Vehicle Gateway Unit (VGU) acts as the central network hub, routing messages between different vehicle networks (CAN-to-Ethernet, CAN-to-CAN), implementing security firewalls, handling diagnostic access (DoIP), and managing network wake-up. This skill covers production-ready gateway development with AUTOSAR COM stack.\n\n## Core Responsibilities\n\n### 1. Network Routing (CAN-to-Ethernet, CAN-to-CAN)\n```c\n\u002F* vgu_routing_engine.c - Multi-network message routing *\u002F\n#include \"vgu_routing_engine.h\"\n#include \"Com.h\"\n#include \"PduR.h\"\n#include \u003Cstdint.h>\n#include \u003Cstdbool.h>\n\n#define MAX_ROUTING_ENTRIES 256\n#define MAX_NETWORKS 8\n\ntypedef enum {\n    NETWORK_CAN_POWERTRAIN = 0,\n    NETWORK_CAN_CHASSIS,\n    NETWORK_CAN_BODY,\n    NETWORK_CAN_INFOTAINMENT,\n    NETWORK_ETH_BACKBONE,\n    NETWORK_LIN_DOOR,\n    NETWORK_FLEXRAY_ADAS,\n    NETWORK_INVALID\n} NetworkID_t;\n\ntypedef enum {\n    ROUTING_MODE_UNCONDITIONAL,  \u002F* Always route *\u002F\n    ROUTING_MODE_CONDITIONAL,    \u002F* Route based on vehicle mode *\u002F\n    ROUTING_MODE_FILTERED,       \u002F* Apply gateway filter *\u002F\n    ROUTING_MODE_BLOCKED         \u002F* Never route (security) *\u002F\n} RoutingMode_t;\n\ntypedef struct {\n    uint32_t source_pdu_id;\n    NetworkID_t source_network;\n    uint32_t dest_pdu_id;\n    NetworkID_t dest_network;\n    RoutingMode_t routing_mode;\n    uint16_t cycle_time_ms;       \u002F* For cyclic routing *\u002F\n    bool transform_required;      \u002F* Endianness\u002Fscaling conversion *\u002F\n    uint32_t route_count;         \u002F* Statistics *\u002F\n} RoutingEntry_t;\n\nstatic RoutingEntry_t g_routing_table[MAX_ROUTING_ENTRIES];\nstatic uint16_t g_routing_table_size = 0;\n\n\u002F* Example routing table configuration *\u002F\nstatic const RoutingEntry_t DEFAULT_ROUTING_TABLE[] = {\n    \u002F* VCU Motor Command: CAN Powertrain -> Ethernet Backbone *\u002F\n    {\n        .source_pdu_id = 0x100,\n        .source_network = NETWORK_CAN_POWERTRAIN,\n        .dest_pdu_id = 0x100,\n        .dest_network = NETWORK_ETH_BACKBONE,\n        .routing_mode = ROUTING_MODE_UNCONDITIONAL,\n        .cycle_time_ms = 10,\n        .transform_required = false\n    },\n    \u002F* BMS Battery Status: CAN Powertrain -> CAN Infotainment (for display) *\u002F\n    {\n        .source_pdu_id = 0x300,\n        .source_network = NETWORK_CAN_POWERTRAIN,\n        .dest_pdu_id = 0x300,\n        .dest_network = NETWORK_CAN_INFOTAINMENT,\n        .routing_mode = ROUTING_MODE_FILTERED,\n        .cycle_time_ms = 100,\n        .transform_required = false\n    },\n    \u002F* IVI User Input: CAN Infotainment -> Ethernet Backbone (blocked in drive) *\u002F\n    {\n        .source_pdu_id = 0x400,\n        .source_network = NETWORK_CAN_INFOTAINMENT,\n        .dest_pdu_id = 0x400,\n        .dest_network = NETWORK_ETH_BACKBONE,\n        .routing_mode = ROUTING_MODE_CONDITIONAL,\n        .cycle_time_ms = 50,\n        .transform_required = false\n    },\n    \u002F* ADAS Camera: Ethernet -> CAN Chassis (lane keeping) *\u002F\n    {\n        .source_pdu_id = 0x500,\n        .source_network = NETWORK_ETH_BACKBONE,\n        .dest_pdu_id = 0x500,\n        .dest_network = NETWORK_CAN_CHASSIS,\n        .routing_mode = ROUTING_MODE_UNCONDITIONAL,\n        .cycle_time_ms = 20,\n        .transform_required = true  \u002F* SOME\u002FIP to CAN conversion *\u002F\n    }\n};\n\nvoid VGU_RoutingEngine_Init(void) {\n    \u002F* Load default routing table *\u002F\n    g_routing_table_size = sizeof(DEFAULT_ROUTING_TABLE) \u002F sizeof(RoutingEntry_t);\n    memcpy(g_routing_table, DEFAULT_ROUTING_TABLE, sizeof(DEFAULT_ROUTING_TABLE));\n\n    \u002F* Initialize network interfaces *\u002F\n    for (int i = 0; i \u003C MAX_NETWORKS; i++) {\n        VGU_Network_Init((NetworkID_t)i);\n    }\n\n    \u002F* Load routing table from NVM if available *\u002F\n    NvM_ReadBlock(NVM_BLOCK_ROUTING_TABLE, g_routing_table);\n}\n\nStd_ReturnType VGU_RouteMessage(uint32_t source_pdu_id,\n                                 NetworkID_t source_network,\n                                 const uint8_t* data,\n                                 uint8_t length) {\n    \u002F* Find routing entry *\u002F\n    for (uint16_t i = 0; i \u003C g_routing_table_size; i++) {\n        RoutingEntry_t* entry = &g_routing_table[i];\n\n        if (entry->source_pdu_id == source_pdu_id &&\n            entry->source_network == source_network) {\n\n            \u002F* Check routing mode *\u002F\n            if (!VGU_RoutingAllowed(entry)) {\n                return E_NOT_OK;\n            }\n\n            \u002F* Apply security filter *\u002F\n            if (!VGU_SecurityFilter_Check(entry, data, length)) {\n                VGU_SecurityEvent_Log(SECURITY_EVENT_FILTER_REJECT, source_pdu_id);\n                return E_NOT_OK;\n            }\n\n            \u002F* Transform if required *\u002F\n            uint8_t transformed_data[64];\n            uint8_t transformed_length = length;\n\n            if (entry->transform_required) {\n                VGU_DataTransform(data, length, transformed_data,\n                                   &transformed_length, entry);\n            } else {\n                memcpy(transformed_data, data, length);\n            }\n\n            \u002F* Route to destination network *\u002F\n            Std_ReturnType result = VGU_Network_Transmit(\n                entry->dest_network,\n                entry->dest_pdu_id,\n                transformed_data,\n                transformed_length);\n\n            if (result == E_OK) {\n                entry->route_count++;\n            }\n\n            return result;\n        }\n    }\n\n    \u002F* No routing entry found *\u002F\n    return E_NOT_OK;\n}\n\nbool VGU_RoutingAllowed(const RoutingEntry_t* entry) {\n    switch (entry->routing_mode) {\n        case ROUTING_MODE_UNCONDITIONAL:\n            return true;\n\n        case ROUTING_MODE_CONDITIONAL:\n            \u002F* Example: block IVI messages when vehicle is driving *\u002F\n            if (entry->source_network == NETWORK_CAN_INFOTAINMENT) {\n                uint16_t vehicle_speed = VCU_GetVehicleSpeed_kph();\n                return (vehicle_speed \u003C 5);  \u002F* Only allow when stopped *\u002F\n            }\n            return true;\n\n        case ROUTING_MODE_FILTERED:\n            \u002F* Additional filtering logic *\u002F\n            return true;\n\n        case ROUTING_MODE_BLOCKED:\n            return false;\n\n        default:\n            return false;\n    }\n}\n\n\u002F* CAN-to-Ethernet transformation (CAN frame -> SOME\u002FIP) *\u002F\nvoid VGU_DataTransform_CANtoETH(const uint8_t* can_data, uint8_t can_length,\n                                 uint8_t* eth_data, uint8_t* eth_length) {\n    \u002F* SOME\u002FIP header: Service ID, Method ID, Length, Client ID, Session ID, ... *\u002F\n    uint16_t service_id = 0x1234;\n    uint16_t method_id = 0x0001;\n\n    \u002F* Build SOME\u002FIP message *\u002F\n    eth_data[0] = (service_id >> 8) & 0xFF;\n    eth_data[1] = service_id & 0xFF;\n    eth_data[2] = (method_id >> 8) & 0xFF;\n    eth_data[3] = method_id & 0xFF;\n\n    \u002F* Length field *\u002F\n    uint32_t payload_length = can_length + 8;  \u002F* Payload + SOME\u002FIP overhead *\u002F\n    eth_data[4] = (payload_length >> 24) & 0xFF;\n    eth_data[5] = (payload_length >> 16) & 0xFF;\n    eth_data[6] = (payload_length >> 8) & 0xFF;\n    eth_data[7] = payload_length & 0xFF;\n\n    \u002F* Copy CAN payload *\u002F\n    memcpy(&eth_data[16], can_data, can_length);\n\n    *eth_length = 16 + can_length;\n}\n```\n\n### 2. Security Firewall\n```c\n\u002F* vgu_security_firewall.c - Message filtering and intrusion detection *\u002F\n#include \"vgu_security_firewall.h\"\n\n#define MAX_FIREWALL_RULES 128\n#define MAX_ALLOWED_CAN_IDS 512\n#define ANOMALY_THRESHOLD 10\n\ntypedef enum {\n    FIREWALL_ACTION_ALLOW = 0,\n    FIREWALL_ACTION_BLOCK,\n    FIREWALL_ACTION_LOG,\n    FIREWALL_ACTION_ALERT\n} FirewallAction_t;\n\ntypedef struct {\n    uint32_t can_id;\n    NetworkID_t network;\n    FirewallAction_t action;\n    uint32_t min_cycle_time_ms;  \u002F* Minimum expected cycle time *\u002F\n    uint32_t max_cycle_time_ms;  \u002F* Maximum expected cycle time *\u002F\n    uint8_t expected_dlc;\n    bool require_authentication;\n} FirewallRule_t;\n\ntypedef struct {\n    uint32_t can_id;\n    uint32_t last_rx_timestamp_ms;\n    uint32_t rx_count;\n    uint32_t anomaly_count;\n} MessageMonitor_t;\n\nstatic FirewallRule_t g_firewall_rules[MAX_FIREWALL_RULES];\nstatic MessageMonitor_t g_message_monitors[MAX_ALLOWED_CAN_IDS];\n\n\u002F* Example firewall rules *\u002F\nstatic const FirewallRule_t DEFAULT_FIREWALL_RULES[] = {\n    \u002F* VCU Motor Command: strict timing, authenticated *\u002F\n    {\n        .can_id = 0x100,\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_ALLOW,\n        .min_cycle_time_ms = 8,\n        .max_cycle_time_ms = 12,\n        .expected_dlc = 8,\n        .require_authentication = true\n    },\n    \u002F* BMS Battery Status: allow with timing check *\u002F\n    {\n        .can_id = 0x300,\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_ALLOW,\n        .min_cycle_time_ms = 90,\n        .max_cycle_time_ms = 110,\n        .expected_dlc = 8,\n        .require_authentication = false\n    },\n    \u002F* Diagnostic request: block unless diagnostic session active *\u002F\n    {\n        .can_id = 0x7DF,  \u002F* OBD-II diagnostic request *\u002F\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_LOG,\n        .min_cycle_time_ms = 0,\n        .max_cycle_time_ms = 0xFFFFFFFF,\n        .expected_dlc = 8,\n        .require_authentication = true\n    },\n    \u002F* Unknown high-priority CAN ID: block and alert *\u002F\n    {\n        .can_id = 0x000,  \u002F* High priority range 0x000-0x0FF *\u002F\n        .network = NETWORK_CAN_POWERTRAIN,\n        .action = FIREWALL_ACTION_BLOCK,\n        .min_cycle_time_ms = 0,\n        .max_cycle_time_ms = 0xFFFFFFFF,\n        .expected_dlc = 0,\n        .require_authentication = false\n    }\n};\n\nvoid VGU_SecurityFirewall_Init(void) {\n    memcpy(g_firewall_rules, DEFAULT_FIREWALL_RULES, sizeof(DEFAULT_FIREWALL_RULES));\n    memset(g_message_monitors, 0, sizeof(g_message_monitors));\n}\n\nbool VGU_SecurityFilter_Check(const RoutingEntry_t* route,\n                               const uint8_t* data,\n                               uint8_t length) {\n    uint32_t can_id = route->source_pdu_id;\n    uint32_t current_time_ms = GetSystemTime_ms();\n\n    \u002F* Find firewall rule *\u002F\n    FirewallRule_t* rule = NULL;\n    for (int i = 0; i \u003C MAX_FIREWALL_RULES; i++) {\n        if (g_firewall_rules[i].can_id == can_id &&\n            g_firewall_rules[i].network == route->source_network) {\n            rule = &g_firewall_rules[i];\n            break;\n        }\n    }\n\n    if (rule == NULL) {\n        \u002F* No rule defined: default deny *\u002F\n        return false;\n    }\n\n    \u002F* Check DLC *\u002F\n    if (rule->expected_dlc > 0 && length != rule->expected_dlc) {\n        VGU_SecurityEvent_Log(SECURITY_EVENT_DLC_MISMATCH, can_id);\n        return false;\n    }\n\n    \u002F* Find message monitor entry *\u002F\n    MessageMonitor_t* monitor = NULL;\n    for (int i = 0; i \u003C MAX_ALLOWED_CAN_IDS; i++) {\n        if (g_message_monitors[i].can_id == can_id) {\n            monitor = &g_message_monitors[i];\n            break;\n        } else if (g_message_monitors[i].can_id == 0) {\n            \u002F* Create new monitor entry *\u002F\n            monitor = &g_message_monitors[i];\n            monitor->can_id = can_id;\n            break;\n        }\n    }\n\n    if (monitor != NULL) {\n        \u002F* Check cycle time *\u002F\n        if (monitor->last_rx_timestamp_ms > 0) {\n            uint32_t delta_ms = current_time_ms - monitor->last_rx_timestamp_ms;\n\n            if (delta_ms \u003C rule->min_cycle_time_ms ||\n                delta_ms > rule->max_cycle_time_ms) {\n                monitor->anomaly_count++;\n\n                if (monitor->anomaly_count > ANOMALY_THRESHOLD) {\n                    VGU_SecurityEvent_Log(SECURITY_EVENT_TIMING_VIOLATION, can_id);\n                    \u002F* Don't block, but alert *\u002F\n                }\n            } else {\n                \u002F* Reset anomaly counter on valid timing *\u002F\n                if (monitor->anomaly_count > 0) {\n                    monitor->anomaly_count--;\n                }\n            }\n        }\n\n        monitor->last_rx_timestamp_ms = current_time_ms;\n        monitor->rx_count++;\n    }\n\n    \u002F* Check authentication if required *\u002F\n    if (rule->require_authentication) {\n        if (!VGU_Security_VerifyMAC(data, length)) {\n            VGU_SecurityEvent_Log(SECURITY_EVENT_AUTH_FAIL, can_id);\n            return false;\n        }\n    }\n\n    \u002F* Apply firewall action *\u002F\n    switch (rule->action) {\n        case FIREWALL_ACTION_ALLOW:\n            return true;\n\n        case FIREWALL_ACTION_BLOCK:\n            VGU_SecurityEvent_Log(SECURITY_EVENT_BLOCKED, can_id);\n            return false;\n\n        case FIREWALL_ACTION_LOG:\n            VGU_SecurityEvent_Log(SECURITY_EVENT_LOGGED, can_id);\n            return true;\n\n        case FIREWALL_ACTION_ALERT:\n            VGU_SecurityEvent_Log(SECURITY_EVENT_ALERT, can_id);\n            return true;\n\n        default:\n            return false;\n    }\n}\n\n\u002F* SecOC (Secure Onboard Communication) - MAC verification *\u002F\nbool VGU_Security_VerifyMAC(const uint8_t* data, uint8_t length) {\n    \u002F* Extract MAC from last 8 bytes *\u002F\n    uint64_t received_mac = 0;\n    for (int i = 0; i \u003C 8; i++) {\n        received_mac = (received_mac \u003C\u003C 8) | data[length - 8 + i];\n    }\n\n    \u002F* Calculate expected MAC using CMAC-AES *\u002F\n    uint64_t calculated_mac = VGU_Crypto_CalculateMAC(data, length - 8);\n\n    return (received_mac == calculated_mac);\n}\n```\n\n### 3. Diagnostic Gateway (DoIP - Diagnostics over IP)\n```c\n\u002F* vgu_doip_gateway.c - ISO 13400 Diagnostic over IP *\u002F\n#include \"vgu_doip_gateway.h\"\n\n#define DOIP_UDP_PORT 13400\n#define DOIP_TCP_PORT 13400\n#define MAX_DOIP_CONNECTIONS 4\n\ntypedef enum {\n    DOIP_VEHICLE_ANNOUNCEMENT = 0x0004,\n    DOIP_ROUTING_ACTIVATION_REQUEST = 0x0005,\n    DOIP_ROUTING_ACTIVATION_RESPONSE = 0x0006,\n    DOIP_DIAGNOSTIC_MESSAGE = 0x8001,\n    DOIP_DIAGNOSTIC_MESSAGE_ACK = 0x8002,\n    DOIP_DIAGNOSTIC_MESSAGE_NACK = 0x8003\n} DoIPMessageType_t;\n\ntypedef struct {\n    uint8_t protocol_version;\n    uint8_t inverse_protocol_version;\n    uint16_t payload_type;\n    uint32_t payload_length;\n} DoIPHeader_t;\n\ntypedef struct {\n    int socket_fd;\n    bool active;\n    uint16_t source_address;\n    uint16_t target_address;\n    uint8_t activation_type;\n    uint32_t last_activity_ms;\n} DoIPConnection_t;\n\nstatic DoIPConnection_t g_doip_connections[MAX_DOIP_CONNECTIONS];\n\nvoid VGU_DoIP_Init(void) {\n    \u002F* Create UDP socket for vehicle announcement *\u002F\n    int udp_socket = socket(AF_INET, SOCK_DGRAM, 0);\n    struct sockaddr_in addr = {\n        .sin_family = AF_INET,\n        .sin_port = htons(DOIP_UDP_PORT),\n        .sin_addr.s_addr = INADDR_ANY\n    };\n    bind(udp_socket, (struct sockaddr*)&addr, sizeof(addr));\n\n    \u002F* Create TCP socket for diagnostic communication *\u002F\n    int tcp_socket = socket(AF_INET, SOCK_STREAM, 0);\n    bind(tcp_socket, (struct sockaddr*)&addr, sizeof(addr));\n    listen(tcp_socket, MAX_DOIP_CONNECTIONS);\n\n    \u002F* Send periodic vehicle announcement *\u002F\n    VGU_DoIP_SendVehicleAnnouncement(udp_socket);\n}\n\nvoid VGU_DoIP_SendVehicleAnnouncement(int udp_socket) {\n    uint8_t announcement[32];\n    DoIPHeader_t* header = (DoIPHeader_t*)announcement;\n\n    header->protocol_version = 0x02;  \u002F* ISO 13400-2:2012 *\u002F\n    header->inverse_protocol_version = 0xFD;\n    header->payload_type = htons(DOIP_VEHICLE_ANNOUNCEMENT);\n    header->payload_length = htonl(14);\n\n    \u002F* Payload: VIN (17 bytes) + Logical Address (2 bytes) + EID (6 bytes) + GID (6 bytes) *\u002F\n    const char* vin = \"1HGBH41JXMN109186\";\n    memcpy(&announcement[8], vin, 17);\n\n    uint16_t logical_address = 0x0001;  \u002F* Gateway address *\u002F\n    memcpy(&announcement[25], &logical_address, 2);\n\n    \u002F* Broadcast announcement *\u002F\n    struct sockaddr_in broadcast_addr = {\n        .sin_family = AF_INET,\n        .sin_port = htons(DOIP_UDP_PORT),\n        .sin_addr.s_addr = htonl(INADDR_BROADCAST)\n    };\n    sendto(udp_socket, announcement, 32, 0,\n           (struct sockaddr*)&broadcast_addr, sizeof(broadcast_addr));\n}\n\nvoid VGU_DoIP_HandleRoutingActivation(int tcp_socket,\n                                       const uint8_t* request,\n                                       uint16_t length) {\n    \u002F* Parse routing activation request *\u002F\n    uint16_t source_address = (request[8] \u003C\u003C 8) | request[9];\n    uint8_t activation_type = request[10];\n\n    \u002F* Find available connection slot *\u002F\n    DoIPConnection_t* conn = NULL;\n    for (int i = 0; i \u003C MAX_DOIP_CONNECTIONS; i++) {\n        if (!g_doip_connections[i].active) {\n            conn = &g_doip_connections[i];\n            break;\n        }\n    }\n\n    uint8_t response_code;\n    if (conn != NULL) {\n        conn->socket_fd = tcp_socket;\n        conn->active = true;\n        conn->source_address = source_address;\n        conn->activation_type = activation_type;\n        conn->last_activity_ms = GetSystemTime_ms();\n\n        response_code = 0x10;  \u002F* Routing successfully activated *\u002F\n    } else {\n        response_code = 0x02;  \u002F* All sockets in use *\u002F\n    }\n\n    \u002F* Send routing activation response *\u002F\n    uint8_t response[13];\n    DoIPHeader_t* header = (DoIPHeader_t*)response;\n    header->protocol_version = 0x02;\n    header->inverse_protocol_version = 0xFD;\n    header->payload_type = htons(DOIP_ROUTING_ACTIVATION_RESPONSE);\n    header->payload_length = htonl(5);\n\n    response[8] = (source_address >> 8) & 0xFF;\n    response[9] = source_address & 0xFF;\n    response[10] = 0x00;  \u002F* Logical address of gateway *\u002F\n    response[11] = 0x01;\n    response[12] = response_code;\n\n    send(tcp_socket, response, 13, 0);\n}\n\nvoid VGU_DoIP_RouteDiagnosticMessage(const uint8_t* doip_message, uint16_t length) {\n    \u002F* Extract source and target addresses *\u002F\n    uint16_t source_addr = (doip_message[8] \u003C\u003C 8) | doip_message[9];\n    uint16_t target_addr = (doip_message[10] \u003C\u003C 8) | doip_message[11];\n\n    \u002F* Extract UDS payload *\u002F\n    const uint8_t* uds_payload = &doip_message[12];\n    uint16_t uds_length = length - 12;\n\n    \u002F* Route to target ECU based on logical address *\u002F\n    NetworkID_t target_network;\n    uint32_t target_can_id;\n\n    switch (target_addr) {\n        case 0x0010:  \u002F* VCU *\u002F\n            target_network = NETWORK_CAN_POWERTRAIN;\n            target_can_id = 0x7E0;  \u002F* VCU diagnostic address *\u002F\n            break;\n        case 0x0020:  \u002F* BMS *\u002F\n            target_network = NETWORK_CAN_POWERTRAIN;\n            target_can_id = 0x7E1;\n            break;\n        case 0x0030:  \u002F* MCU *\u002F\n            target_network = NETWORK_CAN_POWERTRAIN;\n            target_can_id = 0x7E2;\n            break;\n        default:\n            \u002F* Unknown target *\u002F\n            return;\n    }\n\n    \u002F* Send diagnostic request over CAN *\u002F\n    VGU_Network_Transmit(target_network, target_can_id, uds_payload, uds_length);\n}\n```\n\n### 4. Gateway Wake-Up Management\n```c\n\u002F* vgu_wakeup_management.c - Network wake-up and power management *\u002F\n#include \"vgu_wakeup_management.h\"\n\ntypedef enum {\n    WAKEUP_SOURCE_CAN_POWERTRAIN = 0,\n    WAKEUP_SOURCE_CAN_CHASSIS,\n    WAKEUP_SOURCE_LIN_DOOR,\n    WAKEUP_SOURCE_ETHERNET,\n    WAKEUP_SOURCE_TIMER,\n    WAKEUP_SOURCE_IGNITION,\n    WAKEUP_SOURCE_COUNT\n} WakeupSource_t;\n\ntypedef struct {\n    bool wakeup_enabled[WAKEUP_SOURCE_COUNT];\n    WakeupSource_t last_wakeup_source;\n    uint32_t wakeup_timestamp_ms;\n} WakeupState_t;\n\nstatic WakeupState_t g_wakeup_state = {0};\n\nvoid VGU_WakeupManagement_Init(void) {\n    \u002F* Enable relevant wakeup sources *\u002F\n    g_wakeup_state.wakeup_enabled[WAKEUP_SOURCE_CAN_POWERTRAIN] = true;\n    g_wakeup_state.wakeup_enabled[WAKEUP_SOURCE_LIN_DOOR] = true;\n    g_wakeup_state.wakeup_enabled[WAKEUP_SOURCE_IGNITION] = true;\n\n    \u002F* Configure CAN transceivers for selective wake-up *\u002F\n    CanTrcv_SetOpMode(CAN_POWERTRAIN, CANTRCV_WUMODE_ENABLE);\n    CanTrcv_SetOpMode(CAN_CHASSIS, CANTRCV_WUMODE_ENABLE);\n}\n\nvoid VGU_WakeupManagement_OnWakeup(WakeupSource_t source) {\n    g_wakeup_state.last_wakeup_source = source;\n    g_wakeup_state.wakeup_timestamp_ms = GetSystemTime_ms();\n\n    \u002F* Notify EcuM of wakeup event *\u002F\n    EcuM_SetWakeupEvent((EcuM_WakeupSourceType)(1 \u003C\u003C source));\n\n    \u002F* Start network initialization sequence based on wakeup source *\u002F\n    switch (source) {\n        case WAKEUP_SOURCE_CAN_POWERTRAIN:\n            \u002F* High-priority startup: VCU, BMS, MCU needed *\u002F\n            VGU_Network_Start(NETWORK_CAN_POWERTRAIN);\n            VGU_Network_Start(NETWORK_CAN_CHASSIS);\n            break;\n\n        case WAKEUP_SOURCE_LIN_DOOR:\n            \u002F* Body network startup: BCM, door modules *\u002F\n            VGU_Network_Start(NETWORK_CAN_BODY);\n            VGU_Network_Start(NETWORK_LIN_DOOR);\n            break;\n\n        case WAKEUP_SOURCE_IGNITION:\n            \u002F* Full network startup *\u002F\n            for (NetworkID_t net = 0; net \u003C NETWORK_INVALID; net++) {\n                VGU_Network_Start(net);\n            }\n            break;\n\n        default:\n            break;\n    }\n}\n\nvoid VGU_WakeupManagement_EnterSleep(void) {\n    \u002F* Shutdown sequence: least critical networks first *\u002F\n    VGU_Network_Stop(NETWORK_CAN_INFOTAINMENT);\n    VGU_Network_Stop(NETWORK_CAN_BODY);\n\n    \u002F* Wait for pending transmissions *\u002F\n    while (VGU_Network_HasPendingTx(NETWORK_CAN_CHASSIS)) {\n        OsTask_Sleep(10);\n    }\n\n    VGU_Network_Stop(NETWORK_CAN_CHASSIS);\n\n    \u002F* Powertrain network last (safety-critical) *\u002F\n    VGU_Network_Stop(NETWORK_CAN_POWERTRAIN);\n\n    \u002F* Configure transceivers for wake-up *\u002F\n    CanTrcv_SetOpMode(CAN_POWERTRAIN, CANTRCV_WUMODE_ENABLE);\n\n    \u002F* Enter low-power mode *\u002F\n    Mcu_SetMode(MCU_MODE_SLEEP);\n}\n```\n\n## AUTOSAR COM Stack Configuration\n\n### Gateway PDU Router (ARXML)\n```xml\n\u003C!-- vgu_pdur_configuration.arxml -->\n\u003CAUTOSAR xmlns=\"http:\u002F\u002Fautosar.org\u002Fschema\u002Fr4.0\">\n  \u003CAR-PACKAGES>\n    \u003CAR-PACKAGE>\n      \u003CSHORT-NAME>PduR_RoutingTables\u003C\u002FSHORT-NAME>\n      \u003CELEMENTS>\n        \u003CPDU-R-ROUTING-TABLE>\n          \u003CSHORT-NAME>VGU_RoutingTable\u003C\u002FSHORT-NAME>\n          \u003CROUTING-PATHS>\n            \u003C!-- CAN Powertrain -> Ethernet Backbone -->\n            \u003CPDU-R-ROUTING-PATH>\n              \u003CSHORT-NAME>VCU_MotorCmd_CANtoETH\u003C\u002FSHORT-NAME>\n              \u003CPDU-R-SOURCE-PDU-REF DEST=\"I-PDU\">\n                \u002FCAN_Powertrain\u002FVCU_MotorCmd\n              \u003C\u002FPDU-R-SOURCE-PDU-REF>\n              \u003CPDU-R-DESTINATION-PDU-REF DEST=\"I-PDU\">\n                \u002FETH_Backbone\u002FVCU_MotorCmd_ETH\n              \u003C\u002FPDU-R-DESTINATION-PDU-REF>\n              \u003CPDU-R-DEFAULT-VALUE>0\u003C\u002FPDU-R-DEFAULT-VALUE>\n            \u003C\u002FPDU-R-ROUTING-PATH>\n\n            \u003C!-- Ethernet -> CAN Chassis (ADAS commands) -->\n            \u003CPDU-R-ROUTING-PATH>\n              \u003CSHORT-NAME>ADAS_SteeringCmd_ETHtoGAN\u003C\u002FSHORT-NAME>\n              \u003CPDU-R-SOURCE-PDU-REF DEST=\"I-PDU\">\n                \u002FETH_Backbone\u002FADAS_SteeringCmd\n              \u003C\u002FPDU-R-SOURCE-PDU-REF>\n              \u003CPDU-R-DESTINATION-PDU-REF DEST=\"I-PDU\">\n                \u002FCAN_Chassis\u002FADAS_SteeringCmd_CAN\n              \u003C\u002FPDU-R-DESTINATION-PDU-REF>\n              \u003CPDU-R-DEFAULT-VALUE>0\u003C\u002FPDU-R-DEFAULT-VALUE>\n            \u003C\u002FPDU-R-ROUTING-PATH>\n          \u003C\u002FROUTING-PATHS>\n        \u003C\u002FPDU-R-ROUTING-TABLE>\n      \u003C\u002FELEMENTS>\n    \u003C\u002FAR-PACKAGE>\n  \u003C\u002FAR-PACKAGES>\n\u003C\u002FAUTOSAR>\n```\n\n## VGU Network Configuration (DBC)\n```\nVERSION \"\"\n\nNS_ :\n\nBS_:\n\nBU_: VGU VCU BMS MCU BCM IVI\n\n\u002F* Gateway Status Message *\u002F\nBO_ 1024 VGU_Status: 8 VGU\n SG_ VGU_NetworkStatus_Powertrain : 0|2@1+ (0,0) [0|3] \"\"  VCU,BMS,MCU\n SG_ VGU_NetworkStatus_Chassis : 2|2@1+ (0,0) [0|3] \"\"  BCM\n SG_ VGU_NetworkStatus_Body : 4|2@1+ (0,0) [0|3] \"\"  BCM\n SG_ VGU_NetworkStatus_Infotainment : 6|2@1+ (0,0) [0|3] \"\"  IVI\n SG_ VGU_NetworkStatus_Ethernet : 8|2@1+ (0,0) [0|3] \"\"  VCU,IVI\n SG_ VGU_RoutingActive : 10|1@1+ (0,0) [0|1] \"\"  ALL\n SG_ VGU_FirewallActive : 11|1@1+ (0,0) [0|1] \"\"  ALL\n SG_ VGU_DiagnosticSessionActive : 12|1@1+ (0,0) [0|1] \"\"  ALL\n SG_ VGU_SecurityAnomalyCount : 16|16@1+ (0,0) [0|65535] \"\"  ALL\n SG_ VGU_RoutedMessageCount : 32|32@1+ (0,0) [0|4294967295] \"\"  ALL\n\nVAL_ 1024 VGU_NetworkStatus_Powertrain 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Chassis 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Body 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Infotainment 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\nVAL_ 1024 VGU_NetworkStatus_Ethernet 0 \"Offline\" 1 \"Initializing\" 2 \"Active\" 3 \"Error\";\n```\n\n## Testing Requirements\n\n### Gateway HIL Test\n```python\n# vgu_hil_test.py - Hardware-in-the-Loop testing for VGU\nimport can\nimport socket\nimport pytest\n\nclass TestVGURouting:\n    def test_can_to_ethernet_routing(self, vgu_hil):\n        \"\"\"Verify CAN message is routed to Ethernet\"\"\"\n        # Send VCU_MotorCmd on CAN Powertrain\n        can_msg = can.Message(arbitration_id=0x100,\n                               data=[0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xAB],\n                               is_extended_id=False)\n        vgu_hil.can_powertrain.send(can_msg)\n\n        # Verify message appears on Ethernet backbone (SOME\u002FIP)\n        eth_packet = vgu_hil.eth_backbone.recv(timeout=0.1)\n        assert eth_packet is not None\n        assert eth_packet[0:2] == b'\\x12\\x34'  # Service ID\n\n    def test_security_firewall_blocks_invalid_dlc(self, vgu_hil):\n        \"\"\"Verify firewall blocks message with wrong DLC\"\"\"\n        # Send message with incorrect DLC\n        invalid_msg = can.Message(arbitration_id=0x100,\n                                   data=[0x64, 0x00],  # DLC=2, expected=8\n                                   is_extended_id=False)\n        vgu_hil.can_powertrain.send(invalid_msg)\n\n        # Verify VGU logs security event\n        security_log = vgu_hil.read_can_message(0x400, timeout=0.1)\n        assert security_log.data[0] == 0x01  # DLC_MISMATCH event\n\n        # Verify message NOT routed to Ethernet\n        eth_packet = vgu_hil.eth_backbone.recv(timeout=0.1)\n        assert eth_packet is None\n\n    def test_doip_routing_activation(self, vgu_hil):\n        \"\"\"Verify DoIP routing activation over TCP\"\"\"\n        # Connect to DoIP port\n        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        sock.connect((\"192.168.1.100\", 13400))\n\n        # Send routing activation request\n        activation_request = bytes([\n            0x02, 0xFD,  # Protocol version\n            0x00, 0x05,  # Payload type: Routing Activation Request\n            0x00, 0x00, 0x00, 0x07,  # Payload length\n            0x0E, 0x80,  # Source address (tester)\n            0x00,        # Activation type\n            0x00, 0x00, 0x00, 0x00  # Reserved\n        ])\n        sock.send(activation_request)\n\n        # Receive routing activation response\n        response = sock.recv(13)\n        assert len(response) == 13\n        assert response[2:4] == b'\\x00\\x06'  # Routing Activation Response\n        assert response[12] == 0x10  # Response code: Successfully activated\n\n        sock.close()\n```\n\n## References\n- ISO 13400: Diagnostic communication over Internet Protocol (DoIP)\n- AUTOSAR Classic Platform R20-11: PDU Router Specification\n- SAE J1939: Serial Control and Communications Heavy Duty Vehicle Network\n- IEEE 802.1Q: Virtual LANs and Network Segmentation\n- ISO 14229-1: Unified Diagnostic Services (UDS)\n\n## Common Issues\n- Message routing latency causing control delays\n- Firewall false positives blocking legitimate messages\n- DoIP connection timeout during long diagnostic sessions\n- Wake-up signal not propagating across networks\n- Ethernet packet loss during high CAN traffic bursts\n",{"name":5,"tags":24,"source":26,"license":15,"description":27,"imported_at":28,"source_path":29,"source_repository":30},[25,5],"automotive","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills","Automotive Ecu Systems expertise. Covers 8 topics: Bcm Body Control, Bms Battery Management, Domain Controller Integration, Ivi Infotainment Systems, Pdu Power Distribution.\n","2026-09-20","skills\u002Fautomotive-ecu-systems\u002FSKILL.md","pangzhenying2025\u002Fhermes-automotive-skills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fautomotive\u002Fautomotive-ecu-systems","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":38,"prompt":48,"zipAvailable":49},[39,42,45],{"tool":40,"command":41},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill automotive-ecu-systems",{"tool":43,"command":44},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill automotive-ecu-systems",{"tool":46,"command":47},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill automotive-ecu-systems","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fautomotive\u002Fautomotive-ecu-systems\u002FSKILL.md",true,[],[52,60,67,74,81,88],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":59},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":59},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":59},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":59},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":59},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":59},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]