[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735W9TH33HSSJRK0HKN05EV":3,"skill-same:01M735W9TH33HSSJRK0HKN05EV":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":32,"install":33,"resources":46},"01M735W9TH33HSSJRK0HKN05EV","automotive-safety",null,"Automotive Safety expertise. Covers 6 topics: Fmea Fta Analysis, Hazard Analysis Risk Assessment, Iso 26262 Overview, Safety Mechanisms Patterns, Safety Verification Validation.","pangzhenying2025\u002Fhermes-automotive-skills","pangzhenying2025","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F213717646?v=4","01M735F4ESJ0SM29HHRG810PS8","01M735F4FX3N7R55KGY8AYBRZ0",11,"MIT","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fautomotive-safety\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: automotive-safety\ndescription: >\n  Automotive Safety expertise. Covers 6 topics: Fmea Fta Analysis, Hazard Analysis Risk Assessment, Iso 26262 Overview, Safety Mechanisms Patterns, Safety Verification Validation.\ntags: [automotive, automotive-safety]\n---\n\n# Automotive Safety\n\n## Fmea Fta Analysis\n\n# FMEA\u002FFTA\u002FFMEDA Analysis for ISO 26262\n\nComprehensive guidance on Failure Mode and Effects Analysis (FMEA), Fault Tree Analysis (FTA), and Failure Modes, Effects, and Diagnostic Analysis (FMEDA) for automotive functional safety, including templates, calculation methods, and production-ready examples.\n\n## Overview\n\n### Analysis Types\n\n**FMEA (Failure Mode and Effects Analysis)**\n- Bottom-up analysis: component failure → system effect\n- Identifies single-point and latent faults\n- Calculates diagnostic coverage\n- Required for all ASIL levels\n\n**FTA (Fault Tree Analysis)**\n- Top-down analysis: hazardous event → contributing faults\n- Quantifies failure probability\n- Validates ASIL decomposition\n- Mandatory for ASIL C\u002FD\n\n**FMEDA (Failure Modes, Effects, and Diagnostic Analysis)**\n- Extension of FMEA with quantitative metrics\n- Calculates PMHF (Probabilistic Metric for random Hardware Failures)\n- Determines SPFM and LFM\n- Required for ASIL B\u002FC\u002FD hardware\n\n## FMEA Methodology\n\n### FMEA Process Flow\n\n```\n┌──────────────────────────┐\n│ 1. Define System         │\n│    Boundaries            │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 2. Identify Components   │\n│    and Functions         │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 3. Identify Failure      │\n│    Modes                 │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 4. Analyze Effects       │\n│    (Local\u002FSystem\u002FEnd)    │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 5. Classify Faults       │\n│    (SPF\u002FRF\u002FLF)           │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 6. Define Safety         │\n│    Mechanisms            │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 7. Calculate Diagnostic  │\n│    Coverage (DC)         │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 8. Verify Metrics        │\n│    (SPFM\u002FLFM\u002FPMHF)       │\n└──────────────────────────┘\n```\n\n### Fault Classifications\n\n**Single-Point Fault (SPF)**\n- Fault that directly leads to violation of safety goal\n- No safety mechanism provides detection\n- Must be minimized (SPFM > 99% for ASIL-D)\n\n**Residual Fault (RF)**\n- Fault detected by safety mechanism but coverage \u003C 100%\n- Contributes to PMHF calculation\n- Example: CRC detects 99.998% of errors → 0.002% residual\n\n**Latent Fault (LF)**\n- Multi-point fault: not detected immediately\n- Only becomes hazardous in combination with another fault\n- Must be detected before second fault occurs (LFM > 90% for ASIL-D)\n\n**Safe Fault (SF)**\n- Fault detected with high coverage (> 99%)\n- Transition to safe state within FTTI\n- Does not contribute to PMHF\n\n### FMEA Worksheet Template\n\n```yaml\nfmea_id: \"FMEA-ESC-HW-001\"\nsystem: \"Electronic Stability Control\"\nsubsystem: \"ESC ECU Hardware\"\nasil: \"ASIL-D\"\nanalyst: \"HW Safety Engineer\"\ndate: \"2024-03-19\"\nversion: \"1.2\"\n\ncomponents:\n  - component_id: \"C001\"\n    component_name: \"Microcontroller (MCU)\"\n    part_number: \"TMS570LC4357\"\n    function: \"Main processing unit for ESC algorithms\"\n\n    failure_modes:\n      - fm_id: \"FM-C001-001\"\n        failure_mode: \"MCU Core 0 stuck-at-high output\"\n        failure_rate_fit: 50  # Failures in 10^9 hours\n        failure_cause: \"Transistor latch-up, ESD damage\"\n\n        effects:\n          local_effect: \"Core 0 outputs invalid high logic\"\n          subsystem_effect: \"Incorrect PWM output to brake modulator\"\n          system_effect: \"Unintended brake actuation on one wheel\"\n          end_effect: \"Vehicle instability, potential loss of control\"\n\n        severity: \"S3\"  # Life-threatening\n        detection_method: \"Dual-core lockstep comparison\"\n        detection_coverage_pct: 99.9\n\n        fault_classification:\n          before_sm: \"SPF\"  # Single-point fault without safety mechanism\n          after_sm: \"SF\"    # Safe fault with lockstep detection\n          diagnostic_coverage: 99.9  # DC = 99.9%\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-001\"\n          description: \"Dual-core lockstep with cycle-by-cycle comparison\"\n          detection_time_ms: 0.1  # Detection within 100 μs\n          reaction: \"Immediate transition to safe state\"\n          ftti_ms: 150\n\n        residual_failure_rate_fit: 0.05  # 50 * (1 - 0.999) = 0.05\n        lambda_spf_fit: 0.05\n        lambda_rf_fit: 0.05\n\n      - fm_id: \"FM-C001-002\"\n        failure_mode: \"MCU RAM single-bit flip (SEU)\"\n        failure_rate_fit: 100\n        failure_cause: \"Cosmic ray, alpha particle\"\n\n        effects:\n          local_effect: \"Corrupted data in RAM\"\n          subsystem_effect: \"Incorrect calculation results\"\n          system_effect: \"Wrong ESC intervention decision\"\n          end_effect: \"Delayed or incorrect stability control\"\n\n        severity: \"S2\"\n        detection_method: \"ECC (Error Correcting Code) on RAM\"\n        detection_coverage_pct: 99.99\n\n        fault_classification:\n          before_sm: \"SPF\"\n          after_sm: \"SF\"\n          diagnostic_coverage: 99.99\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-002\"\n          description: \"ECC on safety-critical RAM sections\"\n          detection_time_ms: 0.01\n          reaction: \"Correct single-bit errors, flag multi-bit errors\"\n\n        residual_failure_rate_fit: 0.01\n        lambda_spf_fit: 0.01\n        lambda_rf_fit: 0.01\n\n      - fm_id: \"FM-C001-003\"\n        failure_mode: \"MCU clock frequency drift\"\n        failure_rate_fit: 20\n        failure_cause: \"Oscillator aging, temperature stress\"\n\n        effects:\n          local_effect: \"Incorrect timing of operations\"\n          subsystem_effect: \"ESC algorithm timing violated\"\n          system_effect: \"Delayed ESC response (> 100 ms)\"\n          end_effect: \"Reduced effectiveness of stability control\"\n\n        severity: \"S2\"\n        detection_method: \"External watchdog with window timing\"\n        detection_coverage_pct: 95.0\n\n        fault_classification:\n          before_sm: \"SPF\"\n          after_sm: \"RF\"  # Residual fault (95% coverage)\n          diagnostic_coverage: 95.0\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-003\"\n          description: \"Window watchdog monitors timing\"\n          detection_time_ms: 50\n          reaction: \"Safe state transition if timing violated\"\n\n        residual_failure_rate_fit: 1.0  # 20 * (1 - 0.95) = 1.0\n        lambda_spf_fit: 0\n        lambda_rf_fit: 1.0\n\n  - component_id: \"C002\"\n    component_name: \"Wheel Speed Sensor (Front Left)\"\n    part_number: \"ABS-SENSOR-FL\"\n    function: \"Measure front-left wheel rotational speed\"\n\n    failure_modes:\n      - fm_id: \"FM-C002-001\"\n        failure_mode: \"Sensor output stuck-at-zero\"\n        failure_rate_fit: 150\n        failure_cause: \"Wiring short-to-ground, sensor damage\"\n\n        effects:\n          local_effect: \"Constant zero speed output\"\n          subsystem_effect: \"ESC detects wheel as stationary\"\n          system_effect: \"Incorrect vehicle dynamics calculation\"\n          end_effect: \"ESC may fail to intervene when needed\"\n\n        severity: \"S3\"\n        detection_method: \"Plausibility check vs other wheel speeds\"\n        detection_coverage_pct: 90.0\n\n        fault_classification:\n          before_sm: \"LF\"  # Latent fault (multi-point failure)\n          after_sm: \"LF\"   # Still latent but detected\n          diagnostic_coverage: 90.0\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-004\"\n          description: \"Cross-check wheel speeds for consistency\"\n          detection_time_ms: 200\n          reaction: \"Flag sensor as faulty, use 3-wheel calculation\"\n\n        residual_failure_rate_fit: 15.0  # 150 * (1 - 0.90) = 15.0\n        lambda_lf_fit: 135.0  # 150 * 0.90 (detected latent)\n        lambda_rf_fit: 15.0\n\nmetrics:\n  total_failure_rate_fit: 320  # Sum of all component failure rates\n\n  spf_metric:\n    lambda_spf_total: 0.06  # Sum of all SPF contributions after SM\n    lambda_total: 320\n    spfm_percent: 99.98  # (1 - 0.06\u002F320) * 100 = 99.98%\n    target_asil_d: 99.0\n    status: \"PASS\"\n\n  lf_metric:\n    lambda_lf_detected: 135.0\n    lambda_lf_total: 150.0\n    lfm_percent: 90.0  # (135\u002F150) * 100 = 90.0%\n    target_asil_d: 90.0\n    status: \"PASS\"\n\n  pmhf:\n    lambda_spf: 0.06\n    lambda_rf: 16.06\n    pmhf_fit: 16.12  # SPF + RF = 0.06 + 16.06\n    target_asil_d_fit: 10.0\n    status: \"FAIL - Requires design improvement\"\n\nconclusions:\n  - SPFM meets ASIL-D target (99.98% > 99%)\n  - LFM meets ASIL-D target (90.0% >= 90%)\n  - PMHF exceeds ASIL-D target (16.12 > 10 FIT)\n  - Recommendation: Improve sensor redundancy or diagnostic coverage\n\nactions:\n  - action_id: \"ACT-001\"\n    description: \"Add redundant wheel speed sensor (1oo2 configuration)\"\n    responsible: \"HW Design Team\"\n    due_date: \"2024-04-30\"\n    expected_pmhf_reduction: \"50%\"\n```\n\n## FTA Methodology\n\n### Fault Tree Symbols\n\n```\n┌─────────────────────────────────────────┐\n│ Event Symbols                           │\n├─────────────────────────────────────────┤\n│  ◯  Basic Event (failure)               │\n│  □  Intermediate Event                  │\n│  ◇  Undeveloped Event                   │\n│  ⬡  External Event                      │\n└─────────────────────────────────────────┘\n\n┌─────────────────────────────────────────┐\n│ Gate Symbols                            │\n├─────────────────────────────────────────┤\n│  ∧  AND Gate (all inputs required)      │\n│  ∨  OR Gate (any input sufficient)      │\n│  ⊕  XOR Gate (exclusive-or)             │\n│  ≥K  K-out-of-N Gate                    │\n└─────────────────────────────────────────┘\n```\n\n### FTA Example - Unintended ESC Activation\n\n```\nTop Event: Unintended ESC Activation (ASIL-D)\n│\n├─ OR ────────────────────────────────────┐\n│                                          │\n▼                                          ▼\n[Spurious Brake Command]              [Sensor False Positive]\n│                                          │\n├─ OR ─────────────────┐                  ├─ OR ──────────────┐\n│                      │                  │                   │\n▼                      ▼                  ▼                   ▼\n[MCU Fault]     [CAN Corruption]    [Yaw Sensor]      [Lateral Accel]\n│                      │              Stuck-High       Sensor Stuck\n├─ AND ───────┐        │\n│             │        │\n▼             ▼        ▼\n[Core Fault] [Lockstep] [EMI]\n◯ 50 FIT      Fails     ◯ 10 FIT\n              ◯ 0.5 FIT\n```\n\n### Quantitative FTA\n\n**Calculate Top Event Probability:**\n\n```python\n# FTA calculations\nimport math\n\n# Basic event failure rates (FIT = failures in 10^9 hours)\nfailure_rates = {\n    'mcu_core_fault': 50,\n    'lockstep_failure': 0.5,\n    'can_emi': 10,\n    'yaw_sensor_stuck': 100,\n    'lateral_accel_stuck': 80\n}\n\n# Mission time (hours)\nmission_time = 10000  # 10,000 hours (typical vehicle lifetime)\n\n# Convert FIT to probability\ndef fit_to_probability(fit, hours):\n    \"\"\"Convert FIT to probability over given hours\"\"\"\n    lambda_per_hour = fit \u002F 1e9\n    return 1 - math.exp(-lambda_per_hour * hours)\n\n# Calculate probabilities\nprob = {}\nfor event, fit in failure_rates.items():\n    prob[event] = fit_to_probability(fit, mission_time)\n    print(f\"{event}: {prob[event]:.6e}\")\n\n# AND gate: P(A AND B) = P(A) * P(B)\nprob_mcu_undetected = prob['mcu_core_fault'] * prob['lockstep_failure']\nprint(f\"\\nMCU undetected fault: {prob_mcu_undetected:.6e}\")\n\n# OR gate: P(A OR B) = P(A) + P(B) - P(A)*P(B)\ndef or_gate(p1, p2):\n    return p1 + p2 - (p1 * p2)\n\n# Spurious brake command path\nprob_spurious_brake = or_gate(prob_mcu_undetected, prob['can_emi'])\nprint(f\"Spurious brake command: {prob_spurious_brake:.6e}\")\n\n# Sensor false positive path\nprob_sensor_false = or_gate(prob['yaw_sensor_stuck'], prob['lateral_accel_stuck'])\nprint(f\"Sensor false positive: {prob_sensor_false:.6e}\")\n\n# Top event\nprob_top_event = or_gate(prob_spurious_brake, prob_sensor_false)\nprint(f\"\\nTop Event (Unintended ESC): {prob_top_event:.6e}\")\n\n# ASIL-D target: \u003C 10 FIT = 1e-4 probability over 10,000 hours\nasil_d_target = fit_to_probability(10, mission_time)\nprint(f\"ASIL-D target (\u003C 10 FIT): {asil_d_target:.6e}\")\n\nif prob_top_event \u003C asil_d_target:\n    print(\"✓ FTA meets ASIL-D requirement\")\nelse:\n    print(\"✗ FTA fails ASIL-D requirement\")\n    print(f\"Risk reduction factor needed: {prob_top_event \u002F asil_d_target:.1f}x\")\n```\n\n### Cut Set Analysis\n\n**Minimal Cut Sets:**\n\nCut sets are combinations of basic events that cause the top event.\n\n```python\n# Minimal cut sets for FTA\ncut_sets = [\n    ['mcu_core_fault', 'lockstep_failure'],  # AND gate\n    ['can_emi'],                              # Single point\n    ['yaw_sensor_stuck'],                     # Single point\n    ['lateral_accel_stuck']                   # Single point\n]\n\n# Calculate cut set probabilities\nprint(\"Minimal Cut Sets:\")\nfor i, cut_set in enumerate(cut_sets, 1):\n    if len(cut_set) == 1:\n        # Single-point fault\n        prob_cut = prob[cut_set[0]]\n        print(f\"  Cut Set {i} (SPF): {cut_set} = {prob_cut:.6e}\")\n    else:\n        # Multi-point fault (AND)\n        prob_cut = 1.0\n        for event in cut_set:\n            prob_cut *= prob[event]\n        print(f\"  Cut Set {i} (AND): {cut_set} = {prob_cut:.6e}\")\n\n# Importance analysis - which events contribute most?\nprint(\"\\nImportance Analysis:\")\nevent_contributions = {}\nfor event in failure_rates:\n    # Calculate top event probability with this event probability = 1\n    test_prob = prob.copy()\n    test_prob[event] = 1.0\n\n    # Recalculate (simplified)\n    if event in ['mcu_core_fault', 'lockstep_failure']:\n        test_spurious = or_gate(test_prob['mcu_core_fault'] * test_prob['lockstep_failure'],\n                                test_prob['can_emi'])\n    else:\n        test_spurious = prob_spurious_brake\n\n    if event in ['yaw_sensor_stuck', 'lateral_accel_stuck']:\n        test_sensor = or_gate(test_prob['yaw_sensor_stuck'], test_prob['lateral_accel_stuck'])\n    else:\n        test_sensor = prob_sensor_false\n\n    test_top = or_gate(test_spurious, test_sensor)\n\n    importance = test_top - prob_top_event\n    event_contributions[event] = importance\n\n# Sort by importance\nsorted_events = sorted(event_contributions.items(), key=lambda x: x[1], reverse=True)\nfor event, importance in sorted_events:\n    print(f\"  {event}: {importance:.6e}\")\n\nprint(\"\\nRecommendation: Focus safety mechanisms on:\", sorted_events[0][0])\n```\n\n## FMEDA Calculations\n\n### Hardware Metrics Formulas\n\n**1. Single-Point Fault Metric (SPFM)**\n\n```\nSPFM = (1 - (ΣλSPF \u002F Σλ)) × 100%\n\nWhere:\n  λSPF = failure rate of single-point faults (FIT)\n  λ = total failure rate (FIT)\n\nASIL Targets:\n  ASIL B: SPFM > 90%\n  ASIL C: SPFM > 97%\n  ASIL D: SPFM > 99%\n```\n\n**2. Latent Fault Metric (LFM)**\n\n```\nLFM = (1 - (ΣλLF,undetected \u002F ΣλLF)) × 100%\n\nWhere:\n  λLF,undetected = latent faults not detected (FIT)\n  λLF = total latent fault rate (FIT)\n\nASIL Targets:\n  ASIL B: LFM > 60%\n  ASIL C: LFM > 80%\n  ASIL D: LFM > 90%\n```\n\n**3. Probabilistic Metric for random Hardware Failures (PMHF)**\n\n```\nPMHF = ΣλSPF + ΣλRF\n\nWhere:\n  λSPF = single-point fault rate (FIT)\n  λRF = residual fault rate (FIT)\n\nASIL Targets (per safety goal):\n  ASIL B: PMHF \u003C 100 FIT\n  ASIL C: PMHF \u003C 100 FIT\n  ASIL D: PMHF \u003C 10 FIT\n\nNote: 1 FIT = 1 failure in 10^9 hours\n      10 FIT ≈ 1 failure per 11,400 years of operation\n```\n\n### Diagnostic Coverage Classes\n\n| DC Class | Coverage Range | Examples |\n|----------|---------------|----------|\n| DC 0 | None (0%) | No diagnostic |\n| DC 1 | Low (60-90%) | Plausibility checks |\n| DC 2 | Medium (90-99%) | Watchdog, CRC |\n| DC 3 | High (99-100%) | Dual-core lockstep, ECC |\n\n### FMEDA Spreadsheet\n\n```\nComponent: ESC ECU Microcontroller\nPart Number: TMS570LC4357\nASIL: D\n\n┌─────┬──────────────────┬──────┬──────┬──────┬────┬────┬────┬────┐\n│ ID  │ Failure Mode     │  λ   │ DC%  │Class │SPF │ RF │ LF │ SF │\n├─────┼──────────────────┼──────┼──────┼──────┼────┼────┼────┼────┤\n│ FM1 │ Core stuck-at    │  50  │ 99.9 │ DC3  │ 0  │0.05│ 0  │49.95│\n│ FM2 │ RAM bit-flip     │ 100  │ 99.99│ DC3  │ 0  │0.01│ 0  │99.99│\n│ FM3 │ Clock drift      │  20  │ 95.0 │ DC2  │ 0  │ 1.0│ 0  │ 19.0│\n│ FM4 │ Flash ECC fail   │  10  │ 100  │ DC3  │ 0  │ 0  │ 0  │ 10.0│\n│ FM5 │ Watchdog fail    │   5  │  0   │ DC0  │ 5  │ 0  │ 0  │  0  │\n│ FM6 │ ADC stuck        │  30  │ 85.0 │ DC1  │ 0  │ 4.5│ 0  │25.5 │\n│ FM7 │ Power supply OV  │  15  │ 99.0 │ DC3  │ 0  │0.15│ 0  │14.85│\n│ FM8 │ Temp sensor drift│  25  │ 90.0 │ DC2  │ 0  │ 2.5│ 0  │22.5 │\n├─────┼──────────────────┼──────┼──────┼──────┼────┼────┼────┼────┤\n│ SUM │                  │ 255  │      │      │ 5  │8.21│ 0  │241.79│\n└─────┴──────────────────┴──────┴──────┴──────┴────┴────┴────┴────┘\n\nCalculations:\n  SPFM = (1 - 5\u002F255) × 100% = 98.04%  ← FAIL (target: >99%)\n  LFM = N\u002FA (no latent faults)\n  PMHF = 5 + 8.21 = 13.21 FIT  ← FAIL (target: \u003C10 FIT)\n\nRequired Actions:\n  1. Eliminate watchdog SPF (add redundant watchdog)\n  2. Improve ADC diagnostic coverage (add cross-checks)\n  3. Target: SPFM > 99%, PMHF \u003C 10 FIT\n```\n\n## FMEA\u002FFTA Integration\n\n### Bidirectional Validation\n\n**FMEA → FTA Validation:**\n\n1. Each SPF in FMEA should appear as single basic event in FTA\n2. Each latent fault should appear in AND gate (multi-point)\n3. Safety mechanisms should reduce FTA cut set probabilities\n\n**FTA → FMEA Validation:**\n\n1. Each FTA basic event should have corresponding FMEA failure mode\n2. FTA cut sets reveal dependent failures for DFA\n3. FTA probability calculation validates PMHF\n\n### Example Cross-Check\n\n```python\n# Validate FMEA and FTA consistency\nfmea_failure_modes = {\n    'mcu_core_fault': {'lambda': 50, 'dc': 99.9, 'spf': 0.05},\n    'ram_bit_flip': {'lambda': 100, 'dc': 99.99, 'spf': 0.01},\n    'sensor_stuck': {'lambda': 150, 'dc': 90.0, 'spf': 0}\n}\n\nfta_basic_events = {\n    'mcu_core_fault': 50,\n    'ram_bit_flip': 100,\n    'sensor_stuck': 150\n}\n\n# Check consistency\nprint(\"FMEA\u002FFTA Cross-Validation:\")\nfor event in fmea_failure_modes:\n    if event in fta_basic_events:\n        fmea_lambda = fmea_failure_modes[event]['lambda']\n        fta_lambda = fta_basic_events[event]\n\n        if fmea_lambda == fta_lambda:\n            print(f\"✓ {event}: Consistent ({fmea_lambda} FIT)\")\n        else:\n            print(f\"✗ {event}: Mismatch (FMEA: {fmea_lambda}, FTA: {fta_lambda})\")\n    else:\n        print(f\"⚠ {event}: Missing in FTA\")\n\nfor event in fta_basic_events:\n    if event not in fmea_failure_modes:\n        print(f\"⚠ {event}: Missing in FMEA\")\n```\n\n## Production-Ready Tools\n\n### FMEA Database Schema (SQL)\n\n```sql\nCREATE TABLE Components (\n    component_id VARCHAR(50) PRIMARY KEY,\n    component_name VARCHAR(200),\n    part_number VARCHAR(100),\n    function TEXT,\n    asil VARCHAR(10)\n);\n\nCREATE TABLE FailureModes (\n    fm_id VARCHAR(50) PRIMARY KEY,\n    component_id VARCHAR(50) REFERENCES Components(component_id),\n    failure_mode TEXT,\n    failure_rate_fit DECIMAL(10,2),\n    failure_cause TEXT,\n    local_effect TEXT,\n    system_effect TEXT,\n    end_effect TEXT,\n    severity VARCHAR(2)\n);\n\nCREATE TABLE SafetyMechanisms (\n    sm_id VARCHAR(50) PRIMARY KEY,\n    fm_id VARCHAR(50) REFERENCES FailureModes(fm_id),\n    description TEXT,\n    detection_coverage_pct DECIMAL(5,2),\n    detection_time_ms DECIMAL(10,2),\n    reaction TEXT,\n    ftti_ms DECIMAL(10,2)\n);\n\nCREATE TABLE FaultClassification (\n    fc_id SERIAL PRIMARY KEY,\n    fm_id VARCHAR(50) REFERENCES FailureModes(fm_id),\n    before_sm VARCHAR(10),  -- SPF, RF, LF, SF\n    after_sm VARCHAR(10),\n    diagnostic_coverage DECIMAL(5,2),\n    lambda_spf_fit DECIMAL(10,2),\n    lambda_rf_fit DECIMAL(10,2),\n    lambda_lf_fit DECIMAL(10,2),\n    lambda_sf_fit DECIMAL(10,2)\n);\n\n-- Query: Calculate SPFM for a system\nSELECT\n    SUM(fc.lambda_spf_fit) AS total_spf,\n    SUM(fm.failure_rate_fit) AS total_lambda,\n    (1 - SUM(fc.lambda_spf_fit) \u002F SUM(fm.failure_rate_fit)) * 100 AS spfm_percent\nFROM FailureModes fm\nJOIN FaultClassification fc ON fm.fm_id = fc.fm_id\nWHERE fm.component_id IN (SELECT component_id FROM Components WHERE asil = 'ASIL-D');\n```\n\n### Python FMEDA Calculator\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nISO 26262 FMEDA Calculator\nCalculates SPFM, LFM, and PMHF metrics\n\"\"\"\n\nclass FMEDACalculator:\n    def __init__(self, asil_level):\n        self.asil_level = asil_level\n        self.failure_modes = []\n        self.targets = self._get_targets(asil_level)\n\n    def _get_targets(self, asil):\n        targets = {\n            'ASIL-A': {'spfm': 0, 'lfm': 0, 'pmhf': 1000},\n            'ASIL-B': {'spfm': 90, 'lfm': 60, 'pmhf': 100},\n            'ASIL-C': {'spfm': 97, 'lfm': 80, 'pmhf': 100},\n            'ASIL-D': {'spfm': 99, 'lfm': 90, 'pmhf': 10}\n        }\n        return targets.get(asil, targets['ASIL-D'])\n\n    def add_failure_mode(self, name, lambda_fit, dc_percent):\n        \"\"\"\n        Add a failure mode with diagnostic coverage\n        \"\"\"\n        fm = {\n            'name': name,\n            'lambda': lambda_fit,\n            'dc': dc_percent \u002F 100.0,\n            'lambda_detected': lambda_fit * (dc_percent \u002F 100.0),\n            'lambda_residual': lambda_fit * (1 - dc_percent \u002F 100.0)\n        }\n        self.failure_modes.append(fm)\n\n    def calculate_metrics(self):\n        \"\"\"\n        Calculate SPFM, LFM, PMHF\n        \"\"\"\n        lambda_total = sum(fm['lambda'] for fm in self.failure_modes)\n        lambda_spf = sum(fm['lambda_residual'] for fm in self.failure_modes if fm['dc'] == 0)\n        lambda_rf = sum(fm['lambda_residual'] for fm in self.failure_modes if 0 \u003C fm['dc'] \u003C 1)\n        lambda_lf_detected = sum(fm['lambda_detected'] for fm in self.failure_modes)\n        lambda_lf_total = lambda_total  # Simplified\n\n        spfm = (1 - lambda_spf \u002F lambda_total) * 100 if lambda_total > 0 else 0\n        lfm = (lambda_lf_detected \u002F lambda_lf_total) * 100 if lambda_lf_total > 0 else 0\n        pmhf = lambda_spf + lambda_rf\n\n        return {\n            'spfm': spfm,\n            'lfm': lfm,\n            'pmhf': pmhf,\n            'lambda_total': lambda_total,\n            'lambda_spf': lambda_spf,\n            'lambda_rf': lambda_rf\n        }\n\n    def check_compliance(self):\n        \"\"\"\n        Check if metrics meet ASIL targets\n        \"\"\"\n        metrics = self.calculate_metrics()\n\n        compliance = {\n            'spfm': metrics['spfm'] >= self.targets['spfm'],\n            'lfm': metrics['lfm'] >= self.targets['lfm'],\n            'pmhf': metrics['pmhf'] \u003C= self.targets['pmhf']\n        }\n\n        return metrics, compliance\n\n    def generate_report(self):\n        \"\"\"\n        Generate compliance report\n        \"\"\"\n        metrics, compliance = self.check_compliance()\n\n        print(f\"\\n{'='*60}\")\n        print(f\"FMEDA Report - {self.asil_level}\")\n        print(f\"{'='*60}\\n\")\n\n        print(f\"{'Metric':\u003C20} {'Value':\u003C15} {'Target':\u003C15} {'Status':\u003C10}\")\n        print(f\"{'-'*60}\")\n\n        print(f\"{'SPFM':\u003C20} {metrics['spfm']:>8.2f}% \"\n              f\"{self.targets['spfm']:>8}% \"\n              f\"{'PASS' if compliance['spfm'] else 'FAIL':\u003C10}\")\n\n        print(f\"{'LFM':\u003C20} {metrics['lfm']:>8.2f}% \"\n              f\"{self.targets['lfm']:>8}% \"\n              f\"{'PASS' if compliance['lfm'] else 'FAIL':\u003C10}\")\n\n        print(f\"{'PMHF':\u003C20} {metrics['pmhf']:>8.2f} FIT \"\n              f\"{'\u003C':>2}{self.targets['pmhf']:>5} FIT \"\n              f\"{'PASS' if compliance['pmhf'] else 'FAIL':\u003C10}\")\n\n        print(f\"\\n{'Detail':\u003C20} {'Value':\u003C15}\")\n        print(f\"{'-'*35}\")\n        print(f\"{'Total λ':\u003C20} {metrics['lambda_total']:>8.2f} FIT\")\n        print(f\"{'λ SPF':\u003C20} {metrics['lambda_spf']:>8.2f} FIT\")\n        print(f\"{'λ RF':\u003C20} {metrics['lambda_rf']:>8.2f} FIT\")\n\n        overall = all(compliance.values())\n        print(f\"\\n{'Overall Compliance:':\u003C20} {'PASS' if overall else 'FAIL'}\")\n\n        return overall\n\n\n# Example usage\nif __name__ == \"__main__\":\n    calc = FMEDACalculator('ASIL-D')\n\n    # Add failure modes\n    calc.add_failure_mode('MCU Core Fault', lambda_fit=50, dc_percent=99.9)\n    calc.add_failure_mode('RAM Bit Flip', lambda_fit=100, dc_percent=99.99)\n    calc.add_failure_mode('Clock Drift', lambda_fit=20, dc_percent=95.0)\n    calc.add_failure_mode('Watchdog Fail', lambda_fit=5, dc_percent=0.0)  # SPF!\n    calc.add_failure_mode('ADC Stuck', lambda_fit=30, dc_percent=85.0)\n\n    # Generate report\n    calc.generate_report()\n```\n\n## Production Checklist\n\n- [ ] FMEA completed for all hardware\u002Fsoftware components\n- [ ] Failure modes identified at appropriate level (component\u002Ffunction)\n- [ ] Effects analyzed at local\u002Fsystem\u002Fend level\n- [ ] Safety mechanisms defined for all SPF\u002FLF\n- [ ] Diagnostic coverage calculated and validated\n- [ ] SPFM\u002FLFM\u002FPMHF metrics calculated\n- [ ] FTA performed for all ASIL C\u002FD safety goals\n- [ ] Cut sets identified and analyzed\n- [ ] FMEA and FTA cross-validated\n- [ ] Independent review completed\n- [ ] Metrics meet ASIL targets\n\n## References\n\n- ISO 26262-5:2018 Annex D - FMEDA Method\n- ISO 26262-9:2018 - ASIL-Oriented Analyses\n- IEC 61025 - Fault Tree Analysis\n- SAE J1739 - Potential Failure Mode and Effects Analysis (FMEA)\n- AIAG\u002FVDA FMEA Handbook\n\n## Related Skills\n\n- ISO 26262 Overview\n- Safety Mechanisms and Patterns\n- Hardware Safety Requirements\n- Software Safety Requirements\n- Dependent Failure Analysis (DFA)\n\n---\n\n## Hazard Analysis Risk Assessment\n\n# Hazard Analysis and Risk Assessment (HARA)\n\nComprehensive guidance on performing ISO 26262-compliant Hazard Analysis and Risk Assessment (HARA) for automotive E\u002FE systems, including hazard identification, situation analysis, severity\u002Fexposure\u002Fcontrollability classification, and ASIL determination.\n\n## HARA Overview\n\n### Purpose and Scope\n\n**Objectives:**\n- Identify potential hazards from malfunctioning behavior\n- Assess risk level of each hazardous event\n- Determine Automotive Safety Integrity Level (ASIL)\n- Define safety goals to mitigate unacceptable risks\n\n**When to Perform HARA:**\n- Concept phase (Part 3 of ISO 26262)\n- New vehicle\u002Fsystem development\n- Major system modifications\n- Changes to operational context\n- New use cases or operational scenarios\n\n### HARA Process Flow\n\n```\n┌────────────────────────────────┐\n│   1. Item Definition           │\n│   • Boundaries                 │\n│   • Functions                  │\n│   • Interfaces                 │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   2. Hazard Identification     │\n│   • Malfunctioning behavior    │\n│   • Hazard types               │\n│   • Brainstorming sessions     │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   3. Situation Analysis        │\n│   • Operating scenarios        │\n│   • Driving conditions         │\n│   • Vehicle states             │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   4. Risk Classification       │\n│   • Severity (S0-S3)           │\n│   • Exposure (E0-E4)           │\n│   • Controllability (C0-C3)    │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   5. ASIL Determination        │\n│   • Apply ASIL table           │\n│   • Document rationale         │\n│   • Define safety goals        │\n└────────────────────────────────┘\n```\n\n## Severity Classification (S)\n\n### S0: No Injuries\n\n**Definition:** No injuries occur\n\n**Examples:**\n- Infotainment system freeze (no impact on driving)\n- Interior courtesy light failure\n- Seat warmer malfunction\n- Radio reception loss\n- USB charging port failure\n\n**Typical Systems:**\n- Entertainment systems\n- Comfort features (non-critical)\n- Aesthetic lighting\n\n### S1: Light and Moderate Injuries\n\n**Definition:** Light and moderate injuries including at least one person with moderate injuries\n\n**Injury Examples:**\n- Whiplash\n- Minor bone fractures\n- Mild concussion\n- Bruises and contusions\n- Soft tissue injuries\n\n**Hazard Examples:**\n- Cruise control failure to disengage immediately (delay \u003C 2s)\n- Parking sensor false negative at very low speed (\u003C 5 km\u002Fh)\n- Window regulator unexpected movement during adjustment\n- Seat adjuster unintended movement while parked\n- HVAC blower maximum speed in hot conditions\n\n**Typical ASIL:** QM or ASIL A (depending on E and C)\n\n### S2: Severe and Life-Threatening Injuries\n\n**Definition:** Severe and life-threatening injuries (survival probable) to at least one person\n\n**Injury Examples:**\n- Severe bone fractures\n- Internal injuries\n- Severe head trauma (but survivable)\n- Multiple rib fractures\n- Spinal injuries (non-fatal)\n\n**Hazard Examples:**\n- Unintended acceleration (\u003C 50 km\u002Fh, short duration)\n- Steering system increased friction\u002Fresistance\n- Active suspension failure causing vehicle instability\n- Lane keeping assist unintended steering intervention\n- Automatic emergency braking false activation at moderate speed\n- Airbag non-deployment in moderate-speed collision\n\n**Typical ASIL:** ASIL B or C (depending on E and C)\n\n### S3: Life-Threatening and Fatal Injuries\n\n**Definition:** Life-threatening injuries (survival uncertain) or fatal injuries to at least one person\n\n**Injury Examples:**\n- Severe head trauma (likely fatal)\n- Multiple severe internal injuries\n- Severe burns\n- Fatal collision impact\n- Ejection from vehicle\n\n**Hazard Examples:**\n- Total brake system failure at highway speed\n- Unintended full acceleration at highway speed\n- Complete steering loss\n- Airbag inadvertent deployment while driving\n- Electronic stability control (ESC) unintended strong intervention\n- Electric vehicle high-voltage shock to occupants\n- Autonomous emergency steering wrong direction into oncoming traffic\n\n**Typical ASIL:** ASIL C or D (depending on E and C)\n\n## Exposure Classification (E)\n\n### E0: Incredibly Unlikely\n\n**Definition:** Operational situation occurs less than 0.1% of average operating time\n\n**Examples:**\n- Manufacturing test mode only\n- Service\u002Fdiagnostic mode (dealer access)\n- Valet parking mode with specific conditions\n- Trailer tow mode on vehicles rarely towing\n- Extreme weather mode (desert\u002Farctic) for temperate regions\n\n**Annual Occurrence:** Less than 1 hour per year\n\n### E1: Very Low Probability\n\n**Definition:** 0.1% to 1% of average operating time\n\n**Examples:**\n- Parallel parking maneuvers\n- Reverse gear operation\n- Hill start scenarios\n- Car wash mode\n- Off-road driving (for on-road vehicles)\n- Mountain driving with steep grades\n\n**Annual Occurrence:** 10 to 100 hours per year\n\n### E2: Low Probability\n\n**Definition:** 1% to 10% of average operating time\n\n**Examples:**\n- City\u002Furban driving\n- Stop-and-go traffic\n- Residential area driving\n- Parking lot navigation\n- School zone driving\n- Weather: rain\u002Fsnow conditions\n\n**Annual Occurrence:** 100 to 1000 hours per year\n\n### E3: Medium Probability\n\n**Definition:** 10% to 50% of average operating time\n\n**Examples:**\n- Rural road driving\n- Suburban driving\n- Two-lane highways\n- Curved roads\n- Night driving\n- Mixed traffic conditions\n\n**Annual Occurrence:** 1000 to 5000 hours per year\n\n### E4: High Probability\n\n**Definition:** More than 50% of average operating time\n\n**Examples:**\n- Highway\u002Fmotorway cruising\n- Straight road driving\n- High-speed driving (> 100 km\u002Fh)\n- Daytime driving\n- Normal weather conditions\n- Multiple occupants in vehicle\n\n**Annual Occurrence:** More than 5000 hours per year\n\n**Note:** Average vehicle operation ~10,000 hours over 10-year life\n\n## Controllability Classification (C)\n\n### C0: Controllable in General\n\n**Definition:** More than 99% of all drivers can act to prevent harm in at least 99% of situations\n\n**Characteristics:**\n- Very obvious to driver\n- Ample time to react\n- Simple corrective action\n- Multiple sensory cues\n- Minimal skill required\n\n**Examples:**\n- Single windshield wiper stops (one still works)\n- Headlight intensity reduction (not complete failure)\n- Fuel gauge inaccuracy (range warning still works)\n- Seat heater temperature slightly off target\n- Radio volume sudden change\n\n**Driver Action Required:** Simple compensation, obvious detection\n\n### C1: Simply Controllable\n\n**Definition:** At least 99% of all drivers can act to prevent harm in at least 99% of situations\n\n**Characteristics:**\n- Easily noticeable\n- Adequate time to react (> 5 seconds)\n- Straightforward corrective action\n- Clear sensory feedback\n- Average driver skill sufficient\n\n**Examples:**\n- ABS degradation (single wheel)\n- Power steering assist reduction (not loss)\n- Cruise control requiring multiple attempts to cancel\n- Automatic transmission delayed shift (\u003C 2s)\n- Tire pressure monitoring false warning\n- Parking brake electronic release delay\n\n**Driver Action Required:** Simple reaction, average skill level\n\n### C2: Normally Controllable\n\n**Definition:** At least 90% of all drivers can act to prevent harm in at least 90% of situations\n\n**Characteristics:**\n- Noticeable with attention\n- Limited time to react (1-5 seconds)\n- Requires skilled driver response\n- May need trained reaction\n- Familiar driving maneuver needed\n\n**Examples:**\n- Power steering complete loss (at speed)\n- ABS complete failure (manual braking only)\n- ESC degraded performance (reduced intervention)\n- Traction control sporadic operation\n- Engine power reduction (not total loss)\n- Automatic transmission stuck in gear\n- Regenerative braking unexpected increase\n\n**Driver Action Required:** Skilled driving, immediate attention\n\n### C3: Difficult to Control or Uncontrollable\n\n**Definition:** Less than 90% of all drivers can act to prevent harm in less than 90% of situations\n\n**Characteristics:**\n- May not be noticeable immediately\n- Very short reaction time (\u003C 1 second)\n- Requires expert driver skill\n- Counterintuitive response needed\n- Physical limitations (strength\u002Freflex)\n- Multiple simultaneous failures\n\n**Examples:**\n- Total brake failure (all systems)\n- Steering complete lockup at highway speed\n- Unintended full acceleration at highway speed\n- ESC unintended strong braking intervention in curve\n- Airbag inadvertent deployment while driving\n- All-wheel drive unintended torque split causing spin\n- Autonomous steering wrong direction at highway speed\n- Suspension sudden complete collapse\n\n**Driver Action Required:** Expert skill, may be uncontrollable\n\n## ASIL Determination Matrix\n\n### Complete ASIL Table\n\n```\n┌─────────┬──────────────────────────────────────────────────────────────┐\n│         │                    Controllability                           │\n│Severity │     C0                  C1                  C2        C3     │\n├─────────┼──────────────────────────────────────────────────────────────┤\n│   S1    │                                                              │\n│  E4     │     QM                  QM                  QM        A      │\n│  E3     │     QM                  QM                  QM        A      │\n│  E2     │     QM                  QM                  QM        QM     │\n│  E1     │     QM                  QM                  QM        QM     │\n├─────────┼──────────────────────────────────────────────────────────────┤\n│   S2    │                                                              │\n│  E4     │     QM                  A                   B         C      │\n│  E3     │     QM                  A                   B         C      │\n│  E2     │     QM                  QM                  A         B      │\n│  E1     │     QM                  QM                  QM        A      │\n├─────────┼──────────────────────────────────────────────────────────────┤\n│   S3    │                                                              │\n│  E4     │     A                   B                   C         D      │\n│  E3     │     A                   B                   C         D      │\n│  E2     │     QM                  A                   B         C      │\n│  E1     │     QM                  QM                  A         B      │\n└─────────┴──────────────────────────────────────────────────────────────┘\n```\n\n## HARA Worksheet Template\n\n### Electronic Stability Control (ESC) Example\n\n```yaml\nhara_id: \"HARA-ESC-001\"\nitem: \"Electronic Stability Control System\"\ndate: \"2024-03-19\"\nversion: \"1.0\"\nanalyst: \"Functional Safety Team\"\n\nitem_definition:\n  description: \"Electronic Stability Control (ESC) system that stabilizes the vehicle by applying individual wheel braking and reducing engine torque during oversteer\u002Fundersteer conditions\"\n  boundaries:\n    - ESC_ECU\n    - Wheel_speed_sensors (4x)\n    - Yaw_rate_sensor\n    - Lateral_acceleration_sensor\n    - Steering_angle_sensor\n    - Hydraulic_modulator_unit\n  operating_modes:\n    - ESC_active_mode\n    - ESC_off_mode (driver disabled)\n    - ABS_only_mode (ESC degraded)\n  assumptions:\n    - Driver_input_available\n    - Vehicle_in_motion\n    - Tire_grip_conditions_normal\n\nhazards:\n  - hazard_id: \"H-ESC-001\"\n    malfunctioning_behavior: \"Unintended ESC activation\"\n    description: \"ESC applies asymmetric braking when not needed\"\n\n    hazardous_events:\n      - event_id: \"HE-ESC-001-A\"\n        situation: \"Highway driving in straight line at high speed\"\n        operational_situation:\n          - Vehicle_speed: \"> 100 km\u002Fh\"\n          - Road_condition: \"Dry, straight highway\"\n          - Traffic: \"Dense traffic, nearby vehicles\"\n          - Driver_activity: \"Cruising, minimal steering input\"\n\n        severity: \"S3\"\n        severity_rationale: |\n          Unintended braking at one wheel at highway speed causes sudden\n          vehicle rotation. Driver and passengers face life-threatening\n          injuries from:\n          - Loss of control leading to collision with barriers\n          - Vehicle rollover potential\n          - Rear-end collision from following vehicles\n\n        exposure: \"E4\"\n        exposure_rationale: |\n          Highway driving accounts for > 50% of vehicle operating time for\n          typical usage. Straight-line cruising is the primary highway mode.\n          Estimated exposure: 60% of total driving time.\n\n        controllability: \"C3\"\n        controllability_rationale: |\n          At high speed (> 100 km\u002Fh), sudden asymmetric braking creates:\n          - Immediate yaw rotation (\u003C 500ms to loss of control)\n          - Counterintuitive response needed (accelerate to regain control)\n          - Physical limitation (steering correction requires high torque)\n          - \u003C 90% of drivers can successfully recover\n          - Professional driver training required for recovery\n\n        asil: \"ASIL-D\"\n\n        safety_goal:\n          sg_id: \"SG-ESC-001\"\n          description: \"Prevent unintended ESC activation\"\n          safe_state: \"ESC disabled, manual control\"\n          ftti: \"150 ms\"\n          verification:\n            - Fault_injection_testing\n            - Vehicle_dynamics_simulation\n            - Proving_ground_testing\n\n      - event_id: \"HE-ESC-001-B\"\n        situation: \"Low-speed parking maneuver\"\n        operational_situation:\n          - Vehicle_speed: \"\u003C 10 km\u002Fh\"\n          - Location: \"Parking lot\"\n          - Maneuver: \"Tight turn, sharp steering\"\n\n        severity: \"S1\"\n        severity_rationale: |\n          At low speed, unintended braking causes minor vehicle movement.\n          Potential for light injuries from sudden stop (whiplash).\n          Low collision energy.\n\n        exposure: \"E1\"\n        exposure_rationale: |\n          Parking maneuvers occur \u003C 1% of operating time.\n          Estimated: 50 hours per year.\n\n        controllability: \"C1\"\n        controllability_rationale: |\n          Low speed provides ample reaction time.\n          Simple corrective action: release accelerator, re-apply carefully.\n          99% of drivers can handle this situation.\n\n        asil: \"QM\"\n\n        safety_goal:\n          sg_id: \"None (QM)\"\n          description: \"Managed through quality management\"\n\n  - hazard_id: \"H-ESC-002\"\n    malfunctioning_behavior: \"ESC failure to activate\"\n    description: \"ESC does not intervene when vehicle is losing stability\"\n\n    hazardous_events:\n      - event_id: \"HE-ESC-002-A\"\n        situation: \"Cornering on wet highway exit ramp\"\n        operational_situation:\n          - Vehicle_speed: \"70 km\u002Fh\"\n          - Road_condition: \"Wet, curved ramp (radius 50m)\"\n          - Weather: \"Rain, reduced tire grip\"\n          - Lateral_acceleration: \"> 0.7g\"\n\n        severity: \"S3\"\n        severity_rationale: |\n          Without ESC intervention, vehicle enters uncontrolled oversteer:\n          - Spin into barrier or oncoming traffic\n          - Rollover potential for SUVs\n          - Life-threatening collision likely\n\n        exposure: \"E3\"\n        exposure_rationale: |\n          Highway exit ramps used in 10-50% of trips.\n          Wet conditions occur 15-20% of driving time.\n          Combined exposure: ~20% of operating time.\n\n        controllability: \"C2\"\n        controllability_rationale: |\n          Skilled driver can recover from initial oversteer:\n          - Counter-steer + throttle modulation\n          - Requires advanced car control knowledge\n          - 90% of drivers can recover if trained\n          - However, typical driver (no training) success rate \u003C 70%\n          - Conservative assessment: C2\n\n        asil: \"ASIL-C\"\n\n        safety_goal:\n          sg_id: \"SG-ESC-002\"\n          description: \"ESC shall activate when vehicle stability is compromised\"\n          safe_state: \"N\u002FA (function must remain available)\"\n          ftti: \"50 ms\"\n          verification:\n            - Skidpad_testing\n            - Wet_handling_course\n            - Professional_driver_evaluation\n\n  - hazard_id: \"H-ESC-003\"\n    malfunctioning_behavior: \"Delayed ESC response\"\n    description: \"ESC intervention delayed by > 500ms\"\n\n    hazardous_events:\n      - event_id: \"HE-ESC-003-A\"\n        situation: \"Emergency lane change at highway speed\"\n        operational_situation:\n          - Vehicle_speed: \"120 km\u002Fh\"\n          - Maneuver: \"Double lane change (obstacle avoidance)\"\n          - Road_condition: \"Dry highway\"\n\n        severity: \"S2\"\n        severity_rationale: |\n          Delayed ESC allows vehicle to exceed stability limits before\n          intervention. Results in:\n          - Severe over-rotation\n          - Adjacent lane encroachment\n          - Severe injuries probable, but typically survivable\n\n        exposure: \"E2\"\n        exposure_rationale: |\n          Emergency maneuvers occur infrequently: 1-10% of operating time.\n          Estimate: 200 hours per year across all driving.\n\n        controllability: \"C2\"\n        controllability_rationale: |\n          Delayed ESC reduces effectiveness but some correction provided.\n          Skilled driver can compensate with reduced ESC authority.\n          ~85% success rate with trained drivers.\n\n        asil: \"ASIL-B\"\n\n        safety_goal:\n          sg_id: \"SG-ESC-003\"\n          description: \"ESC response time shall be \u003C 100ms from instability detection\"\n          safe_state: \"Graceful degradation to ABS-only\"\n          ftti: \"100 ms\"\n          verification:\n            - Real-time_latency_measurement\n            - HIL_testing_with_vehicle_dynamics_model\n\nsummary:\n  total_hazards: 3\n  total_hazardous_events: 5\n  asil_distribution:\n    asil_d: 1\n    asil_c: 1\n    asil_b: 1\n    asil_a: 0\n    qm: 2\n  highest_asil: \"ASIL-D\"\n  safety_goals_required: 3\n```\n\n## Advanced HARA Techniques\n\n### Situation Analysis Matrix\n\n**Multi-Dimensional Situation Space:**\n\n```\nDimension 1: Vehicle Speed\n├── 0-10 km\u002Fh (parking)\n├── 10-50 km\u002Fh (urban)\n├── 50-100 km\u002Fh (rural)\n└── > 100 km\u002Fh (highway)\n\nDimension 2: Road Conditions\n├── Dry\n├── Wet\n├── Snow\u002FIce\n└── Off-road\n\nDimension 3: Traffic Density\n├── No traffic\n├── Light traffic\n├── Dense traffic\n└── Traffic jam\n\nDimension 4: Driver State\n├── Attentive\n├── Distracted\n├── Drowsy\n└── Impaired (medical emergency)\n\nDimension 5: Time of Day\n├── Day (good visibility)\n├── Dusk\u002Fdawn (reduced visibility)\n└── Night (limited visibility)\n```\n\n**Coverage Matrix Example:**\n```\nSpeed vs Road Conditions:\n\n         │ Dry │ Wet │Snow │ Ice │\n─────────┼─────┼─────┼─────┼─────┤\n0-10km\u002Fh │  ✓  │  ✓  │  ✓  │  ✓  │\n10-50    │  ✓  │  ✓  │  ✓  │  ✓  │\n50-100   │  ✓  │  ✓  │  ✓  │  -  │\n>100km\u002Fh │  ✓  │  ✓  │  -  │  -  │\n\n✓ = Situation analyzed\n- = Situation not applicable (speed limits)\n```\n\n### Controllability Assessment Methods\n\n**Method 1: Expert Judgment**\n- Panel of experienced drivers\n- Simulator testing with representative population\n- Statistical analysis of crash avoidance rates\n\n**Method 2: Accident Statistics**\n- Historical crash data analysis\n- Similar malfunction scenarios\n- Injury severity correlation\n\n**Method 3: Simulator Studies**\n```python\n# Controllability test protocol\ntest_setup = {\n    'participants': 100,  # Diverse driver population\n    'age_range': (18, 75),\n    'experience_range': (1, 50),  # years driving\n    'scenarios': 20,  # per hazardous event\n    'success_criteria': 'No collision AND vehicle stable'\n}\n\n# Classification\nif success_rate > 0.99:\n    controllability = \"C0\"\nelif success_rate >= 0.99:\n    controllability = \"C1\"\nelif success_rate >= 0.90:\n    controllability = \"C2\"\nelse:\n    controllability = \"C3\"\n```\n\n### Exposure Data Collection\n\n**Data Sources:**\n1. **Naturalistic Driving Studies**\n   - Real-world driving data\n   - GPS logging\n   - CAN bus data collection\n   - 100+ vehicles over 1+ years\n\n2. **Fleet Telemetry**\n   - Connected vehicle data\n   - Aggregate usage patterns\n   - Scenario frequency statistics\n\n3. **Statistical Databases**\n   - NHTSA (US)\n   - GIDAS (Germany)\n   - STATS19 (UK)\n\n**Exposure Calculation Example:**\n```python\n# Calculate exposure for \"highway driving > 100 km\u002Fh\"\ndef calculate_exposure(telemetry_data):\n    total_hours = sum(trip.duration for trip in telemetry_data)\n    highway_hours = sum(\n        trip.duration\n        for trip in telemetry_data\n        if trip.speed > 100 and trip.road_type == 'highway'\n    )\n\n    exposure_percentage = (highway_hours \u002F total_hours) * 100\n\n    # Map to E-class\n    if exposure_percentage \u003C 0.1:\n        return \"E0\"\n    elif exposure_percentage \u003C 1:\n        return \"E1\"\n    elif exposure_percentage \u003C 10:\n        return \"E2\"\n    elif exposure_percentage \u003C 50:\n        return \"E3\"\n    else:\n        return \"E4\"\n\n# Example data\ntelemetry = [\n    {'duration': 120, 'speed': 110, 'road_type': 'highway'},  # 2 hours\n    {'duration': 30, 'speed': 40, 'road_type': 'urban'},      # 0.5 hours\n    {'duration': 50, 'speed': 80, 'road_type': 'rural'},      # 0.83 hours\n    # ... 1000s more trips\n]\n\nexposure_class = calculate_exposure(telemetry)\n```\n\n## HARA Documentation\n\n### Safety Case Integration\n\n```markdown\n# Safety Case Section: HARA Evidence\n\n## 1. Completeness Argument\n\n**Claim:** All relevant hazards have been identified for the ESC system.\n\n**Evidence:**\n- E1: HARA workshop with cross-functional team (attendees: safety engineer,\n      system engineer, test engineer, domain expert)\n- E2: Review of similar system hazards from database (23 ESC systems analyzed)\n- E3: Historical accident data review (GIDAS database, 1000+ ESC-related incidents)\n- E4: FMEA results cross-checked with HARA hazard list\n- E5: Independent safety assessment review confirmation\n\n**Sub-Claim 1.1:** Malfunction types cover all failure modes\n**Sub-Claim 1.2:** Operating situations cover representative vehicle usage\n\n## 2. Classification Accuracy Argument\n\n**Claim:** Severity, Exposure, and Controllability classifications are justified.\n\n**Evidence:**\n- E6: Severity based on MAIS (Maximum Abbreviated Injury Scale) correlation\n- E7: Exposure derived from 500-vehicle naturalistic driving study (12 months)\n- E8: Controllability validated through driving simulator study (N=120 drivers)\n- E9: Expert panel review of all classifications (unanimous agreement)\n\n## 3. ASIL Determination Argument\n\n**Claim:** ASIL assignments correctly follow ISO 26262-3 table.\n\n**Evidence:**\n- E10: ASIL determination matrix applied consistently to all hazardous events\n- E11: Independent verification of ASIL assignments (0 discrepancies)\n- E12: Traceability from S\u002FE\u002FC to ASIL documented in HARA database\n```\n\n### Review Checklist\n\n**HARA Quality Review:**\n\n- [ ] Item definition complete and approved\n- [ ] All operating modes considered\n- [ ] Hazards derived from malfunctioning behavior (not internal faults)\n- [ ] Operational situations representative and complete\n- [ ] Severity classification justified with injury mechanism\n- [ ] Exposure based on quantitative data (not assumptions)\n- [ ] Controllability assessed with driver population consideration\n- [ ] ASIL determination traceable to S\u002FE\u002FC\n- [ ] Safety goals defined for all ASIL hazards\n- [ ] Safe state specified for each safety goal\n- [ ] FTTI specified and justified\n- [ ] Cross-check with FMEA\u002FFTA performed\n- [ ] Independent review completed\n- [ ] All findings from reviews addressed\n- [ ] HARA approved by functional safety manager\n\n## Production-Ready Templates\n\n### HARA Database Schema (SQL)\n\n```sql\n-- Items table\nCREATE TABLE Items (\n    item_id VARCHAR(50) PRIMARY KEY,\n    item_name VARCHAR(200),\n    description TEXT,\n    version VARCHAR(20),\n    status VARCHAR(20),\n    created_date DATE,\n    updated_date DATE\n);\n\n-- Hazards table\nCREATE TABLE Hazards (\n    hazard_id VARCHAR(50) PRIMARY KEY,\n    item_id VARCHAR(50) REFERENCES Items(item_id),\n    malfunctioning_behavior TEXT,\n    description TEXT,\n    identified_by VARCHAR(100),\n    identified_date DATE\n);\n\n-- Hazardous Events table\nCREATE TABLE HazardousEvents (\n    event_id VARCHAR(50) PRIMARY KEY,\n    hazard_id VARCHAR(50) REFERENCES Hazards(hazard_id),\n    situation_description TEXT,\n    operational_situation JSONB,\n    severity VARCHAR(2),\n    severity_rationale TEXT,\n    exposure VARCHAR(2),\n    exposure_rationale TEXT,\n    controllability VARCHAR(2),\n    controllability_rationale TEXT,\n    asil VARCHAR(6),\n    review_status VARCHAR(20),\n    reviewer VARCHAR(100),\n    review_date DATE\n);\n\n-- Safety Goals table\nCREATE TABLE SafetyGoals (\n    sg_id VARCHAR(50) PRIMARY KEY,\n    event_id VARCHAR(50) REFERENCES HazardousEvents(event_id),\n    description TEXT,\n    safe_state TEXT,\n    ftti_ms INT,\n    asil VARCHAR(6),\n    status VARCHAR(20),\n    approved_by VARCHAR(100),\n    approved_date DATE\n);\n\n-- Exposure Data table (for evidence)\nCREATE TABLE ExposureData (\n    data_id SERIAL PRIMARY KEY,\n    event_id VARCHAR(50) REFERENCES HazardousEvents(event_id),\n    data_source VARCHAR(200),\n    measurement_value DECIMAL,\n    measurement_unit VARCHAR(50),\n    collection_date DATE,\n    sample_size INT,\n    notes TEXT\n);\n\n-- Query: Generate HARA report for ASIL-D events\nSELECT\n    h.hazard_id,\n    h.malfunctioning_behavior,\n    he.event_id,\n    he.situation_description,\n    he.severity,\n    he.exposure,\n    he.controllability,\n    he.asil,\n    sg.description AS safety_goal,\n    sg.ftti_ms\nFROM Hazards h\nJOIN HazardousEvents he ON h.hazard_id = he.hazard_id\nJOIN SafetyGoals sg ON he.event_id = sg.event_id\nWHERE he.asil = 'ASIL-D'\nORDER BY h.hazard_id;\n```\n\n### Excel HARA Template\n\n```\nSheet 1: Item Definition\n├── A: Item ID\n├── B: Item Name\n├── C: Description\n├── D: Boundaries\n├── E: Operating Modes\n└── F: Assumptions\n\nSheet 2: HARA Worksheet\n├── A: Hazard ID\n├── B: Malfunctioning Behavior\n├── C: Hazardous Event ID\n├── D: Operational Situation\n├── E: Severity (dropdown: S0-S3)\n├── F: Severity Rationale\n├── G: Exposure (dropdown: E0-E4)\n├── H: Exposure Rationale\n├── I: Controllability (dropdown: C0-C3)\n├── J: Controllability Rationale\n├── K: ASIL (formula: =VLOOKUP(...))\n└── L: Safety Goal ID\n\nSheet 3: ASIL Lookup Table\n└── Automated ASIL determination matrix\n\nSheet 4: Safety Goals\n├── A: Safety Goal ID\n├── B: Safety Goal Description\n├── C: Safe State\n├── D: FTTI (ms)\n└── E: Verification Methods\n\nSheet 5: Evidence\n├── A: Event ID\n├── B: Evidence Type (S\u002FE\u002FC)\n├── C: Data Source\n├── D: Reference Document\n└── E: Attachment\n```\n\n## References\n\n- ISO 26262-3:2018 - Concept Phase\n- SAE J2980 - Considerations for ISO 26262 ASIL Hazard Classification\n- ISO\u002FTR 4804 - Safety and cybersecurity for automated driving systems\n- GIDAS (German In-Depth Accident Study)\n- NHTSA CIREN (Crash Injury Research Engineering Network)\n\n## Related Skills\n\n- ISO 26262 Overview\n- Safety Mechanisms and Patterns\n- FMEA\u002FFTA Analysis\n- Safety Verification and Validation\n- Functional Safety Concept Development\n\n---\n\n## Iso 26262 Overview\n\n# ISO 26262 Overview - Functional Safety in Automotive\n\nComprehensive guidance on ISO 26262 standard for functional safety of electrical\u002Felectronic (E\u002FE) systems in road vehicles, covering all 12 parts, V-model lifecycle, ASIL determination, and safety concept development.\n\n## ISO 26262 Standard Structure\n\n### 12 Parts Overview\n\n**Part 1: Vocabulary**\n- Defines 200+ terms used throughout the standard\n- Key terms: ASIL, safety goal, fault, failure, safe state, FTTI, PMHF\n\n**Part 2: Management of Functional Safety**\n- Safety lifecycle management\n- Safety culture and organizational structure\n- Competence management and training\n- Quality management integration\n\n**Part 3: Concept Phase**\n- Item definition\n- Hazard Analysis and Risk Assessment (HARA)\n- Functional safety concept\n- Safety goals and ASIL determination\n\n**Part 4: Product Development at System Level**\n- Technical safety concept\n- System design and architecture\n- Verification and validation planning\n- Safety requirements allocation\n\n**Part 5: Product Development at Hardware Level**\n- Hardware safety requirements\n- Hardware design and implementation\n- Hardware architectural metrics\n- Random hardware failures (PMHF calculation)\n\n**Part 6: Product Development at Software Level**\n- Software safety requirements\n- Software architectural design\n- Software unit design and implementation\n- Software testing (unit, integration, system)\n\n**Part 7: Production, Operation, Service, Decommissioning**\n- Production planning and control\n- Field monitoring and customer support\n- Safety-related maintenance\n- Decommissioning procedures\n\n**Part 8: Supporting Processes**\n- Configuration management\n- Change management\n- Verification methods\n- Documentation standards\n- Confidence in use (reuse of components)\n\n**Part 9: ASIL-Oriented and Safety-Oriented Analyses**\n- Dependent failure analysis (DFA)\n- FMEA\u002FFMEDA methodologies\n- FTA (Fault Tree Analysis)\n- Safety analysis methods\n\n**Part 10: Guidelines**\n- Informative guidance on applying the standard\n- Examples and best practices\n- Interpretation clarifications\n\n**Part 11: Semiconductors**\n- Safety requirements for semiconductor components\n- Random hardware failures in ICs\n- Systematic capability\n- Safety manual requirements\n\n**Part 12: Motorcycles**\n- Adaptation of standard for motorcycles\n- Specific hazard scenarios\n- Controllability considerations for two-wheeled vehicles\n\n## V-Model Safety Lifecycle\n\n### Left Side (Decomposition)\n\n```\n┌─────────────────────────────────────────────┐\n│         Concept Phase (Part 3)              │\n│  • Item Definition                          │\n│  • HARA → Safety Goals → ASIL               │\n│  • Functional Safety Concept                │\n└────────────────┬────────────────────────────┘\n                 │\n                 ▼\n┌─────────────────────────────────────────────┐\n│    System Design (Part 4)                   │\n│  • Technical Safety Concept                 │\n│  • System Architecture                      │\n│  • Safety Requirements Allocation           │\n└────────┬──────────────────┬─────────────────┘\n         │                  │\n         ▼                  ▼\n┌──────────────────┐  ┌──────────────────────┐\n│  HW Design       │  │  SW Design           │\n│  (Part 5)        │  │  (Part 6)            │\n│  • HW Safety Req │  │  • SW Safety Req     │\n│  • HW Arch       │  │  • SW Arch           │\n│  • HW Design     │  │  • SW Unit Design    │\n└────────┬─────────┘  └──────────┬───────────┘\n         │                       │\n         ▼                       ▼\n┌──────────────────┐  ┌──────────────────────┐\n│  HW Implement    │  │  SW Implement        │\n│  • PCB Design    │  │  • Coding            │\n│  • Component     │  │  • Unit Testing      │\n└────────┬─────────┘  └──────────┬───────────┘\n         │                       │\n         └───────────┬───────────┘\n                     │\n```\n\n### Right Side (Integration & Verification)\n\n```\n                     │\n                     ▼\n┌─────────────────────────────────────────────┐\n│    HW\u002FSW Integration (Part 6)               │\n│  • Integration Testing                      │\n│  • Interface Verification                   │\n│  • Safety Mechanism Testing                 │\n└────────────────┬────────────────────────────┘\n                 │\n                 ▼\n┌─────────────────────────────────────────────┐\n│    System Integration (Part 4)              │\n│  • System Testing                           │\n│  • Safety Validation                        │\n│  • FTTI Verification                        │\n└────────────────┬────────────────────────────┘\n                 │\n                 ▼\n┌─────────────────────────────────────────────┐\n│    Vehicle Integration (Part 4)             │\n│  • Vehicle-level Testing                    │\n│  • Safety Goal Verification                 │\n│  • Release for Production                   │\n└─────────────────────────────────────────────┘\n```\n\n## ASIL Determination\n\n### Hazard Classification Parameters\n\n**Severity (S) - Impact of hazardous event**\n\n| Class | Description | Example |\n|-------|-------------|---------|\n| S0 | No injuries | Minor annoyance (wiper malfunction) |\n| S1 | Light\u002Fmoderate injuries | Airbag non-deployment in low-speed collision |\n| S2 | Severe\u002Flife-threatening injuries | Unintended braking at highway speed |\n| S3 | Life-threatening\u002Ffatal injuries | Total brake failure at highway speed |\n\n**Exposure (E) - Probability of operational situation**\n\n| Class | Description | Probability | Example |\n|-------|-------------|-------------|---------|\n| E0 | Incredibly unlikely | \u003C 0.1% of operating time | Test mode only |\n| E1 | Very low probability | 0.1% to 1% | Parking maneuvers |\n| E2 | Low probability | 1% to 10% | City driving |\n| E3 | Medium probability | 10% to 50% | Rural roads |\n| E4 | High probability | > 50% | Highway cruising |\n\n**Controllability (C) - Driver's ability to avoid harm**\n\n| Class | Description | Driver Action | Example |\n|-------|-------------|---------------|---------|\n| C0 | Controllable in general | Simple avoidance | Single wiper inoperative |\n| C1 | Simply controllable | 99% can avoid | ABS degradation (one wheel) |\n| C2 | Normally controllable | 90% can avoid | Power steering assist loss |\n| C3 | Difficult\u002Funcontrollable | \u003C 90% can avoid | Total brake failure |\n\n### ASIL Determination Table\n\n```\nSeverity │  Exposure    Controllability\n    S    │  E4 E3 E2 E1 │  C1    C2    C3\n─────────┼──────────────┼────────────────────\n   S1    │  A  A  QM QM │  QM    QM    A\n   S2    │  B  B  A  A  │  A     B     C\n   S3    │  C  C  B  B  │  B     C     D\n```\n\nLegend:\n- **QM**: Quality Management only (no ASIL required)\n- **ASIL A**: Lowest safety integrity\n- **ASIL B**: Medium-low safety integrity\n- **ASIL C**: Medium-high safety integrity\n- **ASIL D**: Highest safety integrity\n\n### ASIL Requirements Summary\n\n| Aspect | ASIL QM | ASIL A | ASIL B | ASIL C | ASIL D |\n|--------|---------|--------|--------|--------|--------|\n| Software Unit Testing | Recommended | + (some coverage) | ++ (branch coverage) | +++ (MC\u002FDC) | +++ (MC\u002FDC + boundary) |\n| Static Code Analysis | Optional | + | ++ | +++ | +++ |\n| Code Reviews | Basic | + | ++ | +++ | +++ |\n| FMEA | Optional | + | ++ | +++ | +++ |\n| FTA | Not required | Optional | + | ++ | +++ |\n| Hardware Diagnostic Coverage | None | > 60% | > 80% | > 90% | > 99% |\n| PMHF Target | N\u002FA | \u003C 1000 FIT | \u003C 100 FIT | \u003C 100 FIT | \u003C 10 FIT |\n\n## Safety Goal Development\n\n### Item Definition Template\n\n```yaml\nitem_name: \"Electronic Stability Control (ESC)\"\nitem_id: \"ESC-001\"\nboundaries:\n  physical:\n    - ECU_ESC_main\n    - Wheel_speed_sensors x4\n    - Steering_angle_sensor\n    - Yaw_rate_sensor\n    - Lateral_acceleration_sensor\n    - Hydraulic_modulator\n  functional:\n    - Vehicle_dynamics_control\n    - Brake_pressure_modulation\n    - Engine_torque_reduction\n  interfaces:\n    - CAN_powertrain (500 kbps)\n    - CAN_chassis (500 kbps)\n    - LIN_sensors (19.2 kbps)\n    - Brake_pressure_lines (hydraulic)\nassumptions:\n  - Tire_grip_coefficient > 0.3\n  - Sensor_supply_voltage: 5V ± 0.25V\n  - Operating_temperature: -40°C to +85°C\n  - Vehicle_speed: 0 to 200 km\u002Fh\ndependencies:\n  - ABS_system (provides wheel speed data)\n  - Engine_control (accepts torque reduction commands)\n  - Brake_system (hydraulic pressure supply)\n```\n\n### Safety Goal Template\n\n```yaml\nsafety_goal_id: \"SG-ESC-001\"\nitem: \"ESC-001\"\nhazard: \"Unintended ESC activation causing loss of vehicle control\"\nhazardous_event: \"ESC applies asymmetric braking while cornering at highway speed\"\nasil: \"ASIL-D\"\nasil_derivation:\n  severity: \"S3\"  # Life-threatening\n  exposure: \"E4\"  # Highway driving > 50% of time\n  controllability: \"C3\"  # Difficult to control at high speed\nsafety_state: \"ESC_disabled_safe_mode\"\nftti: \"150 ms\"  # Fault Tolerant Time Interval\nsafe_state_description: |\n  ESC system transitions to disabled state where:\n  - No brake pressure modulation occurs\n  - Driver has full manual braking control\n  - Warning lamp illuminated\n  - DTC stored for service\n  - Base ABS functionality maintained\nverification_criteria:\n  - No_unintended_ESC_activation_in_1000_test_runs\n  - FTTI_verified_through_fault_injection\n  - Safe_state_reached_within_150ms\n  - Warning_lamp_activation_confirmed\n```\n\n## Functional Safety Concept\n\n### Safety Requirements Allocation\n\n**Functional Safety Requirement (FSR) Example:**\n\n```yaml\nfsr_id: \"FSR-ESC-001.1\"\nsafety_goal: \"SG-ESC-001\"\ndescription: \"Detect yaw rate sensor plausibility failure\"\nrationale: \"Invalid yaw rate data can cause false ESC activation\"\nallocation: \"System-level (ESC ECU)\"\nasil: \"ASIL-D\"\nverification_method:\n  - Software_unit_test\n  - Hardware-in-loop (HIL) test\n  - Fault_injection_test\nsafety_mechanism: \"SM-ESC-YAW-001 (Yaw rate plausibility check)\"\n```\n\n**Safety Mechanism Types:**\n\n1. **Detection**: Identify faults\n   - Range checks\n   - Plausibility checks\n   - Watchdogs\n   - CRC\u002Fchecksum\n\n2. **Control**: Transition to safe state\n   - Redundant channels\n   - Voting mechanisms\n   - Graceful degradation\n   - Fail-silent\u002Ffail-operational\n\n3. **Warning**: Alert driver\u002Fsystem\n   - Warning lamps\n   - Acoustic signals\n   - Haptic feedback\n   - DTC logging\n\n## Technical Safety Concept\n\n### Safety Architecture Patterns\n\n**1. Homogeneous Redundancy (1oo2)**\n```\nSensor A ──┐\n           ├──> Voter ──> Actuator\nSensor B ──┘\n```\n- Identical sensors\n- ASIL-B each → ASIL-D combined\n- Common cause failure analysis required\n\n**2. Heterogeneous Redundancy**\n```\nRadar ────┐\n          ├──> Fusion ──> Decision\nCamera ───┘\n```\n- Different physical principles\n- Better independence\n- ASIL decomposition possible\n\n**3. Monitoring Architecture (1oo1D)**\n```\nMain Channel ────────> Actuator\n                        ^\n                        │\n                    Monitor\n```\n- Main channel + diagnostic coverage\n- ASIL decomposition: ASIL-D(D) → ASIL-B(D) + ASIL-A(D)\n\n## ASIL Decomposition\n\n### Decomposition Rules\n\n**Valid ASIL-D Decomposition:**\n- ASIL-D(D) = ASIL-C(D) + ASIL-A(D)\n- ASIL-D(D) = ASIL-B(D) + ASIL-B(D)\n- ASIL-D(D) = ASIL-B(D) + ASIL-A(D) [with additional safety mechanisms]\n\n**Requirements:**\n1. Elements must be sufficiently independent\n2. Both elements monitored for failures\n3. Dependent failures analyzed (DFA)\n4. Common cause failures addressed\n5. No single point of failure\n\n**Example - Brake-by-Wire ASIL-D Decomposition:**\n\n```yaml\nsafety_requirement: \"Brake_command_processing\"\noriginal_asil: \"ASIL-D(D)\"\ndecomposition:\n  element_1:\n    function: \"Primary_brake_command_path\"\n    asil: \"ASIL-B(D)\"\n    implementation: \"Microcontroller_core_0\"\n    safety_mechanisms:\n      - Program_flow_monitoring\n      - RAM_test\n      - CRC_on_commands\n  element_2:\n    function: \"Secondary_brake_command_path\"\n    asil: \"ASIL-B(D)\"\n    implementation: \"Microcontroller_core_1\"\n    safety_mechanisms:\n      - Dual_core_lockstep\n      - Cross_comparison\n      - Watchdog\nindependence_measures:\n  - Separate_memory_partitions\n  - Separate_power_supplies\n  - Different_code_implementations\n  - Independent_watchdogs\ndependent_failure_analysis:\n  - EMI_susceptibility_analyzed\n  - Common_power_rail_protected\n  - Temperature_effects_mitigated\n```\n\n## Safety Validation\n\n### Validation Methods by ASIL\n\n| Method | ASIL A | ASIL B | ASIL C | ASIL D |\n|--------|--------|--------|--------|--------|\n| Requirements review | + | ++ | ++ | +++ |\n| Design review | + | ++ | +++ | +++ |\n| Simulation testing | + | ++ | +++ | +++ |\n| Prototype testing | ++ | +++ | +++ | +++ |\n| Field testing | ++ | +++ | +++ | +++ |\n| Fault injection | Optional | + | ++ | +++ |\n| Back-to-back comparison | Optional | + | ++ | +++ |\n\n### Safety Case Structure\n\n```\nSafety Case Document\n├── 1. Item Definition\n│   ├── System boundaries\n│   ├── Assumptions\n│   └── Dependencies\n├── 2. Hazard Analysis (HARA)\n│   ├── Hazard identification\n│   ├── Risk assessment (S, E, C)\n│   └── ASIL determination\n├── 3. Safety Goals\n│   ├── Safety goal definition\n│   ├── Safe state definition\n│   └── FTTI specification\n├── 4. Functional Safety Concept\n│   ├── Functional safety requirements\n│   ├── Safety mechanisms\n│   └── Requirement allocation\n├── 5. Technical Safety Concept\n│   ├── Safety architecture\n│   ├── Technical safety requirements\n│   └── HW\u002FSW allocation\n├── 6. Safety Analysis\n│   ├── FMEA\u002FFMEDA results\n│   ├── FTA results\n│   ├── DFA results\n│   └── PMHF calculation\n├── 7. Verification Evidence\n│   ├── Test results\n│   ├── Review records\n│   └── Analysis reports\n├── 8. Validation Evidence\n│   ├── Safety goal verification\n│   ├── FTTI verification\n│   └── Field data\n└── 9. Confirmation Measures\n    ├── Functional safety audit\n    ├── Independent assessment\n    └── Confirmation review\n```\n\n## Key Metrics and Targets\n\n### Hardware Metrics\n\n**Single-Point Fault Metric (SPFM)**\n```\nSPFM = (1 - ΣλSPF \u002F ΣλTotal) × 100%\n\nTarget:\n- ASIL B: > 90%\n- ASIL C: > 97%\n- ASIL D: > 99%\n```\n\n**Latent Fault Metric (LFM)**\n```\nLFM = (1 - ΣλLF \u002F (ΣλLF + ΣλRF + ΣλDet)) × 100%\n\nTarget:\n- ASIL B: > 60%\n- ASIL C: > 80%\n- ASIL D: > 90%\n```\n\n**Probabilistic Metric for random Hardware Failures (PMHF)**\n```\nPMHF = Σ(λi × failure_rate) FIT\n\nTarget:\n- ASIL B: \u003C 100 FIT\n- ASIL C: \u003C 100 FIT\n- ASIL D: \u003C 10 FIT\n\nFIT = Failures In Time (1 FIT = 1 failure in 10⁹ hours)\n```\n\n### Software Metrics\n\n**MC\u002FDC Coverage (Modified Condition\u002FDecision Coverage)**\n- ASIL D requirement: 100% MC\u002FDC coverage\n- Critical software units only\n- Tool qualification required\n\n**Cyclomatic Complexity**\n- ASIL D recommendation: \u003C 10 per function\n- Rationale: Testability and maintainability\n\n## ISO 26262:2018 Updates\n\n### Changes from 2011 Edition\n\n1. **Semicond uctors** (New Part 11)\n   - Specific requirements for IC suppliers\n   - Safety Element out of Context (SEooC)\n   - Systematic capability determination\n\n2. **Motorcycles** (New Part 12)\n   - Adapted controllability classes\n   - Motorcycle-specific hazards\n   - Two-wheeler dynamics considerations\n\n3. **SOTIF Integration** (ISO 21448)\n   - Performance limitations\n   - Reasonably foreseeable misuse\n   - Validation of non-fault scenarios\n\n4. **Cybersecurity** (ISO 21434)\n   - Security interface with safety\n   - Threat analysis\n   - Secure development lifecycle\n\n5. **Agile Development**\n   - Guidance on iterative methods\n   - Sprint-based V-model\n   - Continuous integration considerations\n\n## Production Checklist\n\n### Phase Gate Criteria\n\n**Concept Phase Exit:**\n- [ ] Item definition approved\n- [ ] HARA completed and reviewed\n- [ ] Safety goals confirmed with ASIL\n- [ ] Functional safety concept defined\n- [ ] Safety plan approved\n\n**System Development Exit:**\n- [ ] Technical safety concept complete\n- [ ] System architecture defined\n- [ ] Safety requirements allocated to HW\u002FSW\n- [ ] Verification plan approved\n- [ ] Preliminary FMEA conducted\n\n**HW\u002FSW Development Exit:**\n- [ ] Detailed design complete\n- [ ] Implementation verified (unit tests)\n- [ ] Integration testing passed\n- [ ] Safety mechanisms validated\n- [ ] Code\u002Fdesign reviews complete\n\n**Integration Exit:**\n- [ ] System integration testing complete\n- [ ] Safety validation performed\n- [ ] FTTI verified through testing\n- [ ] Hardware metrics achieved (SPFM, LFM, PMHF)\n- [ ] Functional safety assessment passed\n\n**Production Release:**\n- [ ] Safety case complete\n- [ ] Independent safety assessment passed\n- [ ] Safety manual released\n- [ ] Production quality procedures established\n- [ ] Field monitoring plan in place\n\n## Tools and Compliance\n\n### Tool Qualification (ISO 26262-8)\n\n**Tool Confidence Levels (TCL)**\n\n| TCL | Tool Impact | Examples |\n|-----|-------------|----------|\n| TCL1 | No impact on safety | Documentation editors |\n| TCL2 | Can introduce errors | Compilers without verification |\n| TCL3 | High risk of undetected errors | Code generators, static analyzers |\n\n**Qualification Methods:**\n1. Increased confidence from use\n2. Validation of tool outputs\n3. Development per recognized standard\n4. Evaluation of tool development process\n\n### Recommended Tools\n\n**ASIL-D Qualified:**\n- MATLAB\u002FSimulink (with IEC Certification Kit)\n- SCADE Suite (qualified per ISO 26262)\n- TargetLink (qualified code generator)\n- Polyspace (static analyzer)\n- LDRA (unit test + coverage)\n- Vector CANoe\u002FCANalyzer (HIL testing)\n\n## References\n\n- ISO 26262-1:2018 to ISO 26262-12:2018 (full standard)\n- ISO\u002FPAS 21448:2019 (SOTIF - Safety of the Intended Functionality)\n- ISO\u002FSAE 21434:2021 (Cybersecurity for road vehicles)\n- ASPICE 3.1 (Automotive SPICE)\n- MISRA C:2012 \u002F MISRA C++:2008 (coding guidelines)\n- SEooC (Safety Element out of Context) guidelines\n\n## Related Skills\n\n- Hazard Analysis and Risk Assessment (HARA)\n- Safety Mechanisms and Patterns\n- FMEA\u002FFTA Analysis\n- Software Safety Requirements\n- Safety Verification and Validation\n\n---\n\n## Safety Mechanisms Patterns\n\n# Safety Mechanisms and Patterns for ISO 26262\n\nComprehensive catalog of safety mechanisms for ASIL-D automotive systems, including redundancy patterns, diagnostic coverage techniques, watchdogs, memory protection, CRC\u002Fchecksums, plausibility checks, and safe state management.\n\n## Safety Mechanism Categories\n\n### Detection Mechanisms\n- Identify faults before they cause failures\n- Achieve diagnostic coverage targets\n- Enable transition to safe state within FTTI\n\n### Control Mechanisms\n- Manage system behavior during faults\n- Implement redundancy and voting\n- Provide graceful degradation paths\n\n### Warning Mechanisms\n- Alert driver\u002Fsystem to faults\n- Trigger DTC storage\n- Activate warning lamps\u002Fsignals\n\n## Redundancy Patterns\n\n### 1. Homogeneous Redundancy (1oo2)\n\n**One-out-of-Two Configuration:**\n\n```\n┌──────────┐\n│ Sensor A │─────┐\n└──────────┘     │      ┌────────┐     ┌──────────┐\n                 ├─────>│ Voter  │────>│ Actuator │\n┌──────────┐     │      └────────┘     └──────────┘\n│ Sensor B │─────┘\n└──────────┘\n```\n\n**Characteristics:**\n- Two identical channels (same design, same component)\n- Any one channel can drive the system\n- ASIL decomposition: ASIL-D(D) = ASIL-B(D) + ASIL-B(D)\n- Requires dependent failure analysis (common cause)\n\n**C Implementation:**\n```c\n\u002F\u002F 1oo2 redundant sensor processing\ntypedef struct {\n    float sensor_a_value;\n    float sensor_b_value;\n    bool sensor_a_valid;\n    bool sensor_b_valid;\n    uint32_t fault_counter_a;\n    uint32_t fault_counter_b;\n} RedundantSensor_t;\n\ntypedef enum {\n    VOTER_OUTPUT_VALID,\n    VOTER_OUTPUT_DEGRADED,\n    VOTER_OUTPUT_FAULT\n} VoterStatus_t;\n\nVoterStatus_t ProcessRedundantSensors(\n    RedundantSensor_t *sensors,\n    float *output_value\n) {\n    const float TOLERANCE = 0.05f;  \u002F\u002F 5% agreement tolerance\n    const uint32_t FAULT_THRESHOLD = 3;\n\n    \u002F\u002F Range check both sensors\n    if (!RangeCheck(sensors->sensor_a_value, 0.0f, 100.0f)) {\n        sensors->sensor_a_valid = false;\n        sensors->fault_counter_a++;\n    } else {\n        sensors->sensor_a_valid = true;\n    }\n\n    if (!RangeCheck(sensors->sensor_b_value, 0.0f, 100.0f)) {\n        sensors->sensor_b_valid = false;\n        sensors->fault_counter_b++;\n    } else {\n        sensors->sensor_b_valid = true;\n    }\n\n    \u002F\u002F Both sensors valid - check agreement\n    if (sensors->sensor_a_valid && sensors->sensor_b_valid) {\n        float difference = fabsf(sensors->sensor_a_value - sensors->sensor_b_value);\n        float average = (sensors->sensor_a_value + sensors->sensor_b_value) \u002F 2.0f;\n\n        if (difference \u002F average \u003C TOLERANCE) {\n            \u002F\u002F Sensors agree - use average\n            *output_value = average;\n            return VOTER_OUTPUT_VALID;\n        } else {\n            \u002F\u002F Sensors disagree - both might be faulty\n            \u002F\u002F Use most conservative value\n            *output_value = fmaxf(sensors->sensor_a_value, sensors->sensor_b_value);\n            return VOTER_OUTPUT_DEGRADED;\n        }\n    }\n\n    \u002F\u002F Only sensor A valid\n    if (sensors->sensor_a_valid && !sensors->sensor_b_valid) {\n        if (sensors->fault_counter_b \u003C FAULT_THRESHOLD) {\n            *output_value = sensors->sensor_a_value;\n            return VOTER_OUTPUT_DEGRADED;\n        } else {\n            return VOTER_OUTPUT_FAULT;\n        }\n    }\n\n    \u002F\u002F Only sensor B valid\n    if (!sensors->sensor_a_valid && sensors->sensor_b_valid) {\n        if (sensors->fault_counter_a \u003C FAULT_THRESHOLD) {\n            *output_value = sensors->sensor_b_value;\n            return VOTER_OUTPUT_DEGRADED;\n        } else {\n            return VOTER_OUTPUT_FAULT;\n        }\n    }\n\n    \u002F\u002F Both sensors invalid\n    return VOTER_OUTPUT_FAULT;\n}\n```\n\n### 2. Heterogeneous Redundancy\n\n**Different Physical Principles:**\n\n```\n┌────────────┐\n│   Radar    │────┐\n└────────────┘    │     ┌─────────┐      ┌──────────┐\n                  ├────>│ Fusion  │─────>│ Decision │\n┌────────────┐    │     └─────────┘      └──────────┘\n│   Camera   │────┘\n└────────────┘\n```\n\n**Benefits:**\n- Better independence (different failure modes)\n- Common cause failures less likely\n- Easier ASIL decomposition justification\n\n**Example - Vehicle Speed Estimation:**\n```c\n\u002F\u002F Heterogeneous speed measurement\ntypedef struct {\n    float wheel_speed_fl;      \u002F\u002F Front-left wheel speed sensor\n    float wheel_speed_fr;      \u002F\u002F Front-right wheel speed sensor\n    float accelerometer_speed; \u002F\u002F Integrated from accelerometer\n    float gps_speed;           \u002F\u002F GPS-based speed\n} SpeedSources_t;\n\nfloat FuseSpeedMeasurements(SpeedSources_t *sources) {\n    const float WHEEL_WEIGHT = 0.7f;\n    const float ACCEL_WEIGHT = 0.2f;\n    const float GPS_WEIGHT = 0.1f;\n\n    \u002F\u002F Primary: Average of wheel speeds\n    float wheel_speed_avg = (sources->wheel_speed_fl + sources->wheel_speed_fr) \u002F 2.0f;\n\n    \u002F\u002F Plausibility check: compare wheel speed to accelerometer\n    float speed_delta = fabsf(wheel_speed_avg - sources->accelerometer_speed);\n\n    if (speed_delta \u003C 5.0f) {  \u002F\u002F Within 5 km\u002Fh\n        \u002F\u002F All sources agree - weighted fusion\n        float fused_speed = (wheel_speed_avg * WHEEL_WEIGHT) +\n                            (sources->accelerometer_speed * ACCEL_WEIGHT) +\n                            (sources->gps_speed * GPS_WEIGHT);\n        return fused_speed;\n    } else {\n        \u002F\u002F Potential wheel slip - rely more on accelerometer\n        return sources->accelerometer_speed;\n    }\n}\n```\n\n### 3. Dual-Core Lockstep\n\n**Hardware-Level Redundancy:**\n\n```\n┌──────────────┐\n│   Core 0     │──┐\n│ (Leading)    │  │   ┌───────────────┐\n└──────────────┘  ├──>│   Comparator  │──> Fault Signal\n                  │   └───────────────┘\n┌──────────────┐  │\n│   Core 1     │──┘\n│ (Trailing)   │\n└──────────────┘\n```\n\n**Characteristics:**\n- Two CPU cores execute identical instructions\n- Outputs compared cycle-by-cycle\n- Any mismatch triggers fault reaction\n- ASIL-D without software redundancy\n\n**Lockstep Monitor (Conceptual):**\n```c\n\u002F\u002F This is typically implemented in hardware, but shown for understanding\ntypedef struct {\n    uint32_t core0_output;\n    uint32_t core1_output;\n    uint32_t mismatch_counter;\n    bool lockstep_fault;\n} LockstepMonitor_t;\n\nvoid CheckLockstep(LockstepMonitor_t *monitor) {\n    const uint32_t MISMATCH_THRESHOLD = 1;  \u002F\u002F Zero tolerance for lockstep\n\n    if (monitor->core0_output != monitor->core1_output) {\n        monitor->mismatch_counter++;\n\n        if (monitor->mismatch_counter >= MISMATCH_THRESHOLD) {\n            monitor->lockstep_fault = true;\n            \u002F\u002F Trigger immediate safe state\n            EnterSafeState();\n            \u002F\u002F Generate DTC\n            SetDTC(DTC_LOCKSTEP_FAULT);\n            \u002F\u002F Activate warning lamp\n            ActivateWarningLamp(WARNING_LAMP_ENGINE);\n        }\n    } else {\n        \u002F\u002F Reset counter if outputs match\n        monitor->mismatch_counter = 0;\n    }\n}\n```\n\n### 4. 2oo3 Voting (Two-out-of-Three)\n\n**Triple Modular Redundancy:**\n\n```\n┌──────────┐\n│ Channel A│───┐\n└──────────┘   │\n               │    ┌────────────┐      ┌──────────┐\n┌──────────┐   ├───>│ 2oo3 Voter │─────>│ Actuator │\n│ Channel B│───┤    └────────────┘      └──────────┘\n└──────────┘   │\n               │\n┌──────────┐   │\n│ Channel C│───┘\n└──────────┘\n```\n\n**Voter Logic:**\n```c\n\u002F\u002F 2oo3 voting for critical safety function\ntypedef struct {\n    float channel_a;\n    float channel_b;\n    float channel_c;\n    bool channel_a_fault;\n    bool channel_b_fault;\n    bool channel_c_fault;\n} TripleChannels_t;\n\nbool Vote2oo3(TripleChannels_t *channels, float *output) {\n    const float VOTE_TOLERANCE = 0.02f;  \u002F\u002F 2% agreement\n\n    int valid_count = 0;\n    if (!channels->channel_a_fault) valid_count++;\n    if (!channels->channel_b_fault) valid_count++;\n    if (!channels->channel_c_fault) valid_count++;\n\n    \u002F\u002F Need at least 2 valid channels\n    if (valid_count \u003C 2) {\n        return false;\n    }\n\n    \u002F\u002F Check agreement between pairs\n    bool ab_agree = fabsf(channels->channel_a - channels->channel_b) \u002F\n                    channels->channel_a \u003C VOTE_TOLERANCE;\n    bool ac_agree = fabsf(channels->channel_a - channels->channel_c) \u002F\n                    channels->channel_a \u003C VOTE_TOLERANCE;\n    bool bc_agree = fabsf(channels->channel_b - channels->channel_c) \u002F\n                    channels->channel_b \u003C VOTE_TOLERANCE;\n\n    \u002F\u002F A and B agree\n    if (ab_agree && !channels->channel_a_fault && !channels->channel_b_fault) {\n        *output = (channels->channel_a + channels->channel_b) \u002F 2.0f;\n        if (!ac_agree && !channels->channel_c_fault) {\n            \u002F\u002F C is outlier - mark as faulty\n            channels->channel_c_fault = true;\n        }\n        return true;\n    }\n\n    \u002F\u002F A and C agree\n    if (ac_agree && !channels->channel_a_fault && !channels->channel_c_fault) {\n        *output = (channels->channel_a + channels->channel_c) \u002F 2.0f;\n        if (!ab_agree && !channels->channel_b_fault) {\n            channels->channel_b_fault = true;\n        }\n        return true;\n    }\n\n    \u002F\u002F B and C agree\n    if (bc_agree && !channels->channel_b_fault && !channels->channel_c_fault) {\n        *output = (channels->channel_b + channels->channel_c) \u002F 2.0f;\n        if (!ab_agree && !channels->channel_a_fault) {\n            channels->channel_a_fault = true;\n        }\n        return true;\n    }\n\n    \u002F\u002F No agreement among any pair\n    return false;\n}\n```\n\n## Watchdog Mechanisms\n\n### 1. Window Watchdog\n\n**Timing Constraints:**\n```c\n\u002F\u002F Window watchdog - must refresh within time window\ntypedef struct {\n    uint32_t window_min_ms;  \u002F\u002F Minimum time before refresh allowed\n    uint32_t window_max_ms;  \u002F\u002F Maximum time before timeout\n    uint32_t last_refresh_time;\n    bool watchdog_fault;\n} WindowWatchdog_t;\n\nvoid InitWindowWatchdog(WindowWatchdog_t *wdt, uint32_t min_ms, uint32_t max_ms) {\n    wdt->window_min_ms = min_ms;\n    wdt->window_max_ms = max_ms;\n    wdt->last_refresh_time = GetSystemTimeMs();\n    wdt->watchdog_fault = false;\n}\n\nvoid RefreshWindowWatchdog(WindowWatchdog_t *wdt) {\n    uint32_t current_time = GetSystemTimeMs();\n    uint32_t elapsed = current_time - wdt->last_refresh_time;\n\n    \u002F\u002F Check if refresh is too early\n    if (elapsed \u003C wdt->window_min_ms) {\n        wdt->watchdog_fault = true;\n        SetDTC(DTC_WATCHDOG_EARLY_REFRESH);\n        EnterSafeState();\n        return;\n    }\n\n    \u002F\u002F Check if refresh is too late\n    if (elapsed > wdt->window_max_ms) {\n        wdt->watchdog_fault = true;\n        SetDTC(DTC_WATCHDOG_TIMEOUT);\n        EnterSafeState();\n        return;\n    }\n\n    \u002F\u002F Valid refresh - update timestamp\n    wdt->last_refresh_time = current_time;\n    wdt->watchdog_fault = false;\n\n    \u002F\u002F Refresh hardware watchdog\n    HW_WDT_Refresh();\n}\n\n\u002F\u002F Monitor task - checks watchdog status\nvoid WatchdogMonitorTask(void) {\n    WindowWatchdog_t *wdt = GetSystemWatchdog();\n\n    uint32_t current_time = GetSystemTimeMs();\n    uint32_t elapsed = current_time - wdt->last_refresh_time;\n\n    if (elapsed > wdt->window_max_ms) {\n        \u002F\u002F Watchdog expired - enter safe state\n        wdt->watchdog_fault = true;\n        EnterSafeState();\n    }\n}\n```\n\n### 2. Logical Program Flow Monitoring\n\n**Checkpoints and Sequence Validation:**\n\n```c\n\u002F\u002F Program flow monitor - detects unexpected execution paths\ntypedef enum {\n    CHECKPOINT_INIT = 0x01,\n    CHECKPOINT_SENSOR_READ = 0x02,\n    CHECKPOINT_CALCULATION = 0x04,\n    CHECKPOINT_OUTPUT = 0x08,\n    CHECKPOINT_END = 0x10\n} Checkpoint_t;\n\ntypedef struct {\n    uint32_t expected_sequence;\n    uint32_t actual_sequence;\n    uint32_t sequence_errors;\n} ProgramFlowMonitor_t;\n\nstatic ProgramFlowMonitor_t flow_monitor;\n\nvoid InitProgramFlowMonitor(void) {\n    flow_monitor.expected_sequence = CHECKPOINT_INIT |\n                                     CHECKPOINT_SENSOR_READ |\n                                     CHECKPOINT_CALCULATION |\n                                     CHECKPOINT_OUTPUT |\n                                     CHECKPOINT_END;\n    flow_monitor.actual_sequence = 0;\n    flow_monitor.sequence_errors = 0;\n}\n\nvoid RecordCheckpoint(Checkpoint_t checkpoint) {\n    flow_monitor.actual_sequence |= checkpoint;\n}\n\nvoid ValidateProgramFlow(void) {\n    if (flow_monitor.actual_sequence != flow_monitor.expected_sequence) {\n        flow_monitor.sequence_errors++;\n\n        if (flow_monitor.sequence_errors > 3) {\n            SetDTC(DTC_PROGRAM_FLOW_ERROR);\n            EnterSafeState();\n        }\n    } else {\n        \u002F\u002F Reset error counter on successful execution\n        flow_monitor.sequence_errors = 0;\n    }\n\n    \u002F\u002F Reset for next cycle\n    flow_monitor.actual_sequence = 0;\n}\n\n\u002F\u002F Critical function with flow monitoring\nvoid SafetyFunction_Example(void) {\n    RecordCheckpoint(CHECKPOINT_INIT);\n\n    \u002F\u002F Initialize\n    InitializeInputs();\n\n    RecordCheckpoint(CHECKPOINT_SENSOR_READ);\n\n    \u002F\u002F Read sensors\n    float sensor_value = ReadSensor();\n\n    RecordCheckpoint(CHECKPOINT_CALCULATION);\n\n    \u002F\u002F Perform calculation\n    float result = ProcessSensorData(sensor_value);\n\n    RecordCheckpoint(CHECKPOINT_OUTPUT);\n\n    \u002F\u002F Output result\n    WriteActuator(result);\n\n    RecordCheckpoint(CHECKPOINT_END);\n\n    \u002F\u002F Validate execution path\n    ValidateProgramFlow();\n}\n```\n\n## CRC and Checksum Mechanisms\n\n### 1. CRC-16 for Message Integrity\n\n```c\n\u002F\u002F CRC-16-CCITT (polynomial 0x1021)\nuint16_t CalculateCRC16(const uint8_t *data, uint16_t length) {\n    uint16_t crc = 0xFFFF;  \u002F\u002F Initial value\n    const uint16_t polynomial = 0x1021;\n\n    for (uint16_t i = 0; i \u003C length; i++) {\n        crc ^= (uint16_t)(data[i] \u003C\u003C 8);\n\n        for (uint8_t bit = 0; bit \u003C 8; bit++) {\n            if (crc & 0x8000) {\n                crc = (crc \u003C\u003C 1) ^ polynomial;\n            } else {\n                crc \u003C\u003C= 1;\n            }\n        }\n    }\n\n    return crc;\n}\n\n\u002F\u002F CAN message with E2E protection\ntypedef struct {\n    uint32_t message_id;\n    uint8_t data[8];\n    uint8_t data_length;\n    uint16_t crc;\n    uint8_t alive_counter;\n} SafetyMessage_t;\n\nbool ValidateSafetyMessage(SafetyMessage_t *msg) {\n    \u002F\u002F Calculate expected CRC (exclude CRC field itself)\n    uint16_t calculated_crc = CalculateCRC16(msg->data, msg->data_length);\n\n    \u002F\u002F Verify CRC\n    if (calculated_crc != msg->crc) {\n        SetDTC(DTC_CRC_MISMATCH);\n        return false;\n    }\n\n    \u002F\u002F Verify alive counter (detects message loss\u002Frepetition)\n    static uint8_t last_counter[256] = {0};  \u002F\u002F Per message ID\n    uint8_t expected_counter = (last_counter[msg->message_id] + 1) & 0x0F;\n\n    if (msg->alive_counter != expected_counter) {\n        SetDTC(DTC_ALIVE_COUNTER_ERROR);\n        return false;\n    }\n\n    last_counter[msg->message_id] = msg->alive_counter;\n    return true;\n}\n```\n\n### 2. AUTOSAR E2E Protection\n\n```c\n\u002F\u002F AUTOSAR E2E Profile 1 (for 8-byte CAN messages)\ntypedef struct {\n    uint8_t Counter;    \u002F\u002F 4-bit alive counter\n    uint8_t DataID;     \u002F\u002F Data identifier\n    uint16_t CRC;       \u002F\u002F 16-bit CRC\n} E2E_P01_Header_t;\n\ntypedef enum {\n    E2E_P01STATUS_OK,\n    E2E_P01STATUS_NONEWDATA,\n    E2E_P01STATUS_WRONGCRC,\n    E2E_P01STATUS_REPEATED,\n    E2E_P01STATUS_WRONGSEQUENCE\n} E2E_P01Status_t;\n\nE2E_P01Status_t E2E_P01Check(\n    const uint8_t *data,\n    uint8_t length,\n    uint8_t *last_counter\n) {\n    E2E_P01_Header_t *header = (E2E_P01_Header_t *)data;\n\n    \u002F\u002F 1. Verify CRC\n    uint16_t calculated_crc = CalculateCRC16(data + 2, length - 2);\n    if (calculated_crc != header->CRC) {\n        return E2E_P01STATUS_WRONGCRC;\n    }\n\n    \u002F\u002F 2. Check counter sequence\n    uint8_t expected_counter = (*last_counter + 1) & 0x0F;\n    if (header->Counter == *last_counter) {\n        return E2E_P01STATUS_REPEATED;\n    } else if (header->Counter != expected_counter) {\n        return E2E_P01STATUS_WRONGSEQUENCE;\n    }\n\n    \u002F\u002F 3. Update counter\n    *last_counter = header->Counter;\n\n    return E2E_P01STATUS_OK;\n}\n```\n\n## Memory Protection\n\n### 1. RAM Test Patterns\n\n```c\n\u002F\u002F March test for RAM integrity\ntypedef enum {\n    MARCH_TEST_PASS,\n    MARCH_TEST_FAIL_WRITE,\n    MARCH_TEST_FAIL_READ\n} MarchTestResult_t;\n\nMarchTestResult_t MarchTest(volatile uint32_t *ram_start, uint32_t size_words) {\n    uint32_t i;\n\n    \u002F\u002F Phase 1: Write 0 (ascending)\n    for (i = 0; i \u003C size_words; i++) {\n        ram_start[i] = 0x00000000;\n    }\n\n    \u002F\u002F Phase 2: Read 0, Write 1 (ascending)\n    for (i = 0; i \u003C size_words; i++) {\n        if (ram_start[i] != 0x00000000) {\n            return MARCH_TEST_FAIL_READ;\n        }\n        ram_start[i] = 0xFFFFFFFF;\n    }\n\n    \u002F\u002F Phase 3: Read 1, Write 0 (descending)\n    for (i = size_words; i > 0; i--) {\n        if (ram_start[i-1] != 0xFFFFFFFF) {\n            return MARCH_TEST_FAIL_READ;\n        }\n        ram_start[i-1] = 0x00000000;\n    }\n\n    \u002F\u002F Phase 4: Read 0 (descending)\n    for (i = size_words; i > 0; i--) {\n        if (ram_start[i-1] != 0x00000000) {\n            return MARCH_TEST_FAIL_READ;\n        }\n    }\n\n    return MARCH_TEST_PASS;\n}\n\n\u002F\u002F Background RAM test (runs incrementally)\ntypedef struct {\n    uint32_t *ram_start;\n    uint32_t ram_size_words;\n    uint32_t current_block;\n    uint32_t blocks_per_cycle;\n} BackgroundRAMTest_t;\n\nvoid InitBackgroundRAMTest(\n    BackgroundRAMTest_t *test,\n    uint32_t *ram_start,\n    uint32_t size_words,\n    uint32_t blocks_per_cycle\n) {\n    test->ram_start = ram_start;\n    test->ram_size_words = size_words;\n    test->current_block = 0;\n    test->blocks_per_cycle = blocks_per_cycle;\n}\n\nvoid RunBackgroundRAMTestCycle(BackgroundRAMTest_t *test) {\n    uint32_t words_per_block = test->ram_size_words \u002F test->blocks_per_cycle;\n    uint32_t start_offset = test->current_block * words_per_block;\n\n    MarchTestResult_t result = MarchTest(\n        &test->ram_start[start_offset],\n        words_per_block\n    );\n\n    if (result != MARCH_TEST_PASS) {\n        SetDTC(DTC_RAM_TEST_FAILURE);\n        EnterSafeState();\n    }\n\n    \u002F\u002F Move to next block\n    test->current_block = (test->current_block + 1) % test->blocks_per_cycle;\n}\n```\n\n### 2. Stack Overflow Detection\n\n```c\n\u002F\u002F Stack canary pattern\n#define STACK_CANARY_PATTERN 0xDEADBEEF\n\ntypedef struct {\n    uint32_t *stack_start;\n    uint32_t *stack_end;\n    uint32_t canary_value;\n} StackMonitor_t;\n\nvoid InitStackMonitor(\n    StackMonitor_t *monitor,\n    uint32_t *stack_start,\n    uint32_t *stack_end\n) {\n    monitor->stack_start = stack_start;\n    monitor->stack_end = stack_end;\n    monitor->canary_value = STACK_CANARY_PATTERN;\n\n    \u002F\u002F Place canary at stack boundary\n    *stack_end = STACK_CANARY_PATTERN;\n}\n\nbool CheckStackOverflow(StackMonitor_t *monitor) {\n    if (*monitor->stack_end != STACK_CANARY_PATTERN) {\n        SetDTC(DTC_STACK_OVERFLOW);\n        return true;\n    }\n    return false;\n}\n\n\u002F\u002F Call in task or periodic interrupt\nvoid StackMonitorTask(void) {\n    StackMonitor_t *monitor = GetStackMonitor();\n\n    if (CheckStackOverflow(monitor)) {\n        EnterSafeState();\n    }\n}\n```\n\n## Plausibility Checks\n\n### 1. Sensor Range Checks\n\n```c\n\u002F\u002F Multi-level range checking with hysteresis\ntypedef struct {\n    float min_physical;     \u002F\u002F Physical sensor limit\n    float max_physical;\n    float min_operational;  \u002F\u002F Normal operating range\n    float max_operational;\n    float hysteresis;       \u002F\u002F Debounce tolerance\n    uint32_t fault_counter;\n    uint32_t fault_threshold;\n} RangeLimits_t;\n\ntypedef enum {\n    RANGE_VALID,\n    RANGE_WARNING,\n    RANGE_FAULT\n} RangeStatus_t;\n\nRangeStatus_t CheckSensorRange(float value, RangeLimits_t *limits) {\n    \u002F\u002F Check physical limits (hard fault)\n    if (value \u003C limits->min_physical || value > limits->max_physical) {\n        limits->fault_counter++;\n\n        if (limits->fault_counter >= limits->fault_threshold) {\n            SetDTC(DTC_SENSOR_RANGE_PHYSICAL);\n            return RANGE_FAULT;\n        }\n    }\n\n    \u002F\u002F Check operational limits with hysteresis\n    if (value \u003C (limits->min_operational - limits->hysteresis) ||\n        value > (limits->max_operational + limits->hysteresis)) {\n\n        limits->fault_counter++;\n\n        if (limits->fault_counter >= limits->fault_threshold) {\n            SetDTC(DTC_SENSOR_RANGE_OPERATIONAL);\n            return RANGE_WARNING;\n        }\n    } else {\n        \u002F\u002F Value in range - reset counter\n        if (limits->fault_counter > 0) {\n            limits->fault_counter--;\n        }\n    }\n\n    return RANGE_VALID;\n}\n\n\u002F\u002F Example: Battery temperature sensor\nRangeLimits_t battery_temp_limits = {\n    .min_physical = -40.0f,      \u002F\u002F Physical sensor limit\n    .max_physical = 125.0f,\n    .min_operational = -20.0f,   \u002F\u002F Normal operating range\n    .max_operational = 60.0f,\n    .hysteresis = 2.0f,          \u002F\u002F 2°C hysteresis\n    .fault_counter = 0,\n    .fault_threshold = 3         \u002F\u002F 3 consecutive faults\n};\n```\n\n### 2. Signal Gradient Checks\n\n```c\n\u002F\u002F Detect unrealistic rate of change\ntypedef struct {\n    float last_value;\n    uint32_t last_timestamp_ms;\n    float max_gradient;  \u002F\u002F Maximum rate of change per second\n    uint32_t fault_counter;\n} GradientMonitor_t;\n\nbool CheckSignalGradient(\n    float current_value,\n    uint32_t current_timestamp_ms,\n    GradientMonitor_t *monitor\n) {\n    uint32_t delta_time_ms = current_timestamp_ms - monitor->last_timestamp_ms;\n\n    if (delta_time_ms > 0) {\n        float delta_value = current_value - monitor->last_value;\n        float gradient = (delta_value * 1000.0f) \u002F (float)delta_time_ms;  \u002F\u002F per second\n\n        if (fabsf(gradient) > monitor->max_gradient) {\n            monitor->fault_counter++;\n\n            if (monitor->fault_counter >= 3) {\n                SetDTC(DTC_SIGNAL_GRADIENT_FAULT);\n                return false;\n            }\n        } else {\n            monitor->fault_counter = 0;\n        }\n    }\n\n    \u002F\u002F Update history\n    monitor->last_value = current_value;\n    monitor->last_timestamp_ms = current_timestamp_ms;\n\n    return true;\n}\n\n\u002F\u002F Example: Vehicle speed gradient check\nGradientMonitor_t speed_gradient = {\n    .last_value = 0.0f,\n    .last_timestamp_ms = 0,\n    .max_gradient = 10.0f,  \u002F\u002F 10 m\u002Fs² max acceleration\u002Fdeceleration\n    .fault_counter = 0\n};\n```\n\n### 3. Cross-Signal Plausibility\n\n```c\n\u002F\u002F Verify consistency between related signals\ntypedef struct {\n    float wheel_speed_fl;\n    float wheel_speed_fr;\n    float wheel_speed_rl;\n    float wheel_speed_rr;\n    float vehicle_speed;\n    float accelerometer_speed;\n} SpeedPlausibility_t;\n\nbool CheckSpeedPlausibility(SpeedPlausibility_t *speeds) {\n    const float MAX_WHEEL_DELTA = 20.0f;  \u002F\u002F km\u002Fh max difference between wheels\n    const float MAX_ACCEL_DELTA = 10.0f;  \u002F\u002F km\u002Fh max difference with accelerometer\n\n    \u002F\u002F Check consistency between front wheels\n    float fl_fr_delta = fabsf(speeds->wheel_speed_fl - speeds->wheel_speed_fr);\n    if (fl_fr_delta > MAX_WHEEL_DELTA) {\n        SetDTC(DTC_WHEEL_SPEED_IMPLAUSIBLE);\n        return false;\n    }\n\n    \u002F\u002F Check consistency between rear wheels\n    float rl_rr_delta = fabsf(speeds->wheel_speed_rl - speeds->wheel_speed_rr);\n    if (rl_rr_delta > MAX_WHEEL_DELTA) {\n        SetDTC(DTC_WHEEL_SPEED_IMPLAUSIBLE);\n        return false;\n    }\n\n    \u002F\u002F Check vehicle speed vs accelerometer integration\n    float accel_delta = fabsf(speeds->vehicle_speed - speeds->accelerometer_speed);\n    if (accel_delta > MAX_ACCEL_DELTA) {\n        SetDTC(DTC_SPEED_ACCEL_MISMATCH);\n        return false;\n    }\n\n    return true;\n}\n```\n\n## Safe State Management\n\n### 1. Safe State Transition\n\n```c\n\u002F\u002F Safe state state machine\ntypedef enum {\n    STATE_NORMAL_OPERATION,\n    STATE_DEGRADED_MODE,\n    STATE_SAFE_STATE,\n    STATE_EMERGENCY_SHUTDOWN\n} SystemState_t;\n\ntypedef struct {\n    SystemState_t current_state;\n    uint32_t fault_mask;\n    uint32_t warning_mask;\n    uint32_t transition_timestamp;\n    bool safe_state_locked;\n} SafeStateManager_t;\n\nvoid TransitionToSafeState(\n    SafeStateManager_t *manager,\n    uint32_t fault_code\n) {\n    \u002F\u002F Record fault\n    manager->fault_mask |= fault_code;\n    manager->transition_timestamp = GetSystemTimeMs();\n\n    switch (manager->current_state) {\n        case STATE_NORMAL_OPERATION:\n            \u002F\u002F Evaluate severity\n            if (IsCriticalFault(fault_code)) {\n                manager->current_state = STATE_SAFE_STATE;\n                EnterSafeStateActions();\n            } else {\n                manager->current_state = STATE_DEGRADED_MODE;\n                EnterDegradedModeActions();\n            }\n            break;\n\n        case STATE_DEGRADED_MODE:\n            \u002F\u002F Any additional fault → safe state\n            manager->current_state = STATE_SAFE_STATE;\n            EnterSafeStateActions();\n            break;\n\n        case STATE_SAFE_STATE:\n            \u002F\u002F Check if emergency shutdown required\n            if (IsEmergencyCondition(fault_code)) {\n                manager->current_state = STATE_EMERGENCY_SHUTDOWN;\n                EmergencyShutdownActions();\n            }\n            break;\n\n        case STATE_EMERGENCY_SHUTDOWN:\n            \u002F\u002F Terminal state - stay here\n            break;\n    }\n\n    \u002F\u002F Log state transition\n    LogStateTransition(manager->current_state, fault_code);\n\n    \u002F\u002F Activate warning lamp\n    UpdateWarningLamp(manager->current_state);\n\n    \u002F\u002F Store DTC\n    SetDTC(fault_code);\n}\n\nvoid EnterSafeStateActions(void) {\n    \u002F\u002F Disable safety-critical outputs\n    DisableActuators();\n\n    \u002F\u002F Switch to fail-safe values\n    SetFailSafeOutputs();\n\n    \u002F\u002F Maintain basic functions (e.g., manual braking)\n    EnableManualControl();\n\n    \u002F\u002F Activate warning indicators\n    ActivateWarningLamp(WARNING_LAMP_SYSTEM_FAULT);\n\n    \u002F\u002F Log event in NVM\n    StoreEventInNonVolatileMemory();\n\n    \u002F\u002F Notify other ECUs via CAN\n    SendSafeStateNotification();\n}\n```\n\n### 2. Graceful Degradation\n\n```c\n\u002F\u002F Multi-level degradation strategy\ntypedef enum {\n    PERFORMANCE_FULL,        \u002F\u002F 100% capability\n    PERFORMANCE_REDUCED_1,   \u002F\u002F 80% capability\n    PERFORMANCE_REDUCED_2,   \u002F\u002F 50% capability\n    PERFORMANCE_MINIMAL,     \u002F\u002F 20% capability (safety only)\n    PERFORMANCE_DISABLED     \u002F\u002F 0% (safe state)\n} PerformanceLevel_t;\n\ntypedef struct {\n    PerformanceLevel_t current_level;\n    uint32_t redundancy_available;\n    uint32_t faults_detected;\n} DegradationManager_t;\n\nvoid UpdatePerformanceLevel(DegradationManager_t *manager) {\n    \u002F\u002F Determine performance level based on fault state\n    if (manager->faults_detected == 0) {\n        manager->current_level = PERFORMANCE_FULL;\n    } else if (manager->redundancy_available >= 2) {\n        manager->current_level = PERFORMANCE_REDUCED_1;\n    } else if (manager->redundancy_available == 1) {\n        manager->current_level = PERFORMANCE_REDUCED_2;\n    } else if (manager->redundancy_available == 0 && manager->faults_detected == 1) {\n        manager->current_level = PERFORMANCE_MINIMAL;\n    } else {\n        manager->current_level = PERFORMANCE_DISABLED;\n    }\n\n    \u002F\u002F Apply performance limits\n    ApplyPerformanceLimits(manager->current_level);\n\n    \u002F\u002F Notify driver\n    UpdateDriverDisplay(manager->current_level);\n}\n\nvoid ApplyPerformanceLimits(PerformanceLevel_t level) {\n    switch (level) {\n        case PERFORMANCE_FULL:\n            SetMaxTorque(100.0f);  \u002F\u002F 100% torque\n            SetMaxSpeed(200.0f);   \u002F\u002F 200 km\u002Fh\n            break;\n\n        case PERFORMANCE_REDUCED_1:\n            SetMaxTorque(80.0f);   \u002F\u002F 80% torque\n            SetMaxSpeed(160.0f);   \u002F\u002F 160 km\u002Fh\n            break;\n\n        case PERFORMANCE_REDUCED_2:\n            SetMaxTorque(50.0f);   \u002F\u002F 50% torque\n            SetMaxSpeed(100.0f);   \u002F\u002F 100 km\u002Fh\n            break;\n\n        case PERFORMANCE_MINIMAL:\n            SetMaxTorque(20.0f);   \u002F\u002F 20% torque (limp home)\n            SetMaxSpeed(50.0f);    \u002F\u002F 50 km\u002Fh\n            break;\n\n        case PERFORMANCE_DISABLED:\n            SetMaxTorque(0.0f);\n            SetMaxSpeed(0.0f);\n            EnterSafeState();\n            break;\n    }\n}\n```\n\n## Diagnostic Coverage Metrics\n\n### ASIL-D Target Coverage\n\n```c\n\u002F\u002F Diagnostic coverage calculation\ntypedef struct {\n    uint32_t total_failure_modes;\n    uint32_t detected_single_point_faults;\n    uint32_t detected_latent_faults;\n    uint32_t detected_residual_faults;\n} DiagnosticCoverage_t;\n\nfloat CalculateSPFM(DiagnosticCoverage_t *coverage) {\n    \u002F\u002F Single-Point Fault Metric\n    \u002F\u002F ASIL-D target: > 99%\n    return ((float)coverage->detected_single_point_faults \u002F\n            (float)coverage->total_failure_modes) * 100.0f;\n}\n\nfloat CalculateLFM(DiagnosticCoverage_t *coverage) {\n    \u002F\u002F Latent Fault Metric\n    \u002F\u002F ASIL-D target: > 90%\n    return ((float)coverage->detected_latent_faults \u002F\n            (float)coverage->total_failure_modes) * 100.0f;\n}\n```\n\n## Production Checklist\n\n- [ ] Redundancy pattern selected and justified\n- [ ] Diagnostic coverage calculated (SPFM > 99%, LFM > 90% for ASIL-D)\n- [ ] Watchdog configuration verified\n- [ ] CRC\u002Fchecksum implementation validated\n- [ ] Memory protection tested\n- [ ] Plausibility checks defined for all sensors\n- [ ] Safe state defined and tested\n- [ ] FTTI verified through fault injection\n- [ ] Warning lamp activation tested\n- [ ] DTC storage verified\n- [ ] Independent safety assessment completed\n\n## References\n\n- ISO 26262-5:2018 - Hardware Development\n- ISO 26262-6:2018 - Software Development\n- ISO 26262-9:2018 - ASIL-Oriented Analyses\n- IEC 61508 - Functional Safety (general industry)\n- AUTOSAR E2E Protocol Specification\n\n## Related Skills\n\n- ISO 26262 Overview\n- FMEA\u002FFTA Analysis\n- Hardware Safety Requirements\n- Software Safety Requirements\n- Safety Verification and Validation\n\n---\n\n## Safety Verification Validation\n\n# Safety Verification and Validation - ISO 26262\n\nComprehensive guidance on verification and validation per ISO 26262-4, including verification methods, validation test strategies, HIL testing, fault injection, back-to-back testing, traceability matrices, and functional safety assessment.\n\n## Verification vs Validation\n\n### Key Differences\n\n**Verification:** *\"Are we building the product right?\"*\n- Check implementation against requirements\n- Performed at each development level\n- Methods: review, analysis, test\n- Answers: Does code match specification?\n\n**Validation:** *\"Are we building the right product?\"*\n- Check product meets safety goals\n- Performed on integrated system\n- Methods: testing in target environment\n- Answers: Does system prevent hazards?\n\n```\nRequirements → [Verification] → Implementation\n      ↓\nSafety Goals → [Validation] → Final Product\n```\n\n## Verification Methods by ASIL\n\n### ISO 26262-8 Table 4 - Verification Methods\n\n| Method | ASIL A | ASIL B | ASIL C | ASIL D |\n|--------|--------|--------|--------|--------|\n| Walkthrough | + | + | ++ | ++ |\n| Inspection | + | ++ | ++ | +++ |\n| Semi-formal verification | O | + | ++ | ++ |\n| Formal verification | O | O | + | ++ |\n| Control flow analysis | + | ++ | ++ | +++ |\n| Data flow analysis | + | ++ | ++ | +++ |\n| Simulation\u002Fprototyping | ++ | ++ | +++ | +++ |\n| Requirements-based test | ++ | +++ | +++ | +++ |\n| Interface test | ++ | +++ | +++ | +++ |\n| Fault injection test | O | + | ++ | +++ |\n| Resource usage analysis | + | ++ | +++ | +++ |\n| Back-to-back comparison | O | + | ++ | +++ |\n\nLegend: +++ Highly recommended, ++ Recommended, + Optional, O Not recommended\n\n## Requirements Review\n\n### Review Checklist Template\n\n```yaml\nreview_id: \"REV-SWR-ESC-001\"\ndocument: \"Software Safety Requirements v2.5\"\nreview_type: \"Inspection\"\nasil: \"ASIL-D\"\ndate: \"2024-03-19\"\nparticipants:\n  - role: \"Moderator\"\n    name: \"J. Smith\"\n  - role: \"Safety Engineer\"\n    name: \"M. Johnson\"\n  - role: \"Software Architect\"\n    name: \"K. Williams\"\n  - role: \"Test Engineer\"\n    name: \"R. Davis\"\n\nrequirements_quality:\n  - criterion: \"Unambiguous\"\n    check: \"Each requirement has single interpretation\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Testable\"\n    check: \"Verification method defined for each requirement\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Complete\"\n    check: \"All safety goals covered by requirements\"\n    status: \"FAIL\"\n    findings:\n      - finding_id: \"F001\"\n        description: \"SG-ESC-003 (response time) not covered by SWR\"\n        severity: \"Critical\"\n        action: \"Add SWR-ESC-045 for timing requirement\"\n        responsible: \"Software Architect\"\n        due_date: \"2024-03-25\"\n\n  - criterion: \"Consistent\"\n    check: \"No conflicting requirements\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Traceable\"\n    check: \"Links to TSR and safety goals present\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Feasible\"\n    check: \"Technically achievable with available resources\"\n    status: \"PASS\"\n    findings: []\n\nverification_criteria:\n  - requirement: \"SWR-ESC-001\"\n    method: \"Requirements-based test\"\n    coverage: \"MC\u002FDC\"\n    status: \"Defined\"\n\n  - requirement: \"SWR-ESC-002\"\n    method: \"Fault injection test\"\n    coverage: \"All fault modes\"\n    status: \"Defined\"\n\nsummary:\n  total_requirements: 44\n  passed: 43\n  failed: 1\n  open_findings: 1\n  approval_status: \"CONDITIONAL (pending F001 closure)\"\n\nnext_review: \"After F001 resolved (estimated 2024-03-26)\"\n```\n\n## Static Analysis\n\n### Control Flow Analysis\n\n```c\n\u002F\u002F Example function for control flow analysis\nuint8_t ESC_CalculateControl(float yaw_rate, float lateral_accel) {\n    uint8_t control_level = 0;\n\n    \u002F\u002F Control flow graph:\n    \u002F\u002F     Entry\n    \u002F\u002F       |\n    \u002F\u002F   Check yaw_rate\n    \u002F\u002F     \u002F   \\\n    \u002F\u002F   Yes    No\n    \u002F\u002F    |      |\n    \u002F\u002F Check    Check\n    \u002F\u002F lat_acc  lat_acc\n    \u002F\u002F    |      |\n    \u002F\u002F   Set    Set\n    \u002F\u002F   level  level\n    \u002F\u002F     \\   \u002F\n    \u002F\u002F     Exit\n\n    if (yaw_rate > YAW_THRESHOLD) {\n        if (lateral_accel > ACCEL_THRESHOLD) {\n            control_level = 3;  \u002F\u002F High intervention\n        } else {\n            control_level = 2;  \u002F\u002F Medium intervention\n        }\n    } else {\n        if (lateral_accel > ACCEL_THRESHOLD) {\n            control_level = 1;  \u002F\u002F Low intervention\n        } else {\n            control_level = 0;  \u002F\u002F No intervention\n        }\n    }\n\n    return control_level;  \u002F\u002F Single exit point (MISRA compliant)\n}\n\n\u002F\u002F Static analysis checks:\n\u002F\u002F ✓ No unreachable code\n\u002F\u002F ✓ Single entry, single exit\n\u002F\u002F ✓ All paths return a value\n\u002F\u002F ✓ Cyclomatic complexity: 3 (acceptable for ASIL-D)\n\u002F\u002F ✓ No recursion\n```\n\n### Data Flow Analysis\n\n```c\n\u002F\u002F Data flow analysis example\ntypedef struct {\n    float wheel_speed_fl;      \u002F\u002F Defined at line 5\n    float wheel_speed_fr;      \u002F\u002F Defined at line 6\n    bool valid_fl;             \u002F\u002F Defined at line 7\n    bool valid_fr;             \u002F\u002F Defined at line 8\n} SensorData_t;\n\nvoid ESC_ProcessSensors(SensorData_t *data) {\n    float average_speed;  \u002F\u002F Declared at line 12\n\n    \u002F\u002F Read sensors (define values)\n    data->wheel_speed_fl = ReadSensor(SENSOR_FL);  \u002F\u002F Line 15: Define wheel_speed_fl\n    data->wheel_speed_fr = ReadSensor(SENSOR_FR);  \u002F\u002F Line 16: Define wheel_speed_fr\n\n    \u002F\u002F Validate sensors (define valid flags)\n    data->valid_fl = ValidateSensor(data->wheel_speed_fl);  \u002F\u002F Line 19: Use wheel_speed_fl\n    data->valid_fr = ValidateSensor(data->wheel_speed_fr);  \u002F\u002F Line 20: Use wheel_speed_fr\n\n    \u002F\u002F Calculate average (use values)\n    if (data->valid_fl && data->valid_fr) {  \u002F\u002F Line 23: Use valid_fl, valid_fr\n        average_speed = (data->wheel_speed_fl + data->wheel_speed_fr) \u002F 2.0f;\n        \u002F\u002F Line 24: Use wheel_speed_fl, wheel_speed_fr, Define average_speed\n    }\n\n    \u002F\u002F Use average (line 28: Use average_speed)\n    if (data->valid_fl && data->valid_fr) {  \u002F\u002F Condition ensures average_speed is defined\n        UseAverageSpeed(average_speed);\n    }\n}\n\n\u002F\u002F Data flow analysis results:\n\u002F\u002F ✓ No use before definition (all variables initialized before use)\n\u002F\u002F ✓ No unused variables\n\u002F\u002F ✓ No redundant assignments\n\u002F\u002F ✓ Proper initialization of average_speed before use\n```\n\n## Requirements-Based Testing\n\n### Test Case Template\n\n```yaml\ntest_case_id: \"TC-SWR-ESC-001-001\"\nrequirement: \"SWR-ESC-001.1\"\nrequirement_text: \"Software SHALL reject wheel speed \u003C 0 km\u002Fh\"\ntest_type: \"Unit Test\"\nasil: \"ASIL-D\"\ntest_level: \"Software Unit Testing\"\n\npreconditions:\n  - ESC module initialized\n  - Wheel speed sensor interface configured\n  - No prior faults\n\ntest_inputs:\n  - name: \"wheel_speed_fl\"\n    value: -10.0\n    unit: \"km\u002Fh\"\n  - name: \"sensor_status\"\n    value: \"VALID\"\n\nexpected_outputs:\n  - name: \"validation_result\"\n    value: false\n    description: \"Validation should fail for negative speed\"\n  - name: \"fault_flag\"\n    value: true\n    description: \"Fault flag should be set\"\n  - name: \"dtc_code\"\n    value: \"DTC_WHEEL_SPEED_INVALID\"\n\ntest_procedure:\n  - step: 1\n    action: \"Call ESC_ValidateWheelSpeed(-10.0)\"\n    expected: \"Function returns false\"\n  - step: 2\n    action: \"Check fault flag\"\n    expected: \"Fault flag is set\"\n  - step: 3\n    action: \"Read DTC buffer\"\n    expected: \"DTC_WHEEL_SPEED_INVALID present\"\n\npass_criteria:\n  - All expected outputs match actual outputs\n  - No unexpected side effects\n  - Function executes within timing budget (\u003C 50 μs)\n\nexecution:\n  date: \"2024-03-19\"\n  tester: \"R. Davis\"\n  environment: \"Unit test framework (Unity)\"\n  result: \"PASS\"\n  actual_outputs:\n    validation_result: false\n    fault_flag: true\n    dtc_code: \"DTC_WHEEL_SPEED_INVALID\"\n  execution_time_us: 12\n  notes: \"Test passed on first attempt\"\n\ncoverage:\n  line_coverage: 100%\n  branch_coverage: 100%\n  mcdc_coverage: 100%\n```\n\n## Fault Injection Testing\n\n### Hardware Fault Injection\n\n```c\n\u002F\u002F Fault injection framework\ntypedef enum {\n    FAULT_NONE,\n    FAULT_SENSOR_STUCK_HIGH,\n    FAULT_SENSOR_STUCK_LOW,\n    FAULT_SENSOR_NOISE,\n    FAULT_SENSOR_DROPOUT,\n    FAULT_BIT_FLIP,\n    FAULT_TIMING_VIOLATION\n} FaultType_t;\n\ntypedef struct {\n    FaultType_t fault_type;\n    uint32_t injection_time_ms;\n    uint32_t duration_ms;\n    void *target_address;\n    uint32_t fault_mask;\n} FaultInjectionConfig_t;\n\n\u002F\u002F Inject sensor stuck-high fault\nvoid InjectFault_SensorStuckHigh(void) {\n    FaultInjectionConfig_t config = {\n        .fault_type = FAULT_SENSOR_STUCK_HIGH,\n        .injection_time_ms = 1000,  \u002F\u002F Inject after 1 second\n        .duration_ms = 500,          \u002F\u002F Fault persists for 500ms\n        .target_address = &wheel_speed_fl_raw,\n        .fault_mask = 0xFFFFFFFF     \u002F\u002F Maximum value\n    };\n\n    \u002F\u002F Configure fault injection hardware (e.g., FPGA, fault injection tool)\n    ConfigureFaultInjection(&config);\n}\n\n\u002F\u002F Test: Verify safe state transition on persistent sensor fault\nvoid Test_SafeState_PersistentSensorFault(void) {\n    \u002F\u002F 1. Initialize system\n    ESC_Init();\n    assert(ESC_GetMode() == ESC_MODE_NORMAL);\n\n    \u002F\u002F 2. Inject stuck-high fault on wheel speed sensor\n    InjectFault_SensorStuckHigh();\n\n    \u002F\u002F 3. Run for fault duration\n    for (uint32_t t = 0; t \u003C 600; t += 10) {  \u002F\u002F 600ms\n        ESC_MainFunction();  \u002F\u002F 10ms periodic task\n        Delay_ms(10);\n    }\n\n    \u002F\u002F 4. Verify safe state entered\n    assert(ESC_GetMode() == ESC_MODE_SAFE_STATE);\n\n    \u002F\u002F 5. Verify warning lamp activated\n    assert(GetWarningLampStatus() == WARNING_LAMP_ON);\n\n    \u002F\u002F 6. Verify DTC stored\n    assert(IsDTCStored(DTC_WHEEL_SPEED_FAULT));\n\n    \u002F\u002F 7. Verify transition time within FTTI\n    uint32_t transition_time = GetSafeStateTransitionTime_ms();\n    assert(transition_time \u003C= 150);  \u002F\u002F FTTI requirement\n\n    printf(\"✓ Safe state test PASS (transition time: %u ms)\\n\", transition_time);\n}\n```\n\n### Software Fault Injection (Mutation Testing)\n\n```python\n# Mutation testing for safety mechanisms\nimport subprocess\nimport re\n\nclass MutationTester:\n    def __init__(self, source_file, test_executable):\n        self.source_file = source_file\n        self.test_executable = test_executable\n        self.mutations = []\n\n    def generate_mutations(self):\n        \"\"\"Generate mutations of source code\"\"\"\n        with open(self.source_file, 'r') as f:\n            original_code = f.read()\n\n        # Mutation 1: Change comparison operators\n        mutations = [\n            (r'>', '>='),    # > to >=\n            (r'\u003C', '\u003C='),    # \u003C to \u003C=\n            (r'==', '!='),   # == to !=\n            (r'&&', '||'),   # && to ||\n        ]\n\n        for i, (pattern, replacement) in enumerate(mutations):\n            mutated_code = re.sub(pattern, replacement, original_code, count=1)\n            self.mutations.append({\n                'id': f'MUT-{i+1}',\n                'description': f'Change {pattern} to {replacement}',\n                'code': mutated_code\n            })\n\n    def run_mutation_test(self, mutation):\n        \"\"\"Run tests against mutated code\"\"\"\n        # Write mutated code to file\n        with open(self.source_file, 'w') as f:\n            f.write(mutation['code'])\n\n        # Recompile\n        compile_result = subprocess.run(['make', 'clean', 'all'],\n                                       capture_output=True)\n\n        # Run tests\n        test_result = subprocess.run([self.test_executable],\n                                     capture_output=True)\n\n        # Mutation killed if tests fail\n        killed = (test_result.returncode != 0)\n\n        return killed\n\n    def analyze_coverage(self):\n        \"\"\"Analyze mutation test coverage\"\"\"\n        total = len(self.mutations)\n        killed = sum(1 for m in self.mutations if self.run_mutation_test(m))\n\n        mutation_score = (killed \u002F total) * 100\n        print(f\"Mutation Score: {mutation_score:.1f}%\")\n        print(f\"Mutations Killed: {killed}\u002F{total}\")\n\n        # ASIL-D target: > 95% mutation score\n        if mutation_score > 95:\n            print(\"✓ Mutation testing PASS\")\n        else:\n            print(\"✗ Mutation testing FAIL (target: > 95%)\")\n\n        return mutation_score\n\n# Example usage\ntester = MutationTester('esc_safety.c', '.\u002Ftest_esc')\ntester.generate_mutations()\ntester.analyze_coverage()\n```\n\n## HIL (Hardware-in-Loop) Testing\n\n### HIL Test Setup\n\n```\n┌─────────────────────────────────────────────────────────┐\n│                   HIL Test System                       │\n│                                                         │\n│  ┌──────────────┐         ┌──────────────┐            │\n│  │   Real-Time  │         │  Vehicle     │            │\n│  │   Simulator  │◄───────►│  Dynamics    │            │\n│  │   (dSPACE)   │         │  Model       │            │\n│  └──────┬───────┘         └──────────────┘            │\n│         │                                              │\n│         │ CAN\u002FLIN\u002FEthernet                             │\n│         │                                              │\n│  ┌──────▼───────┐         ┌──────────────┐            │\n│  │   ESC ECU    │◄───────►│  Fault       │            │\n│  │   (Real HW)  │         │  Injection   │            │\n│  └──────┬───────┘         └──────────────┘            │\n│         │                                              │\n│         │ Actuator Outputs                             │\n│         │                                              │\n│  ┌──────▼───────┐         ┌──────────────┐            │\n│  │   Brake      │         │  Test        │            │\n│  │   Simulator  │◄───────►│  Automation  │            │\n│  └──────────────┘         └──────────────┘            │\n└─────────────────────────────────────────────────────────┘\n```\n\n### HIL Test Script (Python + dSPACE)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nHIL Test: ESC Safety Goal Verification\nTest: SG-ESC-001 - Prevent unintended ESC activation\n\"\"\"\n\nimport dspace\nimport time\nimport numpy as np\n\nclass HILTest_ESC:\n    def __init__(self):\n        self.ds = dspace.HILSystem('10.0.0.100')  # dSPACE IP\n        self.test_results = []\n\n    def setup(self):\n        \"\"\"Initialize HIL system\"\"\"\n        # Load vehicle dynamics model\n        self.ds.load_model('vehicle_dynamics_sedan_2024.sdf')\n\n        # Configure CAN interface\n        self.ds.configure_can(channel=1, baudrate=500000)\n\n        # Reset ECU\n        self.ds.reset_ecu()\n        time.sleep(1)\n\n        # Set initial conditions\n        self.ds.set_variable('VehicleSpeed', 100.0)  # km\u002Fh\n        self.ds.set_variable('RoadFriction', 0.8)    # Dry road\n        self.ds.set_variable('SteeringAngle', 0.0)   # Straight\n\n    def test_no_intervention_straight_driving(self):\n        \"\"\"Verify ESC does not activate during normal straight driving\"\"\"\n        print(\"Test: No intervention during straight driving...\")\n\n        # Run simulation for 30 seconds\n        self.ds.start_simulation()\n\n        for t in np.arange(0, 30, 0.01):  # 10ms steps\n            # Maintain steady state\n            self.ds.set_variable('SteeringAngle', 0.0)\n            self.ds.set_variable('VehicleSpeed', 100.0)\n\n            # Read ESC status\n            esc_active = self.ds.get_can_signal('ESC_Status', 'ESC_Active')\n\n            # Verify ESC not active\n            if esc_active:\n                print(f\"✗ FAIL: Unintended ESC activation at t={t:.2f}s\")\n                self.test_results.append({\n                    'test': 'No_Intervention_Straight',\n                    'result': 'FAIL',\n                    'time': t\n                })\n                self.ds.stop_simulation()\n                return False\n\n            time.sleep(0.01)\n\n        self.ds.stop_simulation()\n        print(\"✓ PASS: No unintended activation\")\n        self.test_results.append({\n            'test': 'No_Intervention_Straight',\n            'result': 'PASS'\n        })\n        return True\n\n    def test_intervention_oversteer(self):\n        \"\"\"Verify ESC activates during oversteer condition\"\"\"\n        print(\"Test: ESC activation during oversteer...\")\n\n        self.ds.start_simulation()\n\n        # Create oversteer condition\n        self.ds.set_variable('VehicleSpeed', 100.0)\n        self.ds.set_variable('RoadFriction', 0.3)  # Wet road\n\n        # Sudden steering input\n        for t in np.arange(0, 2, 0.01):\n            self.ds.set_variable('SteeringAngle', 45.0)  # Sharp turn\n\n            # Monitor vehicle dynamics\n            yaw_rate = self.ds.get_variable('YawRate')\n            lateral_accel = self.ds.get_variable('LateralAccel')\n            esc_active = self.ds.get_can_signal('ESC_Status', 'ESC_Active')\n\n            # Check if ESC activates\n            if yaw_rate > 15.0 and not esc_active:\n                # Vehicle is oversteering but ESC not active\n                if t > 0.15:  # Allow for FTTI (150ms)\n                    print(f\"✗ FAIL: ESC did not activate (t={t:.2f}s, yaw={yaw_rate:.1f}°\u002Fs)\")\n                    self.test_results.append({\n                        'test': 'Intervention_Oversteer',\n                        'result': 'FAIL',\n                        'reason': 'No activation during oversteer'\n                    })\n                    self.ds.stop_simulation()\n                    return False\n\n            if esc_active:\n                print(f\"✓ PASS: ESC activated at t={t:.2f}s\")\n                self.test_results.append({\n                    'test': 'Intervention_Oversteer',\n                    'result': 'PASS',\n                    'activation_time': t\n                })\n                self.ds.stop_simulation()\n                return True\n\n            time.sleep(0.01)\n\n        print(\"✗ FAIL: ESC never activated\")\n        self.test_results.append({\n            'test': 'Intervention_Oversteer',\n            'result': 'FAIL',\n            'reason': 'No activation'\n        })\n        self.ds.stop_simulation()\n        return False\n\n    def test_safe_state_sensor_fault(self):\n        \"\"\"Verify safe state transition on sensor fault\"\"\"\n        print(\"Test: Safe state on sensor fault...\")\n\n        self.ds.start_simulation()\n\n        # Inject sensor fault\n        self.ds.inject_fault('WheelSpeed_FL', fault_type='stuck_high')\n\n        start_time = time.time()\n        safe_state_entered = False\n\n        for t in np.arange(0, 1, 0.01):\n            # Read ECU status\n            operating_mode = self.ds.get_can_signal('ESC_Status', 'OperatingMode')\n\n            if operating_mode == 3:  # Safe state\n                transition_time = (time.time() - start_time) * 1000  # ms\n                print(f\"✓ PASS: Safe state entered in {transition_time:.1f}ms\")\n\n                # Verify FTTI requirement\n                if transition_time \u003C= 150:\n                    print(f\"✓ PASS: FTTI requirement met ({transition_time:.1f}ms \u003C= 150ms)\")\n                    self.test_results.append({\n                        'test': 'Safe_State_Sensor_Fault',\n                        'result': 'PASS',\n                        'ftti_ms': transition_time\n                    })\n                else:\n                    print(f\"✗ FAIL: FTTI exceeded ({transition_time:.1f}ms > 150ms)\")\n                    self.test_results.append({\n                        'test': 'Safe_State_Sensor_Fault',\n                        'result': 'FAIL',\n                        'reason': 'FTTI exceeded'\n                    })\n\n                safe_state_entered = True\n                break\n\n            time.sleep(0.01)\n\n        self.ds.stop_simulation()\n        self.ds.clear_faults()\n\n        if not safe_state_entered:\n            print(\"✗ FAIL: Safe state not entered\")\n            self.test_results.append({\n                'test': 'Safe_State_Sensor_Fault',\n                'result': 'FAIL',\n                'reason': 'No safe state transition'\n            })\n            return False\n\n        return True\n\n    def generate_report(self):\n        \"\"\"Generate test report\"\"\"\n        print(\"\\n\" + \"=\"*60)\n        print(\"HIL Test Report - ESC Safety Verification\")\n        print(\"=\"*60)\n\n        total = len(self.test_results)\n        passed = sum(1 for r in self.test_results if r['result'] == 'PASS')\n\n        print(f\"\\nTotal Tests: {total}\")\n        print(f\"Passed: {passed}\")\n        print(f\"Failed: {total - passed}\")\n        print(f\"Pass Rate: {(passed\u002Ftotal)*100:.1f}%\\n\")\n\n        for result in self.test_results:\n            status = \"✓\" if result['result'] == 'PASS' else \"✗\"\n            print(f\"{status} {result['test']}: {result['result']}\")\n\n        return passed == total\n\n    def run_all_tests(self):\n        \"\"\"Execute all HIL tests\"\"\"\n        self.setup()\n\n        tests = [\n            self.test_no_intervention_straight_driving,\n            self.test_intervention_oversteer,\n            self.test_safe_state_sensor_fault\n        ]\n\n        for test in tests:\n            test()\n            time.sleep(2)  # Delay between tests\n\n        return self.generate_report()\n\n\nif __name__ == \"__main__\":\n    hil_test = HILTest_ESC()\n    all_passed = hil_test.run_all_tests()\n\n    if all_passed:\n        print(\"\\n✓ All HIL tests PASSED\")\n        exit(0)\n    else:\n        print(\"\\n✗ Some HIL tests FAILED\")\n        exit(1)\n```\n\n## Back-to-Back Testing\n\n### Model-Code Comparison\n\n```matlab\n% MATLAB\u002FSimulink reference model\n% ESC_ReferenceModel.m\n\nfunction [control_level] = ESC_ReferenceModel(yaw_rate, lateral_accel)\n    % Reference implementation in MATLAB\n    YAW_THRESHOLD = 15.0;      % deg\u002Fs\n    ACCEL_THRESHOLD = 0.4;     % g\n\n    if yaw_rate > YAW_THRESHOLD\n        if lateral_accel > ACCEL_THRESHOLD\n            control_level = 3;\n        else\n            control_level = 2;\n        end\n    else\n        if lateral_accel > ACCEL_THRESHOLD\n            control_level = 1;\n        else\n            control_level = 0;\n        end\n    end\nend\n\n% Back-to-back test vectors\ntest_vectors = [\n    % yaw_rate, lateral_accel, expected_output\n    0.0, 0.0, 0;     % No intervention\n    20.0, 0.2, 2;    % High yaw, low accel\n    10.0, 0.5, 1;    % Low yaw, high accel\n    20.0, 0.5, 3;    % High yaw, high accel\n    15.0, 0.4, 2;    % Boundary values\n];\n\n% Run reference model\nfprintf('Back-to-Back Test Results:\\n');\nfprintf('%-10s %-15s %-10s %-10s %-10s\\n', 'Test', 'Inputs', 'Model', 'Code', 'Status');\n\nfor i = 1:size(test_vectors, 1)\n    yaw = test_vectors(i, 1);\n    accel = test_vectors(i, 2);\n    expected = test_vectors(i, 3);\n\n    % Run MATLAB model\n    model_output = ESC_ReferenceModel(yaw, accel);\n\n    % Run C code (via MEX or external call)\n    code_output = ESC_CalculateControl_C(yaw, accel);\n\n    % Compare outputs\n    if model_output == code_output && model_output == expected\n        status = 'PASS';\n    else\n        status = 'FAIL';\n    end\n\n    fprintf('TC-%d     (%.1f, %.1f)    %d          %d         %s\\n', ...\n            i, yaw, accel, model_output, code_output, status);\nend\n```\n\n## Traceability Matrix\n\n### Requirements Traceability\n\n```sql\n-- Traceability database schema\nCREATE TABLE SafetyGoals (\n    sg_id VARCHAR(50) PRIMARY KEY,\n    description TEXT,\n    asil VARCHAR(10),\n    ftti_ms INT\n);\n\nCREATE TABLE FunctionalSafetyRequirements (\n    fsr_id VARCHAR(50) PRIMARY KEY,\n    sg_id VARCHAR(50) REFERENCES SafetyGoals(sg_id),\n    description TEXT\n);\n\nCREATE TABLE TechnicalSafetyRequirements (\n    tsr_id VARCHAR(50) PRIMARY KEY,\n    fsr_id VARCHAR(50) REFERENCES FunctionalSafetyRequirements(fsr_id),\n    description TEXT\n);\n\nCREATE TABLE SoftwareSafetyRequirements (\n    swr_id VARCHAR(50) PRIMARY KEY,\n    tsr_id VARCHAR(50) REFERENCES TechnicalSafetyRequirements(tsr_id),\n    description TEXT,\n    verification_method VARCHAR(100)\n);\n\nCREATE TABLE TestCases (\n    tc_id VARCHAR(50) PRIMARY KEY,\n    swr_id VARCHAR(50) REFERENCES SoftwareSafetyRequirements(swr_id),\n    test_type VARCHAR(50),\n    status VARCHAR(20),\n    result VARCHAR(20)\n);\n\n-- Query: Generate traceability matrix\nSELECT\n    sg.sg_id,\n    sg.description AS safety_goal,\n    fsr.fsr_id,\n    tsr.tsr_id,\n    swr.swr_id,\n    tc.tc_id,\n    tc.result\nFROM SafetyGoals sg\nLEFT JOIN FunctionalSafetyRequirements fsr ON sg.sg_id = fsr.sg_id\nLEFT JOIN TechnicalSafetyRequirements tsr ON fsr.fsr_id = tsr.fsr_id\nLEFT JOIN SoftwareSafetyRequirements swr ON tsr.tsr_id = swr.tsr_id\nLEFT JOIN TestCases tc ON swr.swr_id = tc.swr_id\nWHERE sg.sg_id = 'SG-ESC-001'\nORDER BY sg.sg_id, fsr.fsr_id, tsr.tsr_id, swr.swr_id;\n```\n\n## Functional Safety Assessment\n\n### Assessment Checklist\n\n```yaml\nassessment_id: \"FSA-ESC-ECU-001\"\nitem: \"ESC Electronic Control Unit\"\nasil: \"ASIL-D\"\nassessment_type: \"Independent Safety Assessment\"\nassessor: \"TÜV SÜD\"\ndate: \"2024-03-19\"\n\npart_2_management:\n  - criterion: \"Safety lifecycle defined\"\n    status: \"COMPLIANT\"\n    evidence: \"SAF-001: Safety Plan v1.5\"\n\n  - criterion: \"Safety manager appointed\"\n    status: \"COMPLIANT\"\n    evidence: \"Org chart, training records\"\n\n  - criterion: \"Safety culture established\"\n    status: \"COMPLIANT\"\n    evidence: \"Safety culture assessment report\"\n\npart_3_concept:\n  - criterion: \"Item definition complete\"\n    status: \"COMPLIANT\"\n    evidence: \"ITEM-ESC-001: Item Definition v2.0\"\n\n  - criterion: \"HARA performed\"\n    status: \"COMPLIANT\"\n    evidence: \"HARA-ESC-001: 15 hazardous events analyzed\"\n\n  - criterion: \"Safety goals defined\"\n    status: \"COMPLIANT\"\n    evidence: \"3 safety goals (ASIL-D, C, B)\"\n\npart_4_system:\n  - criterion: \"Technical safety concept\"\n    status: \"COMPLIANT\"\n    evidence: \"TSC-ESC-001: TSC v1.8\"\n\n  - criterion: \"System architecture\"\n    status: \"COMPLIANT\"\n    evidence: \"ARCH-ESC-001: Architecture spec\"\n\n  - criterion: \"Safety analysis (FMEA)\"\n    status: \"COMPLIANT\"\n    evidence: \"FMEA-ESC-HW-001, FMEA-ESC-SW-001\"\n\npart_5_hardware:\n  - criterion: \"Hardware safety requirements\"\n    status: \"COMPLIANT\"\n    evidence: \"HSR-ESC-001: 25 requirements\"\n\n  - criterion: \"SPFM\u002FLFM\u002FPMHF calculated\"\n    status: \"COMPLIANT\"\n    evidence: \"FMEDA-ESC-001: SPFM=99.2%, LFM=92.5%, PMHF=8.5 FIT\"\n\n  - criterion: \"Hardware metrics meet targets\"\n    status: \"COMPLIANT\"\n    evidence: \"All metrics within ASIL-D targets\"\n\npart_6_software:\n  - criterion: \"Software safety requirements\"\n    status: \"COMPLIANT\"\n    evidence: \"SWR-ESC-001: 44 requirements\"\n\n  - criterion: \"MISRA compliance\"\n    status: \"COMPLIANT\"\n    evidence: \"Static analysis: 0 violations\"\n\n  - criterion: \"Unit test MC\u002FDC coverage\"\n    status: \"COMPLIANT\"\n    evidence: \"Coverage report: 100% MC\u002FDC\"\n\n  - criterion: \"Software safety manual\"\n    status: \"COMPLIANT\"\n    evidence: \"SSM-ESC-001: SW Safety Manual v1.0\"\n\npart_8_supporting:\n  - criterion: \"Configuration management\"\n    status: \"COMPLIANT\"\n    evidence: \"Git repository, version control procedures\"\n\n  - criterion: \"Tool qualification\"\n    status: \"COMPLIANT\"\n    evidence: \"Compiler (GCC-ARM), Static analyzer (PC-Lint) qualified\"\n\n  - criterion: \"Documentation\"\n    status: \"COMPLIANT\"\n    evidence: \"All work products present and reviewed\"\n\nverification_validation:\n  - criterion: \"Verification plan executed\"\n    status: \"COMPLIANT\"\n    evidence: \"VER-PLAN-ESC-001: All activities complete\"\n\n  - criterion: \"Validation testing performed\"\n    status: \"COMPLIANT\"\n    evidence: \"VAL-REPORT-ESC-001: HIL testing 1000 hours\"\n\n  - criterion: \"Safety goals validated\"\n    status: \"COMPLIANT\"\n    evidence: \"All 3 safety goals verified in target environment\"\n\nfindings:\n  - finding_id: \"FSA-001\"\n    category: \"Observation\"\n    description: \"Traceability links between TSR and SWR could be improved\"\n    severity: \"Minor\"\n    recommendation: \"Add automated traceability tool\"\n    status: \"Open\"\n\n  - finding_id: \"FSA-002\"\n    category: \"Observation\"\n    description: \"Field monitoring process not fully defined\"\n    severity: \"Minor\"\n    recommendation: \"Document field data collection procedures\"\n    status: \"Open\"\n\nconclusion:\n  overall_assessment: \"POSITIVE\"\n  recommendation: \"Release for production\"\n  conditions:\n    - \"Address findings FSA-001 and FSA-002 before SOP\"\n    - \"Maintain configuration management during production\"\n  next_assessment: \"After 1 year of production (field monitoring review)\"\n```\n\n## Production Checklist\n\n### Verification & Validation Sign-Off\n\n- [ ] Requirements reviews completed (all levels)\n- [ ] Design reviews completed (all levels)\n- [ ] Static analysis performed (0 critical violations)\n- [ ] Unit testing completed (100% MC\u002FDC for ASIL-D)\n- [ ] Integration testing completed (all interfaces)\n- [ ] System testing completed (all requirements)\n- [ ] HIL testing completed (> 1000 hours for ASIL-D)\n- [ ] Fault injection testing completed\n- [ ] Back-to-back testing completed (model vs code)\n- [ ] Traceability matrix complete (SG → TC)\n- [ ] Safety analysis verified (FMEA\u002FFTA)\n- [ ] Hardware metrics verified (SPFM\u002FLFM\u002FPMHF)\n- [ ] Safety manual reviewed and approved\n- [ ] Independent safety assessment passed\n- [ ] Release for production authorized\n\n## References\n\n- ISO 26262-4:2018 - Product Development at System Level\n- ISO 26262-8:2018 - Supporting Processes (Verification)\n- ISO 26262-11:2018 - Semiconductors (Validation)\n- dSPACE HIL Testing Guide\n- AUTOSAR Methodology\n- Mutation Testing Handbook\n\n## Related Skills\n\n- ISO 26262 Overview\n- FMEA\u002FFTA Analysis\n- Software Safety Requirements\n- Safety Mechanisms and Patterns\n- Hardware Safety Requirements\n\n---\n\n## Software Safety Requirements\n\n# Software Safety Requirements - ISO 26262 Part 6\n\nComprehensive guidance on ASIL-D software development per ISO 26262-6, including safety requirements specification, architectural design, unit implementation, MISRA C\u002FC++ compliance, MC\u002FDC testing, and software safety manual creation.\n\n## Software Development V-Model\n\n```\n┌────────────────────────────────────────────────────────────┐\n│         Software Safety Requirements (Part 6-6)            │\n│  • Derived from Technical Safety Concept                   │\n│  • ASIL classification                                     │\n│  • Verification criteria                                   │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Architectural Design (Part 6-7)           │\n│  • Hierarchical structure                                  │\n│  • Component interfaces                                    │\n│  • Resource constraints                                    │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Unit Design (Part 6-8)                    │\n│  • Detailed design per unit                                │\n│  • Algorithms and data structures                          │\n│  • Static analysis                                         │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Unit Implementation (Part 6-9)            │\n│  • Coding per MISRA guidelines                             │\n│  • Code reviews                                            │\n│  • Static analysis                                         │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Unit Testing (Part 6-10)                  │\n│  • MC\u002FDC coverage (ASIL-D)                                 │\n│  • Requirements-based tests                                │\n│  • Back-to-back testing                                    │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Integration Testing (Part 6-11)           │\n│  • Interface testing                                       │\n│  • Resource usage verification                             │\n│  • Fault injection                                         │\n└────────────────────────────────────────────────────────────┘\n```\n\n## Software Safety Requirements\n\n### Requirement Structure\n\n**Good Safety Requirement (SMART):**\n- **Specific**: Unambiguous, single interpretation\n- **Measurable**: Testable\u002Fverifiable\n- **Achievable**: Technically feasible\n- **Relevant**: Traceable to safety goal\n- **Time-bound**: Response time specified\n\n**Example Requirements:**\n\n```yaml\nswr_id: \"SWR-ESC-001\"\ntitle: \"Wheel Speed Sensor Range Check\"\nderived_from: \"TSR-ESC-001\"  # Technical Safety Requirement\nasil: \"ASIL-D\"\nsafety_goal: \"SG-ESC-001 (Prevent unintended ESC activation)\"\n\ndescription: |\n  The software shall validate that each wheel speed sensor value is within\n  the physically possible range before using it in vehicle dynamics calculations.\n\nprecondition: \"Wheel speed sensor data received via CAN\"\n\nrequirements:\n  - id: \"SWR-ESC-001.1\"\n    text: \"The software SHALL reject wheel speed values \u003C 0 km\u002Fh\"\n    rationale: \"Negative speed is physically impossible\"\n    verification: \"Unit test with negative input\"\n\n  - id: \"SWR-ESC-001.2\"\n    text: \"The software SHALL reject wheel speed values > 350 km\u002Fh\"\n    rationale: \"Exceeds maximum vehicle speed by 50% margin\"\n    verification: \"Unit test with excessive input\"\n\n  - id: \"SWR-ESC-001.3\"\n    text: \"The software SHALL set a fault flag if invalid speed detected\"\n    rationale: \"Enable diagnostic monitoring\"\n    verification: \"Verify flag state after invalid input\"\n\n  - id: \"SWR-ESC-001.4\"\n    text: \"The software SHALL use last valid speed value if current invalid\"\n    rationale: \"Maintain functionality while rejecting invalid data\"\n    verification: \"Integration test with fault injection\"\n\n  - id: \"SWR-ESC-001.5\"\n    text: \"The software SHALL transition to safe state if > 3 consecutive invalid readings\"\n    rationale: \"Persistent fault indicates sensor failure\"\n    verification: \"System test with sustained fault\"\n\ntiming:\n  execution_time_max_us: 50\n  deadline_ms: 10\n  period_ms: 10\n\nsafety_mechanism: \"SM-ESC-004 (Range Check)\"\ninterfaces:\n  input: \"CAN message ESC_WheelSpeeds (ID 0x200)\"\n  output: \"Internal variable wheel_speed_fl_valid\"\n\nverification_methods:\n  - Requirements-based test\n  - Boundary value analysis\n  - Fault injection test\n  - MC\u002FDC coverage\n\nacceptance_criteria:\n  - All requirements verified with tests\n  - MC\u002FDC coverage >= 100%\n  - Static analysis: 0 violations\n  - Code review: approved\n```\n\n### Requirements Traceability\n\n```\nSafety Goal (SG)\n    │\n    ├─> Functional Safety Requirement (FSR)\n    │       │\n    │       ├─> Technical Safety Requirement (TSR)\n    │       │       │\n    │       │       ├─> Software Safety Requirement (SWR)\n    │       │       │       │\n    │       │       │       ├─> Software Unit (SW-U)\n    │       │       │       │       │\n    │       │       │       │       └─> Unit Test Case (UTC)\n    │       │       │       │\n    │       │       │       └─> Integration Test Case (ITC)\n    │       │       │\n    │       │       └─> System Test Case (STC)\n    │       │\n    │       └─> Validation Test Case (VTC)\n```\n\n## Software Architecture\n\n### ASIL-D Architecture Patterns\n\n**1. Freedom from Interference**\n\n```c\n\u002F\u002F Memory partitioning for ASIL-D\ntypedef struct {\n    \u002F\u002F ASIL-D partition (protected)\n    uint8_t safety_data[1024] __attribute__((section(\".safety_ram\")));\n\n    \u002F\u002F QM partition (separate)\n    uint8_t qm_data[4096] __attribute__((section(\".qm_ram\")));\n} MemoryPartitions_t;\n\n\u002F\u002F MPU configuration (ARM Cortex-M)\nvoid ConfigureMemoryProtection(void) {\n    \u002F\u002F Region 0: Safety-critical code (read-only, execute)\n    MPU->RBAR = SAFETY_CODE_BASE | MPU_REGION_VALID | 0;\n    MPU->RASR = MPU_RASR_ENABLE | MPU_RASR_XN_DISABLE |\n                MPU_RASR_AP_RO | MPU_SIZE_64KB;\n\n    \u002F\u002F Region 1: Safety-critical data (read-write, no execute)\n    MPU->RBAR = SAFETY_DATA_BASE | MPU_REGION_VALID | 1;\n    MPU->RASR = MPU_RASR_ENABLE | MPU_RASR_XN_ENABLE |\n                MPU_RASR_AP_RW | MPU_SIZE_16KB;\n\n    \u002F\u002F Region 2: QM code (separate partition)\n    MPU->RBAR = QM_CODE_BASE | MPU_REGION_VALID | 2;\n    MPU->RASR = MPU_RASR_ENABLE | MPU_RASR_XN_DISABLE |\n                MPU_RASR_AP_RO | MPU_SIZE_128KB;\n\n    \u002F\u002F Enable MPU\n    MPU->CTRL = MPU_CTRL_ENABLE | MPU_CTRL_PRIVDEFENA;\n}\n```\n\n**2. Timing and Scheduling**\n\n```c\n\u002F\u002F ASIL-D task configuration (AUTOSAR OS)\nTASK(SafetyCriticalTask) {\n    const uint32_t WCET_US = 500;  \u002F\u002F Worst-Case Execution Time\n    const uint32_t DEADLINE_MS = 10;\n\n    uint32_t start_time = GetTimestamp_us();\n\n    \u002F\u002F Execute safety-critical function\n    ESC_SafetyFunction();\n\n    uint32_t execution_time = GetTimestamp_us() - start_time;\n\n    \u002F\u002F Verify timing constraints\n    if (execution_time > WCET_US) {\n        SetDTC(DTC_TIMING_VIOLATION);\n        EnterSafeState();\n    }\n\n    TerminateTask();\n}\n\n\u002F\u002F Task scheduling configuration\nconst TaskConfigType SafetyCriticalTaskConfig = {\n    .priority = 255,  \u002F\u002F Highest priority\n    .activation = PERIODIC,\n    .period_ms = 10,\n    .deadline_ms = 10,\n    .stack_size = 2048,\n    .partition = SAFETY_PARTITION\n};\n```\n\n**3. Software Component Structure**\n\n```c\n\u002F\u002F Software component interface (AUTOSAR SWC)\ntypedef struct {\n    \u002F\u002F Inputs (ports)\n    float wheel_speed_fl;\n    float wheel_speed_fr;\n    float wheel_speed_rl;\n    float wheel_speed_rr;\n    float yaw_rate;\n    float lateral_accel;\n\n    \u002F\u002F Outputs (ports)\n    float brake_pressure_fl;\n    float brake_pressure_fr;\n    float brake_pressure_rl;\n    float brake_pressure_rr;\n    bool esc_active;\n\n    \u002F\u002F Mode management\n    ESC_ModeType operating_mode;\n\n    \u002F\u002F Fault status\n    uint32_t fault_flags;\n} ESC_Component_t;\n\n\u002F\u002F Runnable function\nvoid ESC_MainFunction(void) {\n    ESC_Component_t *component = GetESCComponent();\n\n    \u002F\u002F 1. Input validation\n    if (!ValidateInputs(component)) {\n        component->operating_mode = ESC_MODE_SAFE_STATE;\n        SetSafeOutputs(component);\n        return;\n    }\n\n    \u002F\u002F 2. Mode management\n    switch (component->operating_mode) {\n        case ESC_MODE_NORMAL:\n            ESC_NormalOperation(component);\n            break;\n\n        case ESC_MODE_DEGRADED:\n            ESC_DegradedOperation(component);\n            break;\n\n        case ESC_MODE_SAFE_STATE:\n            ESC_SafeState(component);\n            break;\n\n        default:\n            \u002F\u002F Invalid mode - enter safe state\n            component->operating_mode = ESC_MODE_SAFE_STATE;\n            SetDTC(DTC_INVALID_MODE);\n            break;\n    }\n\n    \u002F\u002F 3. Output validation\n    ValidateOutputs(component);\n}\n```\n\n## MISRA C\u002FC++ Compliance\n\n### MISRA C:2012 Critical Rules for ASIL-D\n\n**Mandatory Rules (Must follow):**\n\n```c\n\u002F\u002F Rule 1.3: No undefined behavior\n\u002F\u002F BAD: Integer overflow undefined\nint32_t bad_add(int32_t a, int32_t b) {\n    return a + b;  \u002F\u002F ✗ May overflow\n}\n\n\u002F\u002F GOOD: Check for overflow\nint32_t safe_add(int32_t a, int32_t b, bool *overflow) {\n    if ((b > 0) && (a > (INT32_MAX - b))) {\n        *overflow = true;\n        return INT32_MAX;\n    }\n    if ((b \u003C 0) && (a \u003C (INT32_MIN - b))) {\n        *overflow = true;\n        return INT32_MIN;\n    }\n    *overflow = false;\n    return a + b;\n}\n\n\u002F\u002F Rule 2.2: Dead code shall be removed\n\u002F\u002F BAD: Unreachable code\nvoid bad_function(bool condition) {\n    if (condition) {\n        return;\n    }\n    DoSomething();  \u002F\u002F ✗ Dead code if condition always true\n    return;\n}\n\n\u002F\u002F GOOD: No dead code\nvoid good_function(bool condition) {\n    if (!condition) {\n        DoSomething();\n    }\n}\n\n\u002F\u002F Rule 8.13: Pointer should be const if not modified\n\u002F\u002F BAD: Missing const\nvoid bad_process(uint8_t *data) {  \u002F\u002F ✗ data not modified but not const\n    uint8_t value = data[0];\n    UseValue(value);\n}\n\n\u002F\u002F GOOD: Const pointer\nvoid good_process(const uint8_t *data) {\n    uint8_t value = data[0];\n    UseValue(value);\n}\n\n\u002F\u002F Rule 9.1: Use before initialization\n\u002F\u002F BAD: Uninitialized variable\nvoid bad_init(void) {\n    uint32_t value;\n    if (SomeCondition()) {\n        value = 42;\n    }\n    UseValue(value);  \u002F\u002F ✗ May be uninitialized\n}\n\n\u002F\u002F GOOD: Always initialized\nvoid good_init(void) {\n    uint32_t value = 0;  \u002F\u002F Default initialization\n    if (SomeCondition()) {\n        value = 42;\n    }\n    UseValue(value);\n}\n\n\u002F\u002F Rule 21.3: malloc\u002Ffree shall not be used\n\u002F\u002F BAD: Dynamic memory\nvoid bad_alloc(void) {\n    uint8_t *buffer = (uint8_t *)malloc(100);  \u002F\u002F ✗ Not allowed\n    free(buffer);\n}\n\n\u002F\u002F GOOD: Static allocation\n#define BUFFER_SIZE 100\nvoid good_alloc(void) {\n    uint8_t buffer[BUFFER_SIZE];  \u002F\u002F Static allocation\n    ProcessBuffer(buffer, BUFFER_SIZE);\n}\n```\n\n### MISRA C++ Specific Rules\n\n```cpp\n\u002F\u002F Rule A5-1-2: Use nullptr instead of NULL\n\u002F\u002F BAD: NULL macro\nvoid bad_pointer(void) {\n    int *ptr = NULL;  \u002F\u002F ✗ Old C style\n}\n\n\u002F\u002F GOOD: nullptr\nvoid good_pointer(void) {\n    int *ptr = nullptr;  \u002F\u002F ✓ C++11 style\n}\n\n\u002F\u002F Rule A10-0-2: Virtual destructor for base class\n\u002F\u002F BAD: Missing virtual destructor\nclass BadBase {  \u002F\u002F ✗ No virtual destructor\npublic:\n    void DoSomething();\n};\n\n\u002F\u002F GOOD: Virtual destructor\nclass GoodBase {\npublic:\n    virtual ~GoodBase() = default;  \u002F\u002F ✓ Virtual destructor\n    virtual void DoSomething();\n};\n\n\u002F\u002F Rule A15-5-1: Exception specifications\n\u002F\u002F BAD: Throwing exceptions in safety code\nvoid bad_exception(void) {\n    throw std::runtime_error(\"Error\");  \u002F\u002F ✗ Exceptions not allowed ASIL-D\n}\n\n\u002F\u002F GOOD: Error codes\nenum class ErrorCode {\n    SUCCESS,\n    INVALID_INPUT,\n    TIMEOUT\n};\n\nErrorCode good_error_handling(void) {\n    if (InvalidInput()) {\n        return ErrorCode::INVALID_INPUT;\n    }\n    return ErrorCode::SUCCESS;\n}\n```\n\n### Static Analysis Configuration\n\n**.misra_config.txt (for PC-Lint\u002FFlexelint):**\n```\n\u002F\u002F MISRA C:2012 rules for ASIL-D\n+misra(2012)\n\n\u002F\u002F Mandatory rules\n-strong(AXJ)  \u002F\u002F All rules from Advisory to Required to Mandatory\n\n\u002F\u002F Specific rule configuration\n-esym(960, 1.3)   \u002F\u002F Enable: No undefined behavior\n-esym(960, 2.2)   \u002F\u002F Enable: No dead code\n-esym(960, 8.13)  \u002F\u002F Enable: Pointer to const\n-esym(960, 9.1)   \u002F\u002F Enable: No uninitialized variables\n-esym(960, 21.3)  \u002F\u002F Enable: No dynamic memory\n\n\u002F\u002F Project-specific deviations (requires justification)\n-elib(960)        \u002F\u002F Suppress for library code\n```\n\n## Unit Testing - MC\u002FDC Coverage\n\n### Modified Condition\u002FDecision Coverage (MC\u002FDC)\n\n**Definition:** Every condition in a decision independently affects the outcome.\n\n**Example:**\n\n```c\n\u002F\u002F Function to test\nbool ESC_ShouldActivate(float yaw_rate, float lateral_accel, bool driver_input) {\n    \u002F\u002F Decision with 3 conditions (A, B, C)\n    if ((yaw_rate > THRESHOLD_YAW) &&        \u002F\u002F Condition A\n        (lateral_accel > THRESHOLD_ACCEL) && \u002F\u002F Condition B\n        (!driver_input))                     \u002F\u002F Condition C\n    {\n        return true;\n    }\n    return false;\n}\n\n\u002F\u002F MC\u002FDC Test Cases\nvoid test_mcdc_coverage(void) {\n    \u002F\u002F Truth table with MC\u002FDC coverage\n    \u002F\u002F TC | A | B | C | Result | Covers\n    \u002F\u002F ---+---+---+---+--------+--------\n    \u002F\u002F  1 | F | F | F |   F    | -\n    \u002F\u002F  2 | T | F | F |   F    | A (vs TC4)\n    \u002F\u002F  3 | F | T | F |   F    | B (vs TC4)\n    \u002F\u002F  4 | T | T | F |   T    | baseline\n    \u002F\u002F  5 | T | T | T |   F    | C (vs TC4)\n\n    \u002F\u002F Test Case 1: All false\n    assert(ESC_ShouldActivate(0.0, 0.0, false) == false);\n\n    \u002F\u002F Test Case 2: Only A true (tests A independence)\n    assert(ESC_ShouldActivate(10.0, 0.0, false) == false);\n\n    \u002F\u002F Test Case 3: Only B true (tests B independence)\n    assert(ESC_ShouldActivate(0.0, 10.0, false) == false);\n\n    \u002F\u002F Test Case 4: A and B true, C false (baseline true)\n    assert(ESC_ShouldActivate(10.0, 10.0, false) == true);\n\n    \u002F\u002F Test Case 5: All true but C negated (tests C independence)\n    assert(ESC_ShouldActivate(10.0, 10.0, true) == false);\n\n    \u002F\u002F MC\u002FDC coverage: 100% ✓\n}\n```\n\n### Unit Test Framework (Unity)\n\n```c\n\u002F\u002F test_esc_range_check.c\n#include \"unity.h\"\n#include \"esc_sensor.h\"\n\nvoid setUp(void) {\n    \u002F\u002F Called before each test\n    ESC_Init();\n}\n\nvoid tearDown(void) {\n    \u002F\u002F Called after each test\n    ESC_Deinit();\n}\n\n\u002F\u002F Test: Valid speed accepted\nvoid test_valid_speed_accepted(void) {\n    float speed = 100.0f;  \u002F\u002F Valid: 0-350 km\u002Fh\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(result);\n}\n\n\u002F\u002F Test: Negative speed rejected\nvoid test_negative_speed_rejected(void) {\n    float speed = -10.0f;  \u002F\u002F Invalid: \u003C 0\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_FALSE(result);\n}\n\n\u002F\u002F Test: Excessive speed rejected\nvoid test_excessive_speed_rejected(void) {\n    float speed = 400.0f;  \u002F\u002F Invalid: > 350\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_FALSE(result);\n}\n\n\u002F\u002F Test: Boundary value (low)\nvoid test_boundary_low(void) {\n    float speed = 0.0f;  \u002F\u002F Boundary: exactly 0\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(result);\n}\n\n\u002F\u002F Test: Boundary value (high)\nvoid test_boundary_high(void) {\n    float speed = 350.0f;  \u002F\u002F Boundary: exactly max\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(result);\n}\n\n\u002F\u002F Test: Fault flag set on invalid input\nvoid test_fault_flag_on_invalid(void) {\n    float speed = -10.0f;\n    ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(ESC_IsFaultFlagSet(FAULT_WHEEL_SPEED_INVALID));\n}\n\n\u002F\u002F Test: Safe state after persistent faults\nvoid test_safe_state_persistent_fault(void) {\n    \u002F\u002F Inject 4 consecutive invalid readings\n    for (int i = 0; i \u003C 4; i++) {\n        ESC_ValidateWheelSpeed(-10.0f);\n    }\n    TEST_ASSERT_EQUAL(ESC_MODE_SAFE_STATE, ESC_GetMode());\n}\n\nint main(void) {\n    UNITY_BEGIN();\n    RUN_TEST(test_valid_speed_accepted);\n    RUN_TEST(test_negative_speed_rejected);\n    RUN_TEST(test_excessive_speed_rejected);\n    RUN_TEST(test_boundary_low);\n    RUN_TEST(test_boundary_high);\n    RUN_TEST(test_fault_flag_on_invalid);\n    RUN_TEST(test_safe_state_persistent_fault);\n    return UNITY_END();\n}\n```\n\n### Coverage Report\n\n```bash\n# Run tests with coverage (gcov\u002Flcov)\ngcc -fprofile-arcs -ftest-coverage -o test_esc test_esc.c esc_sensor.c\n.\u002Ftest_esc\nlcov --capture --directory . --output-file coverage.info\ngenhtml coverage.info --output-directory coverage_html\n\n# Coverage report:\n# File: esc_sensor.c\n# Lines: 98.5% (65\u002F66)\n# Functions: 100% (8\u002F8)\n# Branches: 100% (24\u002F24)  ← MC\u002FDC coverage\n# MC\u002FDC: 100% ✓ (ASIL-D requirement met)\n```\n\n## Software Safety Manual\n\n### Template\n\n```markdown\n# Software Safety Manual\n# ESC Electronic Control Unit\n# Version 1.0\n# ASIL-D\n\n## 1. Introduction\n\n### 1.1 Scope\nThis Software Safety Manual describes the safety-related aspects of the\nESC (Electronic Stability Control) ECU software version 2.5.0, developed\nin accordance with ISO 26262-6:2018 for ASIL-D integrity level.\n\n### 1.2 Intended Use\nThe software is designed for use in passenger vehicles (M1 category) with:\n- Maximum gross weight: 3500 kg\n- Maximum speed: 200 km\u002Fh\n- Operating temperature: -40°C to +85°C\n\n## 2. Safety Concept\n\n### 2.1 Safety Goals\n- SG-ESC-001: Prevent unintended ESC activation (ASIL-D)\n- SG-ESC-002: ESC shall activate when stability compromised (ASIL-C)\n- SG-ESC-003: ESC response time \u003C 100ms (ASIL-B)\n\n### 2.2 Software Safety Requirements\nSee Section 5 for complete list (45 requirements, all verified).\n\n## 3. Assumptions and Dependencies\n\n### 3.1 Hardware Assumptions\n- Dual-core lockstep microcontroller (TMS570LC4357)\n- ECC-protected RAM (SECDED capable)\n- Watchdog timer with window monitoring\n- CAN controller with error detection\n\n### 3.2 Integration Assumptions\n- CAN bus operates at 500 kbps\n- Wheel speed sensors provide updates every 10ms\n- Supply voltage: 9V to 16V nominal\n\n### 3.3 Environmental Assumptions\n- Road surface friction coefficient: 0.1 to 1.0\n- Vehicle speed: 0 to 200 km\u002Fh\n- Tire pressure: 1.8 to 3.0 bar\n\n## 4. Safety Mechanisms\n\n### 4.1 Implemented Safety Mechanisms\n| ID | Description | Coverage |\n|----|-------------|----------|\n| SM-ESC-001 | Dual-core lockstep | 99.9% |\n| SM-ESC-002 | ECC on RAM | 99.99% |\n| SM-ESC-003 | Window watchdog | 95.0% |\n| SM-ESC-004 | Range checks | 90.0% |\n| SM-ESC-005 | CRC on CAN | 99.998% |\n\n### 4.2 Diagnostic Coverage\n- SPFM: 99.2% (target: > 99%) ✓\n- LFM: 92.5% (target: > 90%) ✓\n- PMHF: 8.5 FIT (target: \u003C 10 FIT) ✓\n\n## 5. Known Limitations\n\n### 5.1 Functional Limitations\n- ESC disabled when vehicle speed \u003C 10 km\u002Fh\n- ESC functionality reduced with 1 failed wheel speed sensor\n- ESC deactivated in reverse gear\n\n### 5.2 Performance Limitations\n- Maximum yaw rate: ±100°\u002Fs\n- Maximum lateral acceleration: ±1.5g\n- Response time: 50-100ms (depends on sensor update rate)\n\n## 6. Safe States\n\n### 6.1 Safe State Definition\n- All brake modulation disabled\n- Manual brake control available\n- Warning lamp activated\n- DTC stored in non-volatile memory\n\n### 6.2 Transition Conditions\n- Lockstep mismatch detected\n- Persistent sensor failure (> 3 consecutive)\n- Watchdog timeout\n- Critical software error detected\n\n## 7. Integration Guidelines\n\n### 7.1 Configuration Parameters\n```c\n#define ESC_YAW_THRESHOLD_DEG_S     (15.0f)\n#define ESC_LATERAL_ACCEL_THRESHOLD_G (0.4f)\n#define ESC_FTTI_MS                 (150)\n#define ESC_SENSOR_TIMEOUT_MS       (100)\n```\n\n### 7.2 Calibration Requirements\n- Parameters must be calibrated for specific vehicle platform\n- Validation testing required after calibration changes\n- Safety-critical parameters protected by CRC\n\n## 8. Verification Evidence\n\n### 8.1 Testing Summary\n- Unit tests: 487 test cases, 100% MC\u002FDC coverage\n- Integration tests: 125 test cases, all passed\n- System tests: 45 test cases, all passed\n- HIL testing: 1000 hours, 0 safety-critical failures\n\n### 8.2 Static Analysis\n- MISRA C:2012 compliance: 100% (0 deviations)\n- Cyclomatic complexity: Max 8 (target: \u003C 10)\n- Code review: All modules approved\n\n## 9. Maintenance and Support\n\n### 9.1 Software Updates\n- Updates require full regression testing\n- Safety assessment required for any safety-critical change\n- Version control: Git with signed commits\n\n### 9.2 Field Monitoring\n- DTC monitoring via diagnostic interface\n- Software version readable via OBD-II\n- Field failure data collection mandatory\n\n## 10. References\n- ISO 26262-6:2018 - Software Development\n- MISRA C:2012 - Guidelines for C\n- ESC_SWR_v2.5.pdf - Software Safety Requirements\n- ESC_TestReport_v2.5.pdf - Verification Report\n```\n\n## Production Checklist\n\n### ASIL-D Software Development\n\n- [ ] Software safety requirements defined and reviewed\n- [ ] Architecture designed with freedom from interference\n- [ ] MISRA C\u002FC++ compliance verified (100%)\n- [ ] Static analysis performed (0 critical violations)\n- [ ] Unit tests achieve MC\u002FDC coverage (100%)\n- [ ] Integration tests cover all interfaces\n- [ ] Timing analysis performed (WCET verified)\n- [ ] Memory usage analyzed (stack\u002Fheap within limits)\n- [ ] Code reviews completed (all units)\n- [ ] Back-to-back testing (model vs code) performed\n- [ ] Software safety manual completed\n- [ ] Tool qualification performed (compiler, static analyzer)\n- [ ] Configuration management in place\n- [ ] Independent software assessment passed\n\n## References\n\n- ISO 26262-6:2018 - Product Development at Software Level\n- ISO 26262-8:2018 - Supporting Processes\n- MISRA C:2012 - Guidelines for the Use of C\n- MISRA C++:2008 - Guidelines for C++\n- AUTOSAR Coding Guidelines\n- DO-178C - Software Considerations in Airborne Systems (reference)\n\n## Related Skills\n\n- ISO 26262 Overview\n- Safety Mechanisms and Patterns\n- FMEA\u002FFTA Analysis\n- Safety Verification and Validation\n- MISRA C Coding Guidelines\n","# Automotive Safety\n\n## Fmea Fta Analysis\n\n# FMEA\u002FFTA\u002FFMEDA Analysis for ISO 26262\n\nComprehensive guidance on Failure Mode and Effects Analysis (FMEA), Fault Tree Analysis (FTA), and Failure Modes, Effects, and Diagnostic Analysis (FMEDA) for automotive functional safety, including templates, calculation methods, and production-ready examples.\n\n## Overview\n\n### Analysis Types\n\n**FMEA (Failure Mode and Effects Analysis)**\n- Bottom-up analysis: component failure → system effect\n- Identifies single-point and latent faults\n- Calculates diagnostic coverage\n- Required for all ASIL levels\n\n**FTA (Fault Tree Analysis)**\n- Top-down analysis: hazardous event → contributing faults\n- Quantifies failure probability\n- Validates ASIL decomposition\n- Mandatory for ASIL C\u002FD\n\n**FMEDA (Failure Modes, Effects, and Diagnostic Analysis)**\n- Extension of FMEA with quantitative metrics\n- Calculates PMHF (Probabilistic Metric for random Hardware Failures)\n- Determines SPFM and LFM\n- Required for ASIL B\u002FC\u002FD hardware\n\n## FMEA Methodology\n\n### FMEA Process Flow\n\n```\n┌──────────────────────────┐\n│ 1. Define System         │\n│    Boundaries            │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 2. Identify Components   │\n│    and Functions         │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 3. Identify Failure      │\n│    Modes                 │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 4. Analyze Effects       │\n│    (Local\u002FSystem\u002FEnd)    │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 5. Classify Faults       │\n│    (SPF\u002FRF\u002FLF)           │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 6. Define Safety         │\n│    Mechanisms            │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 7. Calculate Diagnostic  │\n│    Coverage (DC)         │\n└────────┬─────────────────┘\n         │\n         ▼\n┌──────────────────────────┐\n│ 8. Verify Metrics        │\n│    (SPFM\u002FLFM\u002FPMHF)       │\n└──────────────────────────┘\n```\n\n### Fault Classifications\n\n**Single-Point Fault (SPF)**\n- Fault that directly leads to violation of safety goal\n- No safety mechanism provides detection\n- Must be minimized (SPFM > 99% for ASIL-D)\n\n**Residual Fault (RF)**\n- Fault detected by safety mechanism but coverage \u003C 100%\n- Contributes to PMHF calculation\n- Example: CRC detects 99.998% of errors → 0.002% residual\n\n**Latent Fault (LF)**\n- Multi-point fault: not detected immediately\n- Only becomes hazardous in combination with another fault\n- Must be detected before second fault occurs (LFM > 90% for ASIL-D)\n\n**Safe Fault (SF)**\n- Fault detected with high coverage (> 99%)\n- Transition to safe state within FTTI\n- Does not contribute to PMHF\n\n### FMEA Worksheet Template\n\n```yaml\nfmea_id: \"FMEA-ESC-HW-001\"\nsystem: \"Electronic Stability Control\"\nsubsystem: \"ESC ECU Hardware\"\nasil: \"ASIL-D\"\nanalyst: \"HW Safety Engineer\"\ndate: \"2024-03-19\"\nversion: \"1.2\"\n\ncomponents:\n  - component_id: \"C001\"\n    component_name: \"Microcontroller (MCU)\"\n    part_number: \"TMS570LC4357\"\n    function: \"Main processing unit for ESC algorithms\"\n\n    failure_modes:\n      - fm_id: \"FM-C001-001\"\n        failure_mode: \"MCU Core 0 stuck-at-high output\"\n        failure_rate_fit: 50  # Failures in 10^9 hours\n        failure_cause: \"Transistor latch-up, ESD damage\"\n\n        effects:\n          local_effect: \"Core 0 outputs invalid high logic\"\n          subsystem_effect: \"Incorrect PWM output to brake modulator\"\n          system_effect: \"Unintended brake actuation on one wheel\"\n          end_effect: \"Vehicle instability, potential loss of control\"\n\n        severity: \"S3\"  # Life-threatening\n        detection_method: \"Dual-core lockstep comparison\"\n        detection_coverage_pct: 99.9\n\n        fault_classification:\n          before_sm: \"SPF\"  # Single-point fault without safety mechanism\n          after_sm: \"SF\"    # Safe fault with lockstep detection\n          diagnostic_coverage: 99.9  # DC = 99.9%\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-001\"\n          description: \"Dual-core lockstep with cycle-by-cycle comparison\"\n          detection_time_ms: 0.1  # Detection within 100 μs\n          reaction: \"Immediate transition to safe state\"\n          ftti_ms: 150\n\n        residual_failure_rate_fit: 0.05  # 50 * (1 - 0.999) = 0.05\n        lambda_spf_fit: 0.05\n        lambda_rf_fit: 0.05\n\n      - fm_id: \"FM-C001-002\"\n        failure_mode: \"MCU RAM single-bit flip (SEU)\"\n        failure_rate_fit: 100\n        failure_cause: \"Cosmic ray, alpha particle\"\n\n        effects:\n          local_effect: \"Corrupted data in RAM\"\n          subsystem_effect: \"Incorrect calculation results\"\n          system_effect: \"Wrong ESC intervention decision\"\n          end_effect: \"Delayed or incorrect stability control\"\n\n        severity: \"S2\"\n        detection_method: \"ECC (Error Correcting Code) on RAM\"\n        detection_coverage_pct: 99.99\n\n        fault_classification:\n          before_sm: \"SPF\"\n          after_sm: \"SF\"\n          diagnostic_coverage: 99.99\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-002\"\n          description: \"ECC on safety-critical RAM sections\"\n          detection_time_ms: 0.01\n          reaction: \"Correct single-bit errors, flag multi-bit errors\"\n\n        residual_failure_rate_fit: 0.01\n        lambda_spf_fit: 0.01\n        lambda_rf_fit: 0.01\n\n      - fm_id: \"FM-C001-003\"\n        failure_mode: \"MCU clock frequency drift\"\n        failure_rate_fit: 20\n        failure_cause: \"Oscillator aging, temperature stress\"\n\n        effects:\n          local_effect: \"Incorrect timing of operations\"\n          subsystem_effect: \"ESC algorithm timing violated\"\n          system_effect: \"Delayed ESC response (> 100 ms)\"\n          end_effect: \"Reduced effectiveness of stability control\"\n\n        severity: \"S2\"\n        detection_method: \"External watchdog with window timing\"\n        detection_coverage_pct: 95.0\n\n        fault_classification:\n          before_sm: \"SPF\"\n          after_sm: \"RF\"  # Residual fault (95% coverage)\n          diagnostic_coverage: 95.0\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-003\"\n          description: \"Window watchdog monitors timing\"\n          detection_time_ms: 50\n          reaction: \"Safe state transition if timing violated\"\n\n        residual_failure_rate_fit: 1.0  # 20 * (1 - 0.95) = 1.0\n        lambda_spf_fit: 0\n        lambda_rf_fit: 1.0\n\n  - component_id: \"C002\"\n    component_name: \"Wheel Speed Sensor (Front Left)\"\n    part_number: \"ABS-SENSOR-FL\"\n    function: \"Measure front-left wheel rotational speed\"\n\n    failure_modes:\n      - fm_id: \"FM-C002-001\"\n        failure_mode: \"Sensor output stuck-at-zero\"\n        failure_rate_fit: 150\n        failure_cause: \"Wiring short-to-ground, sensor damage\"\n\n        effects:\n          local_effect: \"Constant zero speed output\"\n          subsystem_effect: \"ESC detects wheel as stationary\"\n          system_effect: \"Incorrect vehicle dynamics calculation\"\n          end_effect: \"ESC may fail to intervene when needed\"\n\n        severity: \"S3\"\n        detection_method: \"Plausibility check vs other wheel speeds\"\n        detection_coverage_pct: 90.0\n\n        fault_classification:\n          before_sm: \"LF\"  # Latent fault (multi-point failure)\n          after_sm: \"LF\"   # Still latent but detected\n          diagnostic_coverage: 90.0\n\n        safety_mechanism:\n          sm_id: \"SM-ESC-004\"\n          description: \"Cross-check wheel speeds for consistency\"\n          detection_time_ms: 200\n          reaction: \"Flag sensor as faulty, use 3-wheel calculation\"\n\n        residual_failure_rate_fit: 15.0  # 150 * (1 - 0.90) = 15.0\n        lambda_lf_fit: 135.0  # 150 * 0.90 (detected latent)\n        lambda_rf_fit: 15.0\n\nmetrics:\n  total_failure_rate_fit: 320  # Sum of all component failure rates\n\n  spf_metric:\n    lambda_spf_total: 0.06  # Sum of all SPF contributions after SM\n    lambda_total: 320\n    spfm_percent: 99.98  # (1 - 0.06\u002F320) * 100 = 99.98%\n    target_asil_d: 99.0\n    status: \"PASS\"\n\n  lf_metric:\n    lambda_lf_detected: 135.0\n    lambda_lf_total: 150.0\n    lfm_percent: 90.0  # (135\u002F150) * 100 = 90.0%\n    target_asil_d: 90.0\n    status: \"PASS\"\n\n  pmhf:\n    lambda_spf: 0.06\n    lambda_rf: 16.06\n    pmhf_fit: 16.12  # SPF + RF = 0.06 + 16.06\n    target_asil_d_fit: 10.0\n    status: \"FAIL - Requires design improvement\"\n\nconclusions:\n  - SPFM meets ASIL-D target (99.98% > 99%)\n  - LFM meets ASIL-D target (90.0% >= 90%)\n  - PMHF exceeds ASIL-D target (16.12 > 10 FIT)\n  - Recommendation: Improve sensor redundancy or diagnostic coverage\n\nactions:\n  - action_id: \"ACT-001\"\n    description: \"Add redundant wheel speed sensor (1oo2 configuration)\"\n    responsible: \"HW Design Team\"\n    due_date: \"2024-04-30\"\n    expected_pmhf_reduction: \"50%\"\n```\n\n## FTA Methodology\n\n### Fault Tree Symbols\n\n```\n┌─────────────────────────────────────────┐\n│ Event Symbols                           │\n├─────────────────────────────────────────┤\n│  ◯  Basic Event (failure)               │\n│  □  Intermediate Event                  │\n│  ◇  Undeveloped Event                   │\n│  ⬡  External Event                      │\n└─────────────────────────────────────────┘\n\n┌─────────────────────────────────────────┐\n│ Gate Symbols                            │\n├─────────────────────────────────────────┤\n│  ∧  AND Gate (all inputs required)      │\n│  ∨  OR Gate (any input sufficient)      │\n│  ⊕  XOR Gate (exclusive-or)             │\n│  ≥K  K-out-of-N Gate                    │\n└─────────────────────────────────────────┘\n```\n\n### FTA Example - Unintended ESC Activation\n\n```\nTop Event: Unintended ESC Activation (ASIL-D)\n│\n├─ OR ────────────────────────────────────┐\n│                                          │\n▼                                          ▼\n[Spurious Brake Command]              [Sensor False Positive]\n│                                          │\n├─ OR ─────────────────┐                  ├─ OR ──────────────┐\n│                      │                  │                   │\n▼                      ▼                  ▼                   ▼\n[MCU Fault]     [CAN Corruption]    [Yaw Sensor]      [Lateral Accel]\n│                      │              Stuck-High       Sensor Stuck\n├─ AND ───────┐        │\n│             │        │\n▼             ▼        ▼\n[Core Fault] [Lockstep] [EMI]\n◯ 50 FIT      Fails     ◯ 10 FIT\n              ◯ 0.5 FIT\n```\n\n### Quantitative FTA\n\n**Calculate Top Event Probability:**\n\n```python\n# FTA calculations\nimport math\n\n# Basic event failure rates (FIT = failures in 10^9 hours)\nfailure_rates = {\n    'mcu_core_fault': 50,\n    'lockstep_failure': 0.5,\n    'can_emi': 10,\n    'yaw_sensor_stuck': 100,\n    'lateral_accel_stuck': 80\n}\n\n# Mission time (hours)\nmission_time = 10000  # 10,000 hours (typical vehicle lifetime)\n\n# Convert FIT to probability\ndef fit_to_probability(fit, hours):\n    \"\"\"Convert FIT to probability over given hours\"\"\"\n    lambda_per_hour = fit \u002F 1e9\n    return 1 - math.exp(-lambda_per_hour * hours)\n\n# Calculate probabilities\nprob = {}\nfor event, fit in failure_rates.items():\n    prob[event] = fit_to_probability(fit, mission_time)\n    print(f\"{event}: {prob[event]:.6e}\")\n\n# AND gate: P(A AND B) = P(A) * P(B)\nprob_mcu_undetected = prob['mcu_core_fault'] * prob['lockstep_failure']\nprint(f\"\\nMCU undetected fault: {prob_mcu_undetected:.6e}\")\n\n# OR gate: P(A OR B) = P(A) + P(B) - P(A)*P(B)\ndef or_gate(p1, p2):\n    return p1 + p2 - (p1 * p2)\n\n# Spurious brake command path\nprob_spurious_brake = or_gate(prob_mcu_undetected, prob['can_emi'])\nprint(f\"Spurious brake command: {prob_spurious_brake:.6e}\")\n\n# Sensor false positive path\nprob_sensor_false = or_gate(prob['yaw_sensor_stuck'], prob['lateral_accel_stuck'])\nprint(f\"Sensor false positive: {prob_sensor_false:.6e}\")\n\n# Top event\nprob_top_event = or_gate(prob_spurious_brake, prob_sensor_false)\nprint(f\"\\nTop Event (Unintended ESC): {prob_top_event:.6e}\")\n\n# ASIL-D target: \u003C 10 FIT = 1e-4 probability over 10,000 hours\nasil_d_target = fit_to_probability(10, mission_time)\nprint(f\"ASIL-D target (\u003C 10 FIT): {asil_d_target:.6e}\")\n\nif prob_top_event \u003C asil_d_target:\n    print(\"✓ FTA meets ASIL-D requirement\")\nelse:\n    print(\"✗ FTA fails ASIL-D requirement\")\n    print(f\"Risk reduction factor needed: {prob_top_event \u002F asil_d_target:.1f}x\")\n```\n\n### Cut Set Analysis\n\n**Minimal Cut Sets:**\n\nCut sets are combinations of basic events that cause the top event.\n\n```python\n# Minimal cut sets for FTA\ncut_sets = [\n    ['mcu_core_fault', 'lockstep_failure'],  # AND gate\n    ['can_emi'],                              # Single point\n    ['yaw_sensor_stuck'],                     # Single point\n    ['lateral_accel_stuck']                   # Single point\n]\n\n# Calculate cut set probabilities\nprint(\"Minimal Cut Sets:\")\nfor i, cut_set in enumerate(cut_sets, 1):\n    if len(cut_set) == 1:\n        # Single-point fault\n        prob_cut = prob[cut_set[0]]\n        print(f\"  Cut Set {i} (SPF): {cut_set} = {prob_cut:.6e}\")\n    else:\n        # Multi-point fault (AND)\n        prob_cut = 1.0\n        for event in cut_set:\n            prob_cut *= prob[event]\n        print(f\"  Cut Set {i} (AND): {cut_set} = {prob_cut:.6e}\")\n\n# Importance analysis - which events contribute most?\nprint(\"\\nImportance Analysis:\")\nevent_contributions = {}\nfor event in failure_rates:\n    # Calculate top event probability with this event probability = 1\n    test_prob = prob.copy()\n    test_prob[event] = 1.0\n\n    # Recalculate (simplified)\n    if event in ['mcu_core_fault', 'lockstep_failure']:\n        test_spurious = or_gate(test_prob['mcu_core_fault'] * test_prob['lockstep_failure'],\n                                test_prob['can_emi'])\n    else:\n        test_spurious = prob_spurious_brake\n\n    if event in ['yaw_sensor_stuck', 'lateral_accel_stuck']:\n        test_sensor = or_gate(test_prob['yaw_sensor_stuck'], test_prob['lateral_accel_stuck'])\n    else:\n        test_sensor = prob_sensor_false\n\n    test_top = or_gate(test_spurious, test_sensor)\n\n    importance = test_top - prob_top_event\n    event_contributions[event] = importance\n\n# Sort by importance\nsorted_events = sorted(event_contributions.items(), key=lambda x: x[1], reverse=True)\nfor event, importance in sorted_events:\n    print(f\"  {event}: {importance:.6e}\")\n\nprint(\"\\nRecommendation: Focus safety mechanisms on:\", sorted_events[0][0])\n```\n\n## FMEDA Calculations\n\n### Hardware Metrics Formulas\n\n**1. Single-Point Fault Metric (SPFM)**\n\n```\nSPFM = (1 - (ΣλSPF \u002F Σλ)) × 100%\n\nWhere:\n  λSPF = failure rate of single-point faults (FIT)\n  λ = total failure rate (FIT)\n\nASIL Targets:\n  ASIL B: SPFM > 90%\n  ASIL C: SPFM > 97%\n  ASIL D: SPFM > 99%\n```\n\n**2. Latent Fault Metric (LFM)**\n\n```\nLFM = (1 - (ΣλLF,undetected \u002F ΣλLF)) × 100%\n\nWhere:\n  λLF,undetected = latent faults not detected (FIT)\n  λLF = total latent fault rate (FIT)\n\nASIL Targets:\n  ASIL B: LFM > 60%\n  ASIL C: LFM > 80%\n  ASIL D: LFM > 90%\n```\n\n**3. Probabilistic Metric for random Hardware Failures (PMHF)**\n\n```\nPMHF = ΣλSPF + ΣλRF\n\nWhere:\n  λSPF = single-point fault rate (FIT)\n  λRF = residual fault rate (FIT)\n\nASIL Targets (per safety goal):\n  ASIL B: PMHF \u003C 100 FIT\n  ASIL C: PMHF \u003C 100 FIT\n  ASIL D: PMHF \u003C 10 FIT\n\nNote: 1 FIT = 1 failure in 10^9 hours\n      10 FIT ≈ 1 failure per 11,400 years of operation\n```\n\n### Diagnostic Coverage Classes\n\n| DC Class | Coverage Range | Examples |\n|----------|---------------|----------|\n| DC 0 | None (0%) | No diagnostic |\n| DC 1 | Low (60-90%) | Plausibility checks |\n| DC 2 | Medium (90-99%) | Watchdog, CRC |\n| DC 3 | High (99-100%) | Dual-core lockstep, ECC |\n\n### FMEDA Spreadsheet\n\n```\nComponent: ESC ECU Microcontroller\nPart Number: TMS570LC4357\nASIL: D\n\n┌─────┬──────────────────┬──────┬──────┬──────┬────┬────┬────┬────┐\n│ ID  │ Failure Mode     │  λ   │ DC%  │Class │SPF │ RF │ LF │ SF │\n├─────┼──────────────────┼──────┼──────┼──────┼────┼────┼────┼────┤\n│ FM1 │ Core stuck-at    │  50  │ 99.9 │ DC3  │ 0  │0.05│ 0  │49.95│\n│ FM2 │ RAM bit-flip     │ 100  │ 99.99│ DC3  │ 0  │0.01│ 0  │99.99│\n│ FM3 │ Clock drift      │  20  │ 95.0 │ DC2  │ 0  │ 1.0│ 0  │ 19.0│\n│ FM4 │ Flash ECC fail   │  10  │ 100  │ DC3  │ 0  │ 0  │ 0  │ 10.0│\n│ FM5 │ Watchdog fail    │   5  │  0   │ DC0  │ 5  │ 0  │ 0  │  0  │\n│ FM6 │ ADC stuck        │  30  │ 85.0 │ DC1  │ 0  │ 4.5│ 0  │25.5 │\n│ FM7 │ Power supply OV  │  15  │ 99.0 │ DC3  │ 0  │0.15│ 0  │14.85│\n│ FM8 │ Temp sensor drift│  25  │ 90.0 │ DC2  │ 0  │ 2.5│ 0  │22.5 │\n├─────┼──────────────────┼──────┼──────┼──────┼────┼────┼────┼────┤\n│ SUM │                  │ 255  │      │      │ 5  │8.21│ 0  │241.79│\n└─────┴──────────────────┴──────┴──────┴──────┴────┴────┴────┴────┘\n\nCalculations:\n  SPFM = (1 - 5\u002F255) × 100% = 98.04%  ← FAIL (target: >99%)\n  LFM = N\u002FA (no latent faults)\n  PMHF = 5 + 8.21 = 13.21 FIT  ← FAIL (target: \u003C10 FIT)\n\nRequired Actions:\n  1. Eliminate watchdog SPF (add redundant watchdog)\n  2. Improve ADC diagnostic coverage (add cross-checks)\n  3. Target: SPFM > 99%, PMHF \u003C 10 FIT\n```\n\n## FMEA\u002FFTA Integration\n\n### Bidirectional Validation\n\n**FMEA → FTA Validation:**\n\n1. Each SPF in FMEA should appear as single basic event in FTA\n2. Each latent fault should appear in AND gate (multi-point)\n3. Safety mechanisms should reduce FTA cut set probabilities\n\n**FTA → FMEA Validation:**\n\n1. Each FTA basic event should have corresponding FMEA failure mode\n2. FTA cut sets reveal dependent failures for DFA\n3. FTA probability calculation validates PMHF\n\n### Example Cross-Check\n\n```python\n# Validate FMEA and FTA consistency\nfmea_failure_modes = {\n    'mcu_core_fault': {'lambda': 50, 'dc': 99.9, 'spf': 0.05},\n    'ram_bit_flip': {'lambda': 100, 'dc': 99.99, 'spf': 0.01},\n    'sensor_stuck': {'lambda': 150, 'dc': 90.0, 'spf': 0}\n}\n\nfta_basic_events = {\n    'mcu_core_fault': 50,\n    'ram_bit_flip': 100,\n    'sensor_stuck': 150\n}\n\n# Check consistency\nprint(\"FMEA\u002FFTA Cross-Validation:\")\nfor event in fmea_failure_modes:\n    if event in fta_basic_events:\n        fmea_lambda = fmea_failure_modes[event]['lambda']\n        fta_lambda = fta_basic_events[event]\n\n        if fmea_lambda == fta_lambda:\n            print(f\"✓ {event}: Consistent ({fmea_lambda} FIT)\")\n        else:\n            print(f\"✗ {event}: Mismatch (FMEA: {fmea_lambda}, FTA: {fta_lambda})\")\n    else:\n        print(f\"⚠ {event}: Missing in FTA\")\n\nfor event in fta_basic_events:\n    if event not in fmea_failure_modes:\n        print(f\"⚠ {event}: Missing in FMEA\")\n```\n\n## Production-Ready Tools\n\n### FMEA Database Schema (SQL)\n\n```sql\nCREATE TABLE Components (\n    component_id VARCHAR(50) PRIMARY KEY,\n    component_name VARCHAR(200),\n    part_number VARCHAR(100),\n    function TEXT,\n    asil VARCHAR(10)\n);\n\nCREATE TABLE FailureModes (\n    fm_id VARCHAR(50) PRIMARY KEY,\n    component_id VARCHAR(50) REFERENCES Components(component_id),\n    failure_mode TEXT,\n    failure_rate_fit DECIMAL(10,2),\n    failure_cause TEXT,\n    local_effect TEXT,\n    system_effect TEXT,\n    end_effect TEXT,\n    severity VARCHAR(2)\n);\n\nCREATE TABLE SafetyMechanisms (\n    sm_id VARCHAR(50) PRIMARY KEY,\n    fm_id VARCHAR(50) REFERENCES FailureModes(fm_id),\n    description TEXT,\n    detection_coverage_pct DECIMAL(5,2),\n    detection_time_ms DECIMAL(10,2),\n    reaction TEXT,\n    ftti_ms DECIMAL(10,2)\n);\n\nCREATE TABLE FaultClassification (\n    fc_id SERIAL PRIMARY KEY,\n    fm_id VARCHAR(50) REFERENCES FailureModes(fm_id),\n    before_sm VARCHAR(10),  -- SPF, RF, LF, SF\n    after_sm VARCHAR(10),\n    diagnostic_coverage DECIMAL(5,2),\n    lambda_spf_fit DECIMAL(10,2),\n    lambda_rf_fit DECIMAL(10,2),\n    lambda_lf_fit DECIMAL(10,2),\n    lambda_sf_fit DECIMAL(10,2)\n);\n\n-- Query: Calculate SPFM for a system\nSELECT\n    SUM(fc.lambda_spf_fit) AS total_spf,\n    SUM(fm.failure_rate_fit) AS total_lambda,\n    (1 - SUM(fc.lambda_spf_fit) \u002F SUM(fm.failure_rate_fit)) * 100 AS spfm_percent\nFROM FailureModes fm\nJOIN FaultClassification fc ON fm.fm_id = fc.fm_id\nWHERE fm.component_id IN (SELECT component_id FROM Components WHERE asil = 'ASIL-D');\n```\n\n### Python FMEDA Calculator\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nISO 26262 FMEDA Calculator\nCalculates SPFM, LFM, and PMHF metrics\n\"\"\"\n\nclass FMEDACalculator:\n    def __init__(self, asil_level):\n        self.asil_level = asil_level\n        self.failure_modes = []\n        self.targets = self._get_targets(asil_level)\n\n    def _get_targets(self, asil):\n        targets = {\n            'ASIL-A': {'spfm': 0, 'lfm': 0, 'pmhf': 1000},\n            'ASIL-B': {'spfm': 90, 'lfm': 60, 'pmhf': 100},\n            'ASIL-C': {'spfm': 97, 'lfm': 80, 'pmhf': 100},\n            'ASIL-D': {'spfm': 99, 'lfm': 90, 'pmhf': 10}\n        }\n        return targets.get(asil, targets['ASIL-D'])\n\n    def add_failure_mode(self, name, lambda_fit, dc_percent):\n        \"\"\"\n        Add a failure mode with diagnostic coverage\n        \"\"\"\n        fm = {\n            'name': name,\n            'lambda': lambda_fit,\n            'dc': dc_percent \u002F 100.0,\n            'lambda_detected': lambda_fit * (dc_percent \u002F 100.0),\n            'lambda_residual': lambda_fit * (1 - dc_percent \u002F 100.0)\n        }\n        self.failure_modes.append(fm)\n\n    def calculate_metrics(self):\n        \"\"\"\n        Calculate SPFM, LFM, PMHF\n        \"\"\"\n        lambda_total = sum(fm['lambda'] for fm in self.failure_modes)\n        lambda_spf = sum(fm['lambda_residual'] for fm in self.failure_modes if fm['dc'] == 0)\n        lambda_rf = sum(fm['lambda_residual'] for fm in self.failure_modes if 0 \u003C fm['dc'] \u003C 1)\n        lambda_lf_detected = sum(fm['lambda_detected'] for fm in self.failure_modes)\n        lambda_lf_total = lambda_total  # Simplified\n\n        spfm = (1 - lambda_spf \u002F lambda_total) * 100 if lambda_total > 0 else 0\n        lfm = (lambda_lf_detected \u002F lambda_lf_total) * 100 if lambda_lf_total > 0 else 0\n        pmhf = lambda_spf + lambda_rf\n\n        return {\n            'spfm': spfm,\n            'lfm': lfm,\n            'pmhf': pmhf,\n            'lambda_total': lambda_total,\n            'lambda_spf': lambda_spf,\n            'lambda_rf': lambda_rf\n        }\n\n    def check_compliance(self):\n        \"\"\"\n        Check if metrics meet ASIL targets\n        \"\"\"\n        metrics = self.calculate_metrics()\n\n        compliance = {\n            'spfm': metrics['spfm'] >= self.targets['spfm'],\n            'lfm': metrics['lfm'] >= self.targets['lfm'],\n            'pmhf': metrics['pmhf'] \u003C= self.targets['pmhf']\n        }\n\n        return metrics, compliance\n\n    def generate_report(self):\n        \"\"\"\n        Generate compliance report\n        \"\"\"\n        metrics, compliance = self.check_compliance()\n\n        print(f\"\\n{'='*60}\")\n        print(f\"FMEDA Report - {self.asil_level}\")\n        print(f\"{'='*60}\\n\")\n\n        print(f\"{'Metric':\u003C20} {'Value':\u003C15} {'Target':\u003C15} {'Status':\u003C10}\")\n        print(f\"{'-'*60}\")\n\n        print(f\"{'SPFM':\u003C20} {metrics['spfm']:>8.2f}% \"\n              f\"{self.targets['spfm']:>8}% \"\n              f\"{'PASS' if compliance['spfm'] else 'FAIL':\u003C10}\")\n\n        print(f\"{'LFM':\u003C20} {metrics['lfm']:>8.2f}% \"\n              f\"{self.targets['lfm']:>8}% \"\n              f\"{'PASS' if compliance['lfm'] else 'FAIL':\u003C10}\")\n\n        print(f\"{'PMHF':\u003C20} {metrics['pmhf']:>8.2f} FIT \"\n              f\"{'\u003C':>2}{self.targets['pmhf']:>5} FIT \"\n              f\"{'PASS' if compliance['pmhf'] else 'FAIL':\u003C10}\")\n\n        print(f\"\\n{'Detail':\u003C20} {'Value':\u003C15}\")\n        print(f\"{'-'*35}\")\n        print(f\"{'Total λ':\u003C20} {metrics['lambda_total']:>8.2f} FIT\")\n        print(f\"{'λ SPF':\u003C20} {metrics['lambda_spf']:>8.2f} FIT\")\n        print(f\"{'λ RF':\u003C20} {metrics['lambda_rf']:>8.2f} FIT\")\n\n        overall = all(compliance.values())\n        print(f\"\\n{'Overall Compliance:':\u003C20} {'PASS' if overall else 'FAIL'}\")\n\n        return overall\n\n\n# Example usage\nif __name__ == \"__main__\":\n    calc = FMEDACalculator('ASIL-D')\n\n    # Add failure modes\n    calc.add_failure_mode('MCU Core Fault', lambda_fit=50, dc_percent=99.9)\n    calc.add_failure_mode('RAM Bit Flip', lambda_fit=100, dc_percent=99.99)\n    calc.add_failure_mode('Clock Drift', lambda_fit=20, dc_percent=95.0)\n    calc.add_failure_mode('Watchdog Fail', lambda_fit=5, dc_percent=0.0)  # SPF!\n    calc.add_failure_mode('ADC Stuck', lambda_fit=30, dc_percent=85.0)\n\n    # Generate report\n    calc.generate_report()\n```\n\n## Production Checklist\n\n- [ ] FMEA completed for all hardware\u002Fsoftware components\n- [ ] Failure modes identified at appropriate level (component\u002Ffunction)\n- [ ] Effects analyzed at local\u002Fsystem\u002Fend level\n- [ ] Safety mechanisms defined for all SPF\u002FLF\n- [ ] Diagnostic coverage calculated and validated\n- [ ] SPFM\u002FLFM\u002FPMHF metrics calculated\n- [ ] FTA performed for all ASIL C\u002FD safety goals\n- [ ] Cut sets identified and analyzed\n- [ ] FMEA and FTA cross-validated\n- [ ] Independent review completed\n- [ ] Metrics meet ASIL targets\n\n## References\n\n- ISO 26262-5:2018 Annex D - FMEDA Method\n- ISO 26262-9:2018 - ASIL-Oriented Analyses\n- IEC 61025 - Fault Tree Analysis\n- SAE J1739 - Potential Failure Mode and Effects Analysis (FMEA)\n- AIAG\u002FVDA FMEA Handbook\n\n## Related Skills\n\n- ISO 26262 Overview\n- Safety Mechanisms and Patterns\n- Hardware Safety Requirements\n- Software Safety Requirements\n- Dependent Failure Analysis (DFA)\n\n---\n\n## Hazard Analysis Risk Assessment\n\n# Hazard Analysis and Risk Assessment (HARA)\n\nComprehensive guidance on performing ISO 26262-compliant Hazard Analysis and Risk Assessment (HARA) for automotive E\u002FE systems, including hazard identification, situation analysis, severity\u002Fexposure\u002Fcontrollability classification, and ASIL determination.\n\n## HARA Overview\n\n### Purpose and Scope\n\n**Objectives:**\n- Identify potential hazards from malfunctioning behavior\n- Assess risk level of each hazardous event\n- Determine Automotive Safety Integrity Level (ASIL)\n- Define safety goals to mitigate unacceptable risks\n\n**When to Perform HARA:**\n- Concept phase (Part 3 of ISO 26262)\n- New vehicle\u002Fsystem development\n- Major system modifications\n- Changes to operational context\n- New use cases or operational scenarios\n\n### HARA Process Flow\n\n```\n┌────────────────────────────────┐\n│   1. Item Definition           │\n│   • Boundaries                 │\n│   • Functions                  │\n│   • Interfaces                 │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   2. Hazard Identification     │\n│   • Malfunctioning behavior    │\n│   • Hazard types               │\n│   • Brainstorming sessions     │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   3. Situation Analysis        │\n│   • Operating scenarios        │\n│   • Driving conditions         │\n│   • Vehicle states             │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   4. Risk Classification       │\n│   • Severity (S0-S3)           │\n│   • Exposure (E0-E4)           │\n│   • Controllability (C0-C3)    │\n└────────────┬───────────────────┘\n             │\n             ▼\n┌────────────────────────────────┐\n│   5. ASIL Determination        │\n│   • Apply ASIL table           │\n│   • Document rationale         │\n│   • Define safety goals        │\n└────────────────────────────────┘\n```\n\n## Severity Classification (S)\n\n### S0: No Injuries\n\n**Definition:** No injuries occur\n\n**Examples:**\n- Infotainment system freeze (no impact on driving)\n- Interior courtesy light failure\n- Seat warmer malfunction\n- Radio reception loss\n- USB charging port failure\n\n**Typical Systems:**\n- Entertainment systems\n- Comfort features (non-critical)\n- Aesthetic lighting\n\n### S1: Light and Moderate Injuries\n\n**Definition:** Light and moderate injuries including at least one person with moderate injuries\n\n**Injury Examples:**\n- Whiplash\n- Minor bone fractures\n- Mild concussion\n- Bruises and contusions\n- Soft tissue injuries\n\n**Hazard Examples:**\n- Cruise control failure to disengage immediately (delay \u003C 2s)\n- Parking sensor false negative at very low speed (\u003C 5 km\u002Fh)\n- Window regulator unexpected movement during adjustment\n- Seat adjuster unintended movement while parked\n- HVAC blower maximum speed in hot conditions\n\n**Typical ASIL:** QM or ASIL A (depending on E and C)\n\n### S2: Severe and Life-Threatening Injuries\n\n**Definition:** Severe and life-threatening injuries (survival probable) to at least one person\n\n**Injury Examples:**\n- Severe bone fractures\n- Internal injuries\n- Severe head trauma (but survivable)\n- Multiple rib fractures\n- Spinal injuries (non-fatal)\n\n**Hazard Examples:**\n- Unintended acceleration (\u003C 50 km\u002Fh, short duration)\n- Steering system increased friction\u002Fresistance\n- Active suspension failure causing vehicle instability\n- Lane keeping assist unintended steering intervention\n- Automatic emergency braking false activation at moderate speed\n- Airbag non-deployment in moderate-speed collision\n\n**Typical ASIL:** ASIL B or C (depending on E and C)\n\n### S3: Life-Threatening and Fatal Injuries\n\n**Definition:** Life-threatening injuries (survival uncertain) or fatal injuries to at least one person\n\n**Injury Examples:**\n- Severe head trauma (likely fatal)\n- Multiple severe internal injuries\n- Severe burns\n- Fatal collision impact\n- Ejection from vehicle\n\n**Hazard Examples:**\n- Total brake system failure at highway speed\n- Unintended full acceleration at highway speed\n- Complete steering loss\n- Airbag inadvertent deployment while driving\n- Electronic stability control (ESC) unintended strong intervention\n- Electric vehicle high-voltage shock to occupants\n- Autonomous emergency steering wrong direction into oncoming traffic\n\n**Typical ASIL:** ASIL C or D (depending on E and C)\n\n## Exposure Classification (E)\n\n### E0: Incredibly Unlikely\n\n**Definition:** Operational situation occurs less than 0.1% of average operating time\n\n**Examples:**\n- Manufacturing test mode only\n- Service\u002Fdiagnostic mode (dealer access)\n- Valet parking mode with specific conditions\n- Trailer tow mode on vehicles rarely towing\n- Extreme weather mode (desert\u002Farctic) for temperate regions\n\n**Annual Occurrence:** Less than 1 hour per year\n\n### E1: Very Low Probability\n\n**Definition:** 0.1% to 1% of average operating time\n\n**Examples:**\n- Parallel parking maneuvers\n- Reverse gear operation\n- Hill start scenarios\n- Car wash mode\n- Off-road driving (for on-road vehicles)\n- Mountain driving with steep grades\n\n**Annual Occurrence:** 10 to 100 hours per year\n\n### E2: Low Probability\n\n**Definition:** 1% to 10% of average operating time\n\n**Examples:**\n- City\u002Furban driving\n- Stop-and-go traffic\n- Residential area driving\n- Parking lot navigation\n- School zone driving\n- Weather: rain\u002Fsnow conditions\n\n**Annual Occurrence:** 100 to 1000 hours per year\n\n### E3: Medium Probability\n\n**Definition:** 10% to 50% of average operating time\n\n**Examples:**\n- Rural road driving\n- Suburban driving\n- Two-lane highways\n- Curved roads\n- Night driving\n- Mixed traffic conditions\n\n**Annual Occurrence:** 1000 to 5000 hours per year\n\n### E4: High Probability\n\n**Definition:** More than 50% of average operating time\n\n**Examples:**\n- Highway\u002Fmotorway cruising\n- Straight road driving\n- High-speed driving (> 100 km\u002Fh)\n- Daytime driving\n- Normal weather conditions\n- Multiple occupants in vehicle\n\n**Annual Occurrence:** More than 5000 hours per year\n\n**Note:** Average vehicle operation ~10,000 hours over 10-year life\n\n## Controllability Classification (C)\n\n### C0: Controllable in General\n\n**Definition:** More than 99% of all drivers can act to prevent harm in at least 99% of situations\n\n**Characteristics:**\n- Very obvious to driver\n- Ample time to react\n- Simple corrective action\n- Multiple sensory cues\n- Minimal skill required\n\n**Examples:**\n- Single windshield wiper stops (one still works)\n- Headlight intensity reduction (not complete failure)\n- Fuel gauge inaccuracy (range warning still works)\n- Seat heater temperature slightly off target\n- Radio volume sudden change\n\n**Driver Action Required:** Simple compensation, obvious detection\n\n### C1: Simply Controllable\n\n**Definition:** At least 99% of all drivers can act to prevent harm in at least 99% of situations\n\n**Characteristics:**\n- Easily noticeable\n- Adequate time to react (> 5 seconds)\n- Straightforward corrective action\n- Clear sensory feedback\n- Average driver skill sufficient\n\n**Examples:**\n- ABS degradation (single wheel)\n- Power steering assist reduction (not loss)\n- Cruise control requiring multiple attempts to cancel\n- Automatic transmission delayed shift (\u003C 2s)\n- Tire pressure monitoring false warning\n- Parking brake electronic release delay\n\n**Driver Action Required:** Simple reaction, average skill level\n\n### C2: Normally Controllable\n\n**Definition:** At least 90% of all drivers can act to prevent harm in at least 90% of situations\n\n**Characteristics:**\n- Noticeable with attention\n- Limited time to react (1-5 seconds)\n- Requires skilled driver response\n- May need trained reaction\n- Familiar driving maneuver needed\n\n**Examples:**\n- Power steering complete loss (at speed)\n- ABS complete failure (manual braking only)\n- ESC degraded performance (reduced intervention)\n- Traction control sporadic operation\n- Engine power reduction (not total loss)\n- Automatic transmission stuck in gear\n- Regenerative braking unexpected increase\n\n**Driver Action Required:** Skilled driving, immediate attention\n\n### C3: Difficult to Control or Uncontrollable\n\n**Definition:** Less than 90% of all drivers can act to prevent harm in less than 90% of situations\n\n**Characteristics:**\n- May not be noticeable immediately\n- Very short reaction time (\u003C 1 second)\n- Requires expert driver skill\n- Counterintuitive response needed\n- Physical limitations (strength\u002Freflex)\n- Multiple simultaneous failures\n\n**Examples:**\n- Total brake failure (all systems)\n- Steering complete lockup at highway speed\n- Unintended full acceleration at highway speed\n- ESC unintended strong braking intervention in curve\n- Airbag inadvertent deployment while driving\n- All-wheel drive unintended torque split causing spin\n- Autonomous steering wrong direction at highway speed\n- Suspension sudden complete collapse\n\n**Driver Action Required:** Expert skill, may be uncontrollable\n\n## ASIL Determination Matrix\n\n### Complete ASIL Table\n\n```\n┌─────────┬──────────────────────────────────────────────────────────────┐\n│         │                    Controllability                           │\n│Severity │     C0                  C1                  C2        C3     │\n├─────────┼──────────────────────────────────────────────────────────────┤\n│   S1    │                                                              │\n│  E4     │     QM                  QM                  QM        A      │\n│  E3     │     QM                  QM                  QM        A      │\n│  E2     │     QM                  QM                  QM        QM     │\n│  E1     │     QM                  QM                  QM        QM     │\n├─────────┼──────────────────────────────────────────────────────────────┤\n│   S2    │                                                              │\n│  E4     │     QM                  A                   B         C      │\n│  E3     │     QM                  A                   B         C      │\n│  E2     │     QM                  QM                  A         B      │\n│  E1     │     QM                  QM                  QM        A      │\n├─────────┼──────────────────────────────────────────────────────────────┤\n│   S3    │                                                              │\n│  E4     │     A                   B                   C         D      │\n│  E3     │     A                   B                   C         D      │\n│  E2     │     QM                  A                   B         C      │\n│  E1     │     QM                  QM                  A         B      │\n└─────────┴──────────────────────────────────────────────────────────────┘\n```\n\n## HARA Worksheet Template\n\n### Electronic Stability Control (ESC) Example\n\n```yaml\nhara_id: \"HARA-ESC-001\"\nitem: \"Electronic Stability Control System\"\ndate: \"2024-03-19\"\nversion: \"1.0\"\nanalyst: \"Functional Safety Team\"\n\nitem_definition:\n  description: \"Electronic Stability Control (ESC) system that stabilizes the vehicle by applying individual wheel braking and reducing engine torque during oversteer\u002Fundersteer conditions\"\n  boundaries:\n    - ESC_ECU\n    - Wheel_speed_sensors (4x)\n    - Yaw_rate_sensor\n    - Lateral_acceleration_sensor\n    - Steering_angle_sensor\n    - Hydraulic_modulator_unit\n  operating_modes:\n    - ESC_active_mode\n    - ESC_off_mode (driver disabled)\n    - ABS_only_mode (ESC degraded)\n  assumptions:\n    - Driver_input_available\n    - Vehicle_in_motion\n    - Tire_grip_conditions_normal\n\nhazards:\n  - hazard_id: \"H-ESC-001\"\n    malfunctioning_behavior: \"Unintended ESC activation\"\n    description: \"ESC applies asymmetric braking when not needed\"\n\n    hazardous_events:\n      - event_id: \"HE-ESC-001-A\"\n        situation: \"Highway driving in straight line at high speed\"\n        operational_situation:\n          - Vehicle_speed: \"> 100 km\u002Fh\"\n          - Road_condition: \"Dry, straight highway\"\n          - Traffic: \"Dense traffic, nearby vehicles\"\n          - Driver_activity: \"Cruising, minimal steering input\"\n\n        severity: \"S3\"\n        severity_rationale: |\n          Unintended braking at one wheel at highway speed causes sudden\n          vehicle rotation. Driver and passengers face life-threatening\n          injuries from:\n          - Loss of control leading to collision with barriers\n          - Vehicle rollover potential\n          - Rear-end collision from following vehicles\n\n        exposure: \"E4\"\n        exposure_rationale: |\n          Highway driving accounts for > 50% of vehicle operating time for\n          typical usage. Straight-line cruising is the primary highway mode.\n          Estimated exposure: 60% of total driving time.\n\n        controllability: \"C3\"\n        controllability_rationale: |\n          At high speed (> 100 km\u002Fh), sudden asymmetric braking creates:\n          - Immediate yaw rotation (\u003C 500ms to loss of control)\n          - Counterintuitive response needed (accelerate to regain control)\n          - Physical limitation (steering correction requires high torque)\n          - \u003C 90% of drivers can successfully recover\n          - Professional driver training required for recovery\n\n        asil: \"ASIL-D\"\n\n        safety_goal:\n          sg_id: \"SG-ESC-001\"\n          description: \"Prevent unintended ESC activation\"\n          safe_state: \"ESC disabled, manual control\"\n          ftti: \"150 ms\"\n          verification:\n            - Fault_injection_testing\n            - Vehicle_dynamics_simulation\n            - Proving_ground_testing\n\n      - event_id: \"HE-ESC-001-B\"\n        situation: \"Low-speed parking maneuver\"\n        operational_situation:\n          - Vehicle_speed: \"\u003C 10 km\u002Fh\"\n          - Location: \"Parking lot\"\n          - Maneuver: \"Tight turn, sharp steering\"\n\n        severity: \"S1\"\n        severity_rationale: |\n          At low speed, unintended braking causes minor vehicle movement.\n          Potential for light injuries from sudden stop (whiplash).\n          Low collision energy.\n\n        exposure: \"E1\"\n        exposure_rationale: |\n          Parking maneuvers occur \u003C 1% of operating time.\n          Estimated: 50 hours per year.\n\n        controllability: \"C1\"\n        controllability_rationale: |\n          Low speed provides ample reaction time.\n          Simple corrective action: release accelerator, re-apply carefully.\n          99% of drivers can handle this situation.\n\n        asil: \"QM\"\n\n        safety_goal:\n          sg_id: \"None (QM)\"\n          description: \"Managed through quality management\"\n\n  - hazard_id: \"H-ESC-002\"\n    malfunctioning_behavior: \"ESC failure to activate\"\n    description: \"ESC does not intervene when vehicle is losing stability\"\n\n    hazardous_events:\n      - event_id: \"HE-ESC-002-A\"\n        situation: \"Cornering on wet highway exit ramp\"\n        operational_situation:\n          - Vehicle_speed: \"70 km\u002Fh\"\n          - Road_condition: \"Wet, curved ramp (radius 50m)\"\n          - Weather: \"Rain, reduced tire grip\"\n          - Lateral_acceleration: \"> 0.7g\"\n\n        severity: \"S3\"\n        severity_rationale: |\n          Without ESC intervention, vehicle enters uncontrolled oversteer:\n          - Spin into barrier or oncoming traffic\n          - Rollover potential for SUVs\n          - Life-threatening collision likely\n\n        exposure: \"E3\"\n        exposure_rationale: |\n          Highway exit ramps used in 10-50% of trips.\n          Wet conditions occur 15-20% of driving time.\n          Combined exposure: ~20% of operating time.\n\n        controllability: \"C2\"\n        controllability_rationale: |\n          Skilled driver can recover from initial oversteer:\n          - Counter-steer + throttle modulation\n          - Requires advanced car control knowledge\n          - 90% of drivers can recover if trained\n          - However, typical driver (no training) success rate \u003C 70%\n          - Conservative assessment: C2\n\n        asil: \"ASIL-C\"\n\n        safety_goal:\n          sg_id: \"SG-ESC-002\"\n          description: \"ESC shall activate when vehicle stability is compromised\"\n          safe_state: \"N\u002FA (function must remain available)\"\n          ftti: \"50 ms\"\n          verification:\n            - Skidpad_testing\n            - Wet_handling_course\n            - Professional_driver_evaluation\n\n  - hazard_id: \"H-ESC-003\"\n    malfunctioning_behavior: \"Delayed ESC response\"\n    description: \"ESC intervention delayed by > 500ms\"\n\n    hazardous_events:\n      - event_id: \"HE-ESC-003-A\"\n        situation: \"Emergency lane change at highway speed\"\n        operational_situation:\n          - Vehicle_speed: \"120 km\u002Fh\"\n          - Maneuver: \"Double lane change (obstacle avoidance)\"\n          - Road_condition: \"Dry highway\"\n\n        severity: \"S2\"\n        severity_rationale: |\n          Delayed ESC allows vehicle to exceed stability limits before\n          intervention. Results in:\n          - Severe over-rotation\n          - Adjacent lane encroachment\n          - Severe injuries probable, but typically survivable\n\n        exposure: \"E2\"\n        exposure_rationale: |\n          Emergency maneuvers occur infrequently: 1-10% of operating time.\n          Estimate: 200 hours per year across all driving.\n\n        controllability: \"C2\"\n        controllability_rationale: |\n          Delayed ESC reduces effectiveness but some correction provided.\n          Skilled driver can compensate with reduced ESC authority.\n          ~85% success rate with trained drivers.\n\n        asil: \"ASIL-B\"\n\n        safety_goal:\n          sg_id: \"SG-ESC-003\"\n          description: \"ESC response time shall be \u003C 100ms from instability detection\"\n          safe_state: \"Graceful degradation to ABS-only\"\n          ftti: \"100 ms\"\n          verification:\n            - Real-time_latency_measurement\n            - HIL_testing_with_vehicle_dynamics_model\n\nsummary:\n  total_hazards: 3\n  total_hazardous_events: 5\n  asil_distribution:\n    asil_d: 1\n    asil_c: 1\n    asil_b: 1\n    asil_a: 0\n    qm: 2\n  highest_asil: \"ASIL-D\"\n  safety_goals_required: 3\n```\n\n## Advanced HARA Techniques\n\n### Situation Analysis Matrix\n\n**Multi-Dimensional Situation Space:**\n\n```\nDimension 1: Vehicle Speed\n├── 0-10 km\u002Fh (parking)\n├── 10-50 km\u002Fh (urban)\n├── 50-100 km\u002Fh (rural)\n└── > 100 km\u002Fh (highway)\n\nDimension 2: Road Conditions\n├── Dry\n├── Wet\n├── Snow\u002FIce\n└── Off-road\n\nDimension 3: Traffic Density\n├── No traffic\n├── Light traffic\n├── Dense traffic\n└── Traffic jam\n\nDimension 4: Driver State\n├── Attentive\n├── Distracted\n├── Drowsy\n└── Impaired (medical emergency)\n\nDimension 5: Time of Day\n├── Day (good visibility)\n├── Dusk\u002Fdawn (reduced visibility)\n└── Night (limited visibility)\n```\n\n**Coverage Matrix Example:**\n```\nSpeed vs Road Conditions:\n\n         │ Dry │ Wet │Snow │ Ice │\n─────────┼─────┼─────┼─────┼─────┤\n0-10km\u002Fh │  ✓  │  ✓  │  ✓  │  ✓  │\n10-50    │  ✓  │  ✓  │  ✓  │  ✓  │\n50-100   │  ✓  │  ✓  │  ✓  │  -  │\n>100km\u002Fh │  ✓  │  ✓  │  -  │  -  │\n\n✓ = Situation analyzed\n- = Situation not applicable (speed limits)\n```\n\n### Controllability Assessment Methods\n\n**Method 1: Expert Judgment**\n- Panel of experienced drivers\n- Simulator testing with representative population\n- Statistical analysis of crash avoidance rates\n\n**Method 2: Accident Statistics**\n- Historical crash data analysis\n- Similar malfunction scenarios\n- Injury severity correlation\n\n**Method 3: Simulator Studies**\n```python\n# Controllability test protocol\ntest_setup = {\n    'participants': 100,  # Diverse driver population\n    'age_range': (18, 75),\n    'experience_range': (1, 50),  # years driving\n    'scenarios': 20,  # per hazardous event\n    'success_criteria': 'No collision AND vehicle stable'\n}\n\n# Classification\nif success_rate > 0.99:\n    controllability = \"C0\"\nelif success_rate >= 0.99:\n    controllability = \"C1\"\nelif success_rate >= 0.90:\n    controllability = \"C2\"\nelse:\n    controllability = \"C3\"\n```\n\n### Exposure Data Collection\n\n**Data Sources:**\n1. **Naturalistic Driving Studies**\n   - Real-world driving data\n   - GPS logging\n   - CAN bus data collection\n   - 100+ vehicles over 1+ years\n\n2. **Fleet Telemetry**\n   - Connected vehicle data\n   - Aggregate usage patterns\n   - Scenario frequency statistics\n\n3. **Statistical Databases**\n   - NHTSA (US)\n   - GIDAS (Germany)\n   - STATS19 (UK)\n\n**Exposure Calculation Example:**\n```python\n# Calculate exposure for \"highway driving > 100 km\u002Fh\"\ndef calculate_exposure(telemetry_data):\n    total_hours = sum(trip.duration for trip in telemetry_data)\n    highway_hours = sum(\n        trip.duration\n        for trip in telemetry_data\n        if trip.speed > 100 and trip.road_type == 'highway'\n    )\n\n    exposure_percentage = (highway_hours \u002F total_hours) * 100\n\n    # Map to E-class\n    if exposure_percentage \u003C 0.1:\n        return \"E0\"\n    elif exposure_percentage \u003C 1:\n        return \"E1\"\n    elif exposure_percentage \u003C 10:\n        return \"E2\"\n    elif exposure_percentage \u003C 50:\n        return \"E3\"\n    else:\n        return \"E4\"\n\n# Example data\ntelemetry = [\n    {'duration': 120, 'speed': 110, 'road_type': 'highway'},  # 2 hours\n    {'duration': 30, 'speed': 40, 'road_type': 'urban'},      # 0.5 hours\n    {'duration': 50, 'speed': 80, 'road_type': 'rural'},      # 0.83 hours\n    # ... 1000s more trips\n]\n\nexposure_class = calculate_exposure(telemetry)\n```\n\n## HARA Documentation\n\n### Safety Case Integration\n\n```markdown\n# Safety Case Section: HARA Evidence\n\n## 1. Completeness Argument\n\n**Claim:** All relevant hazards have been identified for the ESC system.\n\n**Evidence:**\n- E1: HARA workshop with cross-functional team (attendees: safety engineer,\n      system engineer, test engineer, domain expert)\n- E2: Review of similar system hazards from database (23 ESC systems analyzed)\n- E3: Historical accident data review (GIDAS database, 1000+ ESC-related incidents)\n- E4: FMEA results cross-checked with HARA hazard list\n- E5: Independent safety assessment review confirmation\n\n**Sub-Claim 1.1:** Malfunction types cover all failure modes\n**Sub-Claim 1.2:** Operating situations cover representative vehicle usage\n\n## 2. Classification Accuracy Argument\n\n**Claim:** Severity, Exposure, and Controllability classifications are justified.\n\n**Evidence:**\n- E6: Severity based on MAIS (Maximum Abbreviated Injury Scale) correlation\n- E7: Exposure derived from 500-vehicle naturalistic driving study (12 months)\n- E8: Controllability validated through driving simulator study (N=120 drivers)\n- E9: Expert panel review of all classifications (unanimous agreement)\n\n## 3. ASIL Determination Argument\n\n**Claim:** ASIL assignments correctly follow ISO 26262-3 table.\n\n**Evidence:**\n- E10: ASIL determination matrix applied consistently to all hazardous events\n- E11: Independent verification of ASIL assignments (0 discrepancies)\n- E12: Traceability from S\u002FE\u002FC to ASIL documented in HARA database\n```\n\n### Review Checklist\n\n**HARA Quality Review:**\n\n- [ ] Item definition complete and approved\n- [ ] All operating modes considered\n- [ ] Hazards derived from malfunctioning behavior (not internal faults)\n- [ ] Operational situations representative and complete\n- [ ] Severity classification justified with injury mechanism\n- [ ] Exposure based on quantitative data (not assumptions)\n- [ ] Controllability assessed with driver population consideration\n- [ ] ASIL determination traceable to S\u002FE\u002FC\n- [ ] Safety goals defined for all ASIL hazards\n- [ ] Safe state specified for each safety goal\n- [ ] FTTI specified and justified\n- [ ] Cross-check with FMEA\u002FFTA performed\n- [ ] Independent review completed\n- [ ] All findings from reviews addressed\n- [ ] HARA approved by functional safety manager\n\n## Production-Ready Templates\n\n### HARA Database Schema (SQL)\n\n```sql\n-- Items table\nCREATE TABLE Items (\n    item_id VARCHAR(50) PRIMARY KEY,\n    item_name VARCHAR(200),\n    description TEXT,\n    version VARCHAR(20),\n    status VARCHAR(20),\n    created_date DATE,\n    updated_date DATE\n);\n\n-- Hazards table\nCREATE TABLE Hazards (\n    hazard_id VARCHAR(50) PRIMARY KEY,\n    item_id VARCHAR(50) REFERENCES Items(item_id),\n    malfunctioning_behavior TEXT,\n    description TEXT,\n    identified_by VARCHAR(100),\n    identified_date DATE\n);\n\n-- Hazardous Events table\nCREATE TABLE HazardousEvents (\n    event_id VARCHAR(50) PRIMARY KEY,\n    hazard_id VARCHAR(50) REFERENCES Hazards(hazard_id),\n    situation_description TEXT,\n    operational_situation JSONB,\n    severity VARCHAR(2),\n    severity_rationale TEXT,\n    exposure VARCHAR(2),\n    exposure_rationale TEXT,\n    controllability VARCHAR(2),\n    controllability_rationale TEXT,\n    asil VARCHAR(6),\n    review_status VARCHAR(20),\n    reviewer VARCHAR(100),\n    review_date DATE\n);\n\n-- Safety Goals table\nCREATE TABLE SafetyGoals (\n    sg_id VARCHAR(50) PRIMARY KEY,\n    event_id VARCHAR(50) REFERENCES HazardousEvents(event_id),\n    description TEXT,\n    safe_state TEXT,\n    ftti_ms INT,\n    asil VARCHAR(6),\n    status VARCHAR(20),\n    approved_by VARCHAR(100),\n    approved_date DATE\n);\n\n-- Exposure Data table (for evidence)\nCREATE TABLE ExposureData (\n    data_id SERIAL PRIMARY KEY,\n    event_id VARCHAR(50) REFERENCES HazardousEvents(event_id),\n    data_source VARCHAR(200),\n    measurement_value DECIMAL,\n    measurement_unit VARCHAR(50),\n    collection_date DATE,\n    sample_size INT,\n    notes TEXT\n);\n\n-- Query: Generate HARA report for ASIL-D events\nSELECT\n    h.hazard_id,\n    h.malfunctioning_behavior,\n    he.event_id,\n    he.situation_description,\n    he.severity,\n    he.exposure,\n    he.controllability,\n    he.asil,\n    sg.description AS safety_goal,\n    sg.ftti_ms\nFROM Hazards h\nJOIN HazardousEvents he ON h.hazard_id = he.hazard_id\nJOIN SafetyGoals sg ON he.event_id = sg.event_id\nWHERE he.asil = 'ASIL-D'\nORDER BY h.hazard_id;\n```\n\n### Excel HARA Template\n\n```\nSheet 1: Item Definition\n├── A: Item ID\n├── B: Item Name\n├── C: Description\n├── D: Boundaries\n├── E: Operating Modes\n└── F: Assumptions\n\nSheet 2: HARA Worksheet\n├── A: Hazard ID\n├── B: Malfunctioning Behavior\n├── C: Hazardous Event ID\n├── D: Operational Situation\n├── E: Severity (dropdown: S0-S3)\n├── F: Severity Rationale\n├── G: Exposure (dropdown: E0-E4)\n├── H: Exposure Rationale\n├── I: Controllability (dropdown: C0-C3)\n├── J: Controllability Rationale\n├── K: ASIL (formula: =VLOOKUP(...))\n└── L: Safety Goal ID\n\nSheet 3: ASIL Lookup Table\n└── Automated ASIL determination matrix\n\nSheet 4: Safety Goals\n├── A: Safety Goal ID\n├── B: Safety Goal Description\n├── C: Safe State\n├── D: FTTI (ms)\n└── E: Verification Methods\n\nSheet 5: Evidence\n├── A: Event ID\n├── B: Evidence Type (S\u002FE\u002FC)\n├── C: Data Source\n├── D: Reference Document\n└── E: Attachment\n```\n\n## References\n\n- ISO 26262-3:2018 - Concept Phase\n- SAE J2980 - Considerations for ISO 26262 ASIL Hazard Classification\n- ISO\u002FTR 4804 - Safety and cybersecurity for automated driving systems\n- GIDAS (German In-Depth Accident Study)\n- NHTSA CIREN (Crash Injury Research Engineering Network)\n\n## Related Skills\n\n- ISO 26262 Overview\n- Safety Mechanisms and Patterns\n- FMEA\u002FFTA Analysis\n- Safety Verification and Validation\n- Functional Safety Concept Development\n\n---\n\n## Iso 26262 Overview\n\n# ISO 26262 Overview - Functional Safety in Automotive\n\nComprehensive guidance on ISO 26262 standard for functional safety of electrical\u002Felectronic (E\u002FE) systems in road vehicles, covering all 12 parts, V-model lifecycle, ASIL determination, and safety concept development.\n\n## ISO 26262 Standard Structure\n\n### 12 Parts Overview\n\n**Part 1: Vocabulary**\n- Defines 200+ terms used throughout the standard\n- Key terms: ASIL, safety goal, fault, failure, safe state, FTTI, PMHF\n\n**Part 2: Management of Functional Safety**\n- Safety lifecycle management\n- Safety culture and organizational structure\n- Competence management and training\n- Quality management integration\n\n**Part 3: Concept Phase**\n- Item definition\n- Hazard Analysis and Risk Assessment (HARA)\n- Functional safety concept\n- Safety goals and ASIL determination\n\n**Part 4: Product Development at System Level**\n- Technical safety concept\n- System design and architecture\n- Verification and validation planning\n- Safety requirements allocation\n\n**Part 5: Product Development at Hardware Level**\n- Hardware safety requirements\n- Hardware design and implementation\n- Hardware architectural metrics\n- Random hardware failures (PMHF calculation)\n\n**Part 6: Product Development at Software Level**\n- Software safety requirements\n- Software architectural design\n- Software unit design and implementation\n- Software testing (unit, integration, system)\n\n**Part 7: Production, Operation, Service, Decommissioning**\n- Production planning and control\n- Field monitoring and customer support\n- Safety-related maintenance\n- Decommissioning procedures\n\n**Part 8: Supporting Processes**\n- Configuration management\n- Change management\n- Verification methods\n- Documentation standards\n- Confidence in use (reuse of components)\n\n**Part 9: ASIL-Oriented and Safety-Oriented Analyses**\n- Dependent failure analysis (DFA)\n- FMEA\u002FFMEDA methodologies\n- FTA (Fault Tree Analysis)\n- Safety analysis methods\n\n**Part 10: Guidelines**\n- Informative guidance on applying the standard\n- Examples and best practices\n- Interpretation clarifications\n\n**Part 11: Semiconductors**\n- Safety requirements for semiconductor components\n- Random hardware failures in ICs\n- Systematic capability\n- Safety manual requirements\n\n**Part 12: Motorcycles**\n- Adaptation of standard for motorcycles\n- Specific hazard scenarios\n- Controllability considerations for two-wheeled vehicles\n\n## V-Model Safety Lifecycle\n\n### Left Side (Decomposition)\n\n```\n┌─────────────────────────────────────────────┐\n│         Concept Phase (Part 3)              │\n│  • Item Definition                          │\n│  • HARA → Safety Goals → ASIL               │\n│  • Functional Safety Concept                │\n└────────────────┬────────────────────────────┘\n                 │\n                 ▼\n┌─────────────────────────────────────────────┐\n│    System Design (Part 4)                   │\n│  • Technical Safety Concept                 │\n│  • System Architecture                      │\n│  • Safety Requirements Allocation           │\n└────────┬──────────────────┬─────────────────┘\n         │                  │\n         ▼                  ▼\n┌──────────────────┐  ┌──────────────────────┐\n│  HW Design       │  │  SW Design           │\n│  (Part 5)        │  │  (Part 6)            │\n│  • HW Safety Req │  │  • SW Safety Req     │\n│  • HW Arch       │  │  • SW Arch           │\n│  • HW Design     │  │  • SW Unit Design    │\n└────────┬─────────┘  └──────────┬───────────┘\n         │                       │\n         ▼                       ▼\n┌──────────────────┐  ┌──────────────────────┐\n│  HW Implement    │  │  SW Implement        │\n│  • PCB Design    │  │  • Coding            │\n│  • Component     │  │  • Unit Testing      │\n└────────┬─────────┘  └──────────┬───────────┘\n         │                       │\n         └───────────┬───────────┘\n                     │\n```\n\n### Right Side (Integration & Verification)\n\n```\n                     │\n                     ▼\n┌─────────────────────────────────────────────┐\n│    HW\u002FSW Integration (Part 6)               │\n│  • Integration Testing                      │\n│  • Interface Verification                   │\n│  • Safety Mechanism Testing                 │\n└────────────────┬────────────────────────────┘\n                 │\n                 ▼\n┌─────────────────────────────────────────────┐\n│    System Integration (Part 4)              │\n│  • System Testing                           │\n│  • Safety Validation                        │\n│  • FTTI Verification                        │\n└────────────────┬────────────────────────────┘\n                 │\n                 ▼\n┌─────────────────────────────────────────────┐\n│    Vehicle Integration (Part 4)             │\n│  • Vehicle-level Testing                    │\n│  • Safety Goal Verification                 │\n│  • Release for Production                   │\n└─────────────────────────────────────────────┘\n```\n\n## ASIL Determination\n\n### Hazard Classification Parameters\n\n**Severity (S) - Impact of hazardous event**\n\n| Class | Description | Example |\n|-------|-------------|---------|\n| S0 | No injuries | Minor annoyance (wiper malfunction) |\n| S1 | Light\u002Fmoderate injuries | Airbag non-deployment in low-speed collision |\n| S2 | Severe\u002Flife-threatening injuries | Unintended braking at highway speed |\n| S3 | Life-threatening\u002Ffatal injuries | Total brake failure at highway speed |\n\n**Exposure (E) - Probability of operational situation**\n\n| Class | Description | Probability | Example |\n|-------|-------------|-------------|---------|\n| E0 | Incredibly unlikely | \u003C 0.1% of operating time | Test mode only |\n| E1 | Very low probability | 0.1% to 1% | Parking maneuvers |\n| E2 | Low probability | 1% to 10% | City driving |\n| E3 | Medium probability | 10% to 50% | Rural roads |\n| E4 | High probability | > 50% | Highway cruising |\n\n**Controllability (C) - Driver's ability to avoid harm**\n\n| Class | Description | Driver Action | Example |\n|-------|-------------|---------------|---------|\n| C0 | Controllable in general | Simple avoidance | Single wiper inoperative |\n| C1 | Simply controllable | 99% can avoid | ABS degradation (one wheel) |\n| C2 | Normally controllable | 90% can avoid | Power steering assist loss |\n| C3 | Difficult\u002Funcontrollable | \u003C 90% can avoid | Total brake failure |\n\n### ASIL Determination Table\n\n```\nSeverity │  Exposure    Controllability\n    S    │  E4 E3 E2 E1 │  C1    C2    C3\n─────────┼──────────────┼────────────────────\n   S1    │  A  A  QM QM │  QM    QM    A\n   S2    │  B  B  A  A  │  A     B     C\n   S3    │  C  C  B  B  │  B     C     D\n```\n\nLegend:\n- **QM**: Quality Management only (no ASIL required)\n- **ASIL A**: Lowest safety integrity\n- **ASIL B**: Medium-low safety integrity\n- **ASIL C**: Medium-high safety integrity\n- **ASIL D**: Highest safety integrity\n\n### ASIL Requirements Summary\n\n| Aspect | ASIL QM | ASIL A | ASIL B | ASIL C | ASIL D |\n|--------|---------|--------|--------|--------|--------|\n| Software Unit Testing | Recommended | + (some coverage) | ++ (branch coverage) | +++ (MC\u002FDC) | +++ (MC\u002FDC + boundary) |\n| Static Code Analysis | Optional | + | ++ | +++ | +++ |\n| Code Reviews | Basic | + | ++ | +++ | +++ |\n| FMEA | Optional | + | ++ | +++ | +++ |\n| FTA | Not required | Optional | + | ++ | +++ |\n| Hardware Diagnostic Coverage | None | > 60% | > 80% | > 90% | > 99% |\n| PMHF Target | N\u002FA | \u003C 1000 FIT | \u003C 100 FIT | \u003C 100 FIT | \u003C 10 FIT |\n\n## Safety Goal Development\n\n### Item Definition Template\n\n```yaml\nitem_name: \"Electronic Stability Control (ESC)\"\nitem_id: \"ESC-001\"\nboundaries:\n  physical:\n    - ECU_ESC_main\n    - Wheel_speed_sensors x4\n    - Steering_angle_sensor\n    - Yaw_rate_sensor\n    - Lateral_acceleration_sensor\n    - Hydraulic_modulator\n  functional:\n    - Vehicle_dynamics_control\n    - Brake_pressure_modulation\n    - Engine_torque_reduction\n  interfaces:\n    - CAN_powertrain (500 kbps)\n    - CAN_chassis (500 kbps)\n    - LIN_sensors (19.2 kbps)\n    - Brake_pressure_lines (hydraulic)\nassumptions:\n  - Tire_grip_coefficient > 0.3\n  - Sensor_supply_voltage: 5V ± 0.25V\n  - Operating_temperature: -40°C to +85°C\n  - Vehicle_speed: 0 to 200 km\u002Fh\ndependencies:\n  - ABS_system (provides wheel speed data)\n  - Engine_control (accepts torque reduction commands)\n  - Brake_system (hydraulic pressure supply)\n```\n\n### Safety Goal Template\n\n```yaml\nsafety_goal_id: \"SG-ESC-001\"\nitem: \"ESC-001\"\nhazard: \"Unintended ESC activation causing loss of vehicle control\"\nhazardous_event: \"ESC applies asymmetric braking while cornering at highway speed\"\nasil: \"ASIL-D\"\nasil_derivation:\n  severity: \"S3\"  # Life-threatening\n  exposure: \"E4\"  # Highway driving > 50% of time\n  controllability: \"C3\"  # Difficult to control at high speed\nsafety_state: \"ESC_disabled_safe_mode\"\nftti: \"150 ms\"  # Fault Tolerant Time Interval\nsafe_state_description: |\n  ESC system transitions to disabled state where:\n  - No brake pressure modulation occurs\n  - Driver has full manual braking control\n  - Warning lamp illuminated\n  - DTC stored for service\n  - Base ABS functionality maintained\nverification_criteria:\n  - No_unintended_ESC_activation_in_1000_test_runs\n  - FTTI_verified_through_fault_injection\n  - Safe_state_reached_within_150ms\n  - Warning_lamp_activation_confirmed\n```\n\n## Functional Safety Concept\n\n### Safety Requirements Allocation\n\n**Functional Safety Requirement (FSR) Example:**\n\n```yaml\nfsr_id: \"FSR-ESC-001.1\"\nsafety_goal: \"SG-ESC-001\"\ndescription: \"Detect yaw rate sensor plausibility failure\"\nrationale: \"Invalid yaw rate data can cause false ESC activation\"\nallocation: \"System-level (ESC ECU)\"\nasil: \"ASIL-D\"\nverification_method:\n  - Software_unit_test\n  - Hardware-in-loop (HIL) test\n  - Fault_injection_test\nsafety_mechanism: \"SM-ESC-YAW-001 (Yaw rate plausibility check)\"\n```\n\n**Safety Mechanism Types:**\n\n1. **Detection**: Identify faults\n   - Range checks\n   - Plausibility checks\n   - Watchdogs\n   - CRC\u002Fchecksum\n\n2. **Control**: Transition to safe state\n   - Redundant channels\n   - Voting mechanisms\n   - Graceful degradation\n   - Fail-silent\u002Ffail-operational\n\n3. **Warning**: Alert driver\u002Fsystem\n   - Warning lamps\n   - Acoustic signals\n   - Haptic feedback\n   - DTC logging\n\n## Technical Safety Concept\n\n### Safety Architecture Patterns\n\n**1. Homogeneous Redundancy (1oo2)**\n```\nSensor A ──┐\n           ├──> Voter ──> Actuator\nSensor B ──┘\n```\n- Identical sensors\n- ASIL-B each → ASIL-D combined\n- Common cause failure analysis required\n\n**2. Heterogeneous Redundancy**\n```\nRadar ────┐\n          ├──> Fusion ──> Decision\nCamera ───┘\n```\n- Different physical principles\n- Better independence\n- ASIL decomposition possible\n\n**3. Monitoring Architecture (1oo1D)**\n```\nMain Channel ────────> Actuator\n                        ^\n                        │\n                    Monitor\n```\n- Main channel + diagnostic coverage\n- ASIL decomposition: ASIL-D(D) → ASIL-B(D) + ASIL-A(D)\n\n## ASIL Decomposition\n\n### Decomposition Rules\n\n**Valid ASIL-D Decomposition:**\n- ASIL-D(D) = ASIL-C(D) + ASIL-A(D)\n- ASIL-D(D) = ASIL-B(D) + ASIL-B(D)\n- ASIL-D(D) = ASIL-B(D) + ASIL-A(D) [with additional safety mechanisms]\n\n**Requirements:**\n1. Elements must be sufficiently independent\n2. Both elements monitored for failures\n3. Dependent failures analyzed (DFA)\n4. Common cause failures addressed\n5. No single point of failure\n\n**Example - Brake-by-Wire ASIL-D Decomposition:**\n\n```yaml\nsafety_requirement: \"Brake_command_processing\"\noriginal_asil: \"ASIL-D(D)\"\ndecomposition:\n  element_1:\n    function: \"Primary_brake_command_path\"\n    asil: \"ASIL-B(D)\"\n    implementation: \"Microcontroller_core_0\"\n    safety_mechanisms:\n      - Program_flow_monitoring\n      - RAM_test\n      - CRC_on_commands\n  element_2:\n    function: \"Secondary_brake_command_path\"\n    asil: \"ASIL-B(D)\"\n    implementation: \"Microcontroller_core_1\"\n    safety_mechanisms:\n      - Dual_core_lockstep\n      - Cross_comparison\n      - Watchdog\nindependence_measures:\n  - Separate_memory_partitions\n  - Separate_power_supplies\n  - Different_code_implementations\n  - Independent_watchdogs\ndependent_failure_analysis:\n  - EMI_susceptibility_analyzed\n  - Common_power_rail_protected\n  - Temperature_effects_mitigated\n```\n\n## Safety Validation\n\n### Validation Methods by ASIL\n\n| Method | ASIL A | ASIL B | ASIL C | ASIL D |\n|--------|--------|--------|--------|--------|\n| Requirements review | + | ++ | ++ | +++ |\n| Design review | + | ++ | +++ | +++ |\n| Simulation testing | + | ++ | +++ | +++ |\n| Prototype testing | ++ | +++ | +++ | +++ |\n| Field testing | ++ | +++ | +++ | +++ |\n| Fault injection | Optional | + | ++ | +++ |\n| Back-to-back comparison | Optional | + | ++ | +++ |\n\n### Safety Case Structure\n\n```\nSafety Case Document\n├── 1. Item Definition\n│   ├── System boundaries\n│   ├── Assumptions\n│   └── Dependencies\n├── 2. Hazard Analysis (HARA)\n│   ├── Hazard identification\n│   ├── Risk assessment (S, E, C)\n│   └── ASIL determination\n├── 3. Safety Goals\n│   ├── Safety goal definition\n│   ├── Safe state definition\n│   └── FTTI specification\n├── 4. Functional Safety Concept\n│   ├── Functional safety requirements\n│   ├── Safety mechanisms\n│   └── Requirement allocation\n├── 5. Technical Safety Concept\n│   ├── Safety architecture\n│   ├── Technical safety requirements\n│   └── HW\u002FSW allocation\n├── 6. Safety Analysis\n│   ├── FMEA\u002FFMEDA results\n│   ├── FTA results\n│   ├── DFA results\n│   └── PMHF calculation\n├── 7. Verification Evidence\n│   ├── Test results\n│   ├── Review records\n│   └── Analysis reports\n├── 8. Validation Evidence\n│   ├── Safety goal verification\n│   ├── FTTI verification\n│   └── Field data\n└── 9. Confirmation Measures\n    ├── Functional safety audit\n    ├── Independent assessment\n    └── Confirmation review\n```\n\n## Key Metrics and Targets\n\n### Hardware Metrics\n\n**Single-Point Fault Metric (SPFM)**\n```\nSPFM = (1 - ΣλSPF \u002F ΣλTotal) × 100%\n\nTarget:\n- ASIL B: > 90%\n- ASIL C: > 97%\n- ASIL D: > 99%\n```\n\n**Latent Fault Metric (LFM)**\n```\nLFM = (1 - ΣλLF \u002F (ΣλLF + ΣλRF + ΣλDet)) × 100%\n\nTarget:\n- ASIL B: > 60%\n- ASIL C: > 80%\n- ASIL D: > 90%\n```\n\n**Probabilistic Metric for random Hardware Failures (PMHF)**\n```\nPMHF = Σ(λi × failure_rate) FIT\n\nTarget:\n- ASIL B: \u003C 100 FIT\n- ASIL C: \u003C 100 FIT\n- ASIL D: \u003C 10 FIT\n\nFIT = Failures In Time (1 FIT = 1 failure in 10⁹ hours)\n```\n\n### Software Metrics\n\n**MC\u002FDC Coverage (Modified Condition\u002FDecision Coverage)**\n- ASIL D requirement: 100% MC\u002FDC coverage\n- Critical software units only\n- Tool qualification required\n\n**Cyclomatic Complexity**\n- ASIL D recommendation: \u003C 10 per function\n- Rationale: Testability and maintainability\n\n## ISO 26262:2018 Updates\n\n### Changes from 2011 Edition\n\n1. **Semicond uctors** (New Part 11)\n   - Specific requirements for IC suppliers\n   - Safety Element out of Context (SEooC)\n   - Systematic capability determination\n\n2. **Motorcycles** (New Part 12)\n   - Adapted controllability classes\n   - Motorcycle-specific hazards\n   - Two-wheeler dynamics considerations\n\n3. **SOTIF Integration** (ISO 21448)\n   - Performance limitations\n   - Reasonably foreseeable misuse\n   - Validation of non-fault scenarios\n\n4. **Cybersecurity** (ISO 21434)\n   - Security interface with safety\n   - Threat analysis\n   - Secure development lifecycle\n\n5. **Agile Development**\n   - Guidance on iterative methods\n   - Sprint-based V-model\n   - Continuous integration considerations\n\n## Production Checklist\n\n### Phase Gate Criteria\n\n**Concept Phase Exit:**\n- [ ] Item definition approved\n- [ ] HARA completed and reviewed\n- [ ] Safety goals confirmed with ASIL\n- [ ] Functional safety concept defined\n- [ ] Safety plan approved\n\n**System Development Exit:**\n- [ ] Technical safety concept complete\n- [ ] System architecture defined\n- [ ] Safety requirements allocated to HW\u002FSW\n- [ ] Verification plan approved\n- [ ] Preliminary FMEA conducted\n\n**HW\u002FSW Development Exit:**\n- [ ] Detailed design complete\n- [ ] Implementation verified (unit tests)\n- [ ] Integration testing passed\n- [ ] Safety mechanisms validated\n- [ ] Code\u002Fdesign reviews complete\n\n**Integration Exit:**\n- [ ] System integration testing complete\n- [ ] Safety validation performed\n- [ ] FTTI verified through testing\n- [ ] Hardware metrics achieved (SPFM, LFM, PMHF)\n- [ ] Functional safety assessment passed\n\n**Production Release:**\n- [ ] Safety case complete\n- [ ] Independent safety assessment passed\n- [ ] Safety manual released\n- [ ] Production quality procedures established\n- [ ] Field monitoring plan in place\n\n## Tools and Compliance\n\n### Tool Qualification (ISO 26262-8)\n\n**Tool Confidence Levels (TCL)**\n\n| TCL | Tool Impact | Examples |\n|-----|-------------|----------|\n| TCL1 | No impact on safety | Documentation editors |\n| TCL2 | Can introduce errors | Compilers without verification |\n| TCL3 | High risk of undetected errors | Code generators, static analyzers |\n\n**Qualification Methods:**\n1. Increased confidence from use\n2. Validation of tool outputs\n3. Development per recognized standard\n4. Evaluation of tool development process\n\n### Recommended Tools\n\n**ASIL-D Qualified:**\n- MATLAB\u002FSimulink (with IEC Certification Kit)\n- SCADE Suite (qualified per ISO 26262)\n- TargetLink (qualified code generator)\n- Polyspace (static analyzer)\n- LDRA (unit test + coverage)\n- Vector CANoe\u002FCANalyzer (HIL testing)\n\n## References\n\n- ISO 26262-1:2018 to ISO 26262-12:2018 (full standard)\n- ISO\u002FPAS 21448:2019 (SOTIF - Safety of the Intended Functionality)\n- ISO\u002FSAE 21434:2021 (Cybersecurity for road vehicles)\n- ASPICE 3.1 (Automotive SPICE)\n- MISRA C:2012 \u002F MISRA C++:2008 (coding guidelines)\n- SEooC (Safety Element out of Context) guidelines\n\n## Related Skills\n\n- Hazard Analysis and Risk Assessment (HARA)\n- Safety Mechanisms and Patterns\n- FMEA\u002FFTA Analysis\n- Software Safety Requirements\n- Safety Verification and Validation\n\n---\n\n## Safety Mechanisms Patterns\n\n# Safety Mechanisms and Patterns for ISO 26262\n\nComprehensive catalog of safety mechanisms for ASIL-D automotive systems, including redundancy patterns, diagnostic coverage techniques, watchdogs, memory protection, CRC\u002Fchecksums, plausibility checks, and safe state management.\n\n## Safety Mechanism Categories\n\n### Detection Mechanisms\n- Identify faults before they cause failures\n- Achieve diagnostic coverage targets\n- Enable transition to safe state within FTTI\n\n### Control Mechanisms\n- Manage system behavior during faults\n- Implement redundancy and voting\n- Provide graceful degradation paths\n\n### Warning Mechanisms\n- Alert driver\u002Fsystem to faults\n- Trigger DTC storage\n- Activate warning lamps\u002Fsignals\n\n## Redundancy Patterns\n\n### 1. Homogeneous Redundancy (1oo2)\n\n**One-out-of-Two Configuration:**\n\n```\n┌──────────┐\n│ Sensor A │─────┐\n└──────────┘     │      ┌────────┐     ┌──────────┐\n                 ├─────>│ Voter  │────>│ Actuator │\n┌──────────┐     │      └────────┘     └──────────┘\n│ Sensor B │─────┘\n└──────────┘\n```\n\n**Characteristics:**\n- Two identical channels (same design, same component)\n- Any one channel can drive the system\n- ASIL decomposition: ASIL-D(D) = ASIL-B(D) + ASIL-B(D)\n- Requires dependent failure analysis (common cause)\n\n**C Implementation:**\n```c\n\u002F\u002F 1oo2 redundant sensor processing\ntypedef struct {\n    float sensor_a_value;\n    float sensor_b_value;\n    bool sensor_a_valid;\n    bool sensor_b_valid;\n    uint32_t fault_counter_a;\n    uint32_t fault_counter_b;\n} RedundantSensor_t;\n\ntypedef enum {\n    VOTER_OUTPUT_VALID,\n    VOTER_OUTPUT_DEGRADED,\n    VOTER_OUTPUT_FAULT\n} VoterStatus_t;\n\nVoterStatus_t ProcessRedundantSensors(\n    RedundantSensor_t *sensors,\n    float *output_value\n) {\n    const float TOLERANCE = 0.05f;  \u002F\u002F 5% agreement tolerance\n    const uint32_t FAULT_THRESHOLD = 3;\n\n    \u002F\u002F Range check both sensors\n    if (!RangeCheck(sensors->sensor_a_value, 0.0f, 100.0f)) {\n        sensors->sensor_a_valid = false;\n        sensors->fault_counter_a++;\n    } else {\n        sensors->sensor_a_valid = true;\n    }\n\n    if (!RangeCheck(sensors->sensor_b_value, 0.0f, 100.0f)) {\n        sensors->sensor_b_valid = false;\n        sensors->fault_counter_b++;\n    } else {\n        sensors->sensor_b_valid = true;\n    }\n\n    \u002F\u002F Both sensors valid - check agreement\n    if (sensors->sensor_a_valid && sensors->sensor_b_valid) {\n        float difference = fabsf(sensors->sensor_a_value - sensors->sensor_b_value);\n        float average = (sensors->sensor_a_value + sensors->sensor_b_value) \u002F 2.0f;\n\n        if (difference \u002F average \u003C TOLERANCE) {\n            \u002F\u002F Sensors agree - use average\n            *output_value = average;\n            return VOTER_OUTPUT_VALID;\n        } else {\n            \u002F\u002F Sensors disagree - both might be faulty\n            \u002F\u002F Use most conservative value\n            *output_value = fmaxf(sensors->sensor_a_value, sensors->sensor_b_value);\n            return VOTER_OUTPUT_DEGRADED;\n        }\n    }\n\n    \u002F\u002F Only sensor A valid\n    if (sensors->sensor_a_valid && !sensors->sensor_b_valid) {\n        if (sensors->fault_counter_b \u003C FAULT_THRESHOLD) {\n            *output_value = sensors->sensor_a_value;\n            return VOTER_OUTPUT_DEGRADED;\n        } else {\n            return VOTER_OUTPUT_FAULT;\n        }\n    }\n\n    \u002F\u002F Only sensor B valid\n    if (!sensors->sensor_a_valid && sensors->sensor_b_valid) {\n        if (sensors->fault_counter_a \u003C FAULT_THRESHOLD) {\n            *output_value = sensors->sensor_b_value;\n            return VOTER_OUTPUT_DEGRADED;\n        } else {\n            return VOTER_OUTPUT_FAULT;\n        }\n    }\n\n    \u002F\u002F Both sensors invalid\n    return VOTER_OUTPUT_FAULT;\n}\n```\n\n### 2. Heterogeneous Redundancy\n\n**Different Physical Principles:**\n\n```\n┌────────────┐\n│   Radar    │────┐\n└────────────┘    │     ┌─────────┐      ┌──────────┐\n                  ├────>│ Fusion  │─────>│ Decision │\n┌────────────┐    │     └─────────┘      └──────────┘\n│   Camera   │────┘\n└────────────┘\n```\n\n**Benefits:**\n- Better independence (different failure modes)\n- Common cause failures less likely\n- Easier ASIL decomposition justification\n\n**Example - Vehicle Speed Estimation:**\n```c\n\u002F\u002F Heterogeneous speed measurement\ntypedef struct {\n    float wheel_speed_fl;      \u002F\u002F Front-left wheel speed sensor\n    float wheel_speed_fr;      \u002F\u002F Front-right wheel speed sensor\n    float accelerometer_speed; \u002F\u002F Integrated from accelerometer\n    float gps_speed;           \u002F\u002F GPS-based speed\n} SpeedSources_t;\n\nfloat FuseSpeedMeasurements(SpeedSources_t *sources) {\n    const float WHEEL_WEIGHT = 0.7f;\n    const float ACCEL_WEIGHT = 0.2f;\n    const float GPS_WEIGHT = 0.1f;\n\n    \u002F\u002F Primary: Average of wheel speeds\n    float wheel_speed_avg = (sources->wheel_speed_fl + sources->wheel_speed_fr) \u002F 2.0f;\n\n    \u002F\u002F Plausibility check: compare wheel speed to accelerometer\n    float speed_delta = fabsf(wheel_speed_avg - sources->accelerometer_speed);\n\n    if (speed_delta \u003C 5.0f) {  \u002F\u002F Within 5 km\u002Fh\n        \u002F\u002F All sources agree - weighted fusion\n        float fused_speed = (wheel_speed_avg * WHEEL_WEIGHT) +\n                            (sources->accelerometer_speed * ACCEL_WEIGHT) +\n                            (sources->gps_speed * GPS_WEIGHT);\n        return fused_speed;\n    } else {\n        \u002F\u002F Potential wheel slip - rely more on accelerometer\n        return sources->accelerometer_speed;\n    }\n}\n```\n\n### 3. Dual-Core Lockstep\n\n**Hardware-Level Redundancy:**\n\n```\n┌──────────────┐\n│   Core 0     │──┐\n│ (Leading)    │  │   ┌───────────────┐\n└──────────────┘  ├──>│   Comparator  │──> Fault Signal\n                  │   └───────────────┘\n┌──────────────┐  │\n│   Core 1     │──┘\n│ (Trailing)   │\n└──────────────┘\n```\n\n**Characteristics:**\n- Two CPU cores execute identical instructions\n- Outputs compared cycle-by-cycle\n- Any mismatch triggers fault reaction\n- ASIL-D without software redundancy\n\n**Lockstep Monitor (Conceptual):**\n```c\n\u002F\u002F This is typically implemented in hardware, but shown for understanding\ntypedef struct {\n    uint32_t core0_output;\n    uint32_t core1_output;\n    uint32_t mismatch_counter;\n    bool lockstep_fault;\n} LockstepMonitor_t;\n\nvoid CheckLockstep(LockstepMonitor_t *monitor) {\n    const uint32_t MISMATCH_THRESHOLD = 1;  \u002F\u002F Zero tolerance for lockstep\n\n    if (monitor->core0_output != monitor->core1_output) {\n        monitor->mismatch_counter++;\n\n        if (monitor->mismatch_counter >= MISMATCH_THRESHOLD) {\n            monitor->lockstep_fault = true;\n            \u002F\u002F Trigger immediate safe state\n            EnterSafeState();\n            \u002F\u002F Generate DTC\n            SetDTC(DTC_LOCKSTEP_FAULT);\n            \u002F\u002F Activate warning lamp\n            ActivateWarningLamp(WARNING_LAMP_ENGINE);\n        }\n    } else {\n        \u002F\u002F Reset counter if outputs match\n        monitor->mismatch_counter = 0;\n    }\n}\n```\n\n### 4. 2oo3 Voting (Two-out-of-Three)\n\n**Triple Modular Redundancy:**\n\n```\n┌──────────┐\n│ Channel A│───┐\n└──────────┘   │\n               │    ┌────────────┐      ┌──────────┐\n┌──────────┐   ├───>│ 2oo3 Voter │─────>│ Actuator │\n│ Channel B│───┤    └────────────┘      └──────────┘\n└──────────┘   │\n               │\n┌──────────┐   │\n│ Channel C│───┘\n└──────────┘\n```\n\n**Voter Logic:**\n```c\n\u002F\u002F 2oo3 voting for critical safety function\ntypedef struct {\n    float channel_a;\n    float channel_b;\n    float channel_c;\n    bool channel_a_fault;\n    bool channel_b_fault;\n    bool channel_c_fault;\n} TripleChannels_t;\n\nbool Vote2oo3(TripleChannels_t *channels, float *output) {\n    const float VOTE_TOLERANCE = 0.02f;  \u002F\u002F 2% agreement\n\n    int valid_count = 0;\n    if (!channels->channel_a_fault) valid_count++;\n    if (!channels->channel_b_fault) valid_count++;\n    if (!channels->channel_c_fault) valid_count++;\n\n    \u002F\u002F Need at least 2 valid channels\n    if (valid_count \u003C 2) {\n        return false;\n    }\n\n    \u002F\u002F Check agreement between pairs\n    bool ab_agree = fabsf(channels->channel_a - channels->channel_b) \u002F\n                    channels->channel_a \u003C VOTE_TOLERANCE;\n    bool ac_agree = fabsf(channels->channel_a - channels->channel_c) \u002F\n                    channels->channel_a \u003C VOTE_TOLERANCE;\n    bool bc_agree = fabsf(channels->channel_b - channels->channel_c) \u002F\n                    channels->channel_b \u003C VOTE_TOLERANCE;\n\n    \u002F\u002F A and B agree\n    if (ab_agree && !channels->channel_a_fault && !channels->channel_b_fault) {\n        *output = (channels->channel_a + channels->channel_b) \u002F 2.0f;\n        if (!ac_agree && !channels->channel_c_fault) {\n            \u002F\u002F C is outlier - mark as faulty\n            channels->channel_c_fault = true;\n        }\n        return true;\n    }\n\n    \u002F\u002F A and C agree\n    if (ac_agree && !channels->channel_a_fault && !channels->channel_c_fault) {\n        *output = (channels->channel_a + channels->channel_c) \u002F 2.0f;\n        if (!ab_agree && !channels->channel_b_fault) {\n            channels->channel_b_fault = true;\n        }\n        return true;\n    }\n\n    \u002F\u002F B and C agree\n    if (bc_agree && !channels->channel_b_fault && !channels->channel_c_fault) {\n        *output = (channels->channel_b + channels->channel_c) \u002F 2.0f;\n        if (!ab_agree && !channels->channel_a_fault) {\n            channels->channel_a_fault = true;\n        }\n        return true;\n    }\n\n    \u002F\u002F No agreement among any pair\n    return false;\n}\n```\n\n## Watchdog Mechanisms\n\n### 1. Window Watchdog\n\n**Timing Constraints:**\n```c\n\u002F\u002F Window watchdog - must refresh within time window\ntypedef struct {\n    uint32_t window_min_ms;  \u002F\u002F Minimum time before refresh allowed\n    uint32_t window_max_ms;  \u002F\u002F Maximum time before timeout\n    uint32_t last_refresh_time;\n    bool watchdog_fault;\n} WindowWatchdog_t;\n\nvoid InitWindowWatchdog(WindowWatchdog_t *wdt, uint32_t min_ms, uint32_t max_ms) {\n    wdt->window_min_ms = min_ms;\n    wdt->window_max_ms = max_ms;\n    wdt->last_refresh_time = GetSystemTimeMs();\n    wdt->watchdog_fault = false;\n}\n\nvoid RefreshWindowWatchdog(WindowWatchdog_t *wdt) {\n    uint32_t current_time = GetSystemTimeMs();\n    uint32_t elapsed = current_time - wdt->last_refresh_time;\n\n    \u002F\u002F Check if refresh is too early\n    if (elapsed \u003C wdt->window_min_ms) {\n        wdt->watchdog_fault = true;\n        SetDTC(DTC_WATCHDOG_EARLY_REFRESH);\n        EnterSafeState();\n        return;\n    }\n\n    \u002F\u002F Check if refresh is too late\n    if (elapsed > wdt->window_max_ms) {\n        wdt->watchdog_fault = true;\n        SetDTC(DTC_WATCHDOG_TIMEOUT);\n        EnterSafeState();\n        return;\n    }\n\n    \u002F\u002F Valid refresh - update timestamp\n    wdt->last_refresh_time = current_time;\n    wdt->watchdog_fault = false;\n\n    \u002F\u002F Refresh hardware watchdog\n    HW_WDT_Refresh();\n}\n\n\u002F\u002F Monitor task - checks watchdog status\nvoid WatchdogMonitorTask(void) {\n    WindowWatchdog_t *wdt = GetSystemWatchdog();\n\n    uint32_t current_time = GetSystemTimeMs();\n    uint32_t elapsed = current_time - wdt->last_refresh_time;\n\n    if (elapsed > wdt->window_max_ms) {\n        \u002F\u002F Watchdog expired - enter safe state\n        wdt->watchdog_fault = true;\n        EnterSafeState();\n    }\n}\n```\n\n### 2. Logical Program Flow Monitoring\n\n**Checkpoints and Sequence Validation:**\n\n```c\n\u002F\u002F Program flow monitor - detects unexpected execution paths\ntypedef enum {\n    CHECKPOINT_INIT = 0x01,\n    CHECKPOINT_SENSOR_READ = 0x02,\n    CHECKPOINT_CALCULATION = 0x04,\n    CHECKPOINT_OUTPUT = 0x08,\n    CHECKPOINT_END = 0x10\n} Checkpoint_t;\n\ntypedef struct {\n    uint32_t expected_sequence;\n    uint32_t actual_sequence;\n    uint32_t sequence_errors;\n} ProgramFlowMonitor_t;\n\nstatic ProgramFlowMonitor_t flow_monitor;\n\nvoid InitProgramFlowMonitor(void) {\n    flow_monitor.expected_sequence = CHECKPOINT_INIT |\n                                     CHECKPOINT_SENSOR_READ |\n                                     CHECKPOINT_CALCULATION |\n                                     CHECKPOINT_OUTPUT |\n                                     CHECKPOINT_END;\n    flow_monitor.actual_sequence = 0;\n    flow_monitor.sequence_errors = 0;\n}\n\nvoid RecordCheckpoint(Checkpoint_t checkpoint) {\n    flow_monitor.actual_sequence |= checkpoint;\n}\n\nvoid ValidateProgramFlow(void) {\n    if (flow_monitor.actual_sequence != flow_monitor.expected_sequence) {\n        flow_monitor.sequence_errors++;\n\n        if (flow_monitor.sequence_errors > 3) {\n            SetDTC(DTC_PROGRAM_FLOW_ERROR);\n            EnterSafeState();\n        }\n    } else {\n        \u002F\u002F Reset error counter on successful execution\n        flow_monitor.sequence_errors = 0;\n    }\n\n    \u002F\u002F Reset for next cycle\n    flow_monitor.actual_sequence = 0;\n}\n\n\u002F\u002F Critical function with flow monitoring\nvoid SafetyFunction_Example(void) {\n    RecordCheckpoint(CHECKPOINT_INIT);\n\n    \u002F\u002F Initialize\n    InitializeInputs();\n\n    RecordCheckpoint(CHECKPOINT_SENSOR_READ);\n\n    \u002F\u002F Read sensors\n    float sensor_value = ReadSensor();\n\n    RecordCheckpoint(CHECKPOINT_CALCULATION);\n\n    \u002F\u002F Perform calculation\n    float result = ProcessSensorData(sensor_value);\n\n    RecordCheckpoint(CHECKPOINT_OUTPUT);\n\n    \u002F\u002F Output result\n    WriteActuator(result);\n\n    RecordCheckpoint(CHECKPOINT_END);\n\n    \u002F\u002F Validate execution path\n    ValidateProgramFlow();\n}\n```\n\n## CRC and Checksum Mechanisms\n\n### 1. CRC-16 for Message Integrity\n\n```c\n\u002F\u002F CRC-16-CCITT (polynomial 0x1021)\nuint16_t CalculateCRC16(const uint8_t *data, uint16_t length) {\n    uint16_t crc = 0xFFFF;  \u002F\u002F Initial value\n    const uint16_t polynomial = 0x1021;\n\n    for (uint16_t i = 0; i \u003C length; i++) {\n        crc ^= (uint16_t)(data[i] \u003C\u003C 8);\n\n        for (uint8_t bit = 0; bit \u003C 8; bit++) {\n            if (crc & 0x8000) {\n                crc = (crc \u003C\u003C 1) ^ polynomial;\n            } else {\n                crc \u003C\u003C= 1;\n            }\n        }\n    }\n\n    return crc;\n}\n\n\u002F\u002F CAN message with E2E protection\ntypedef struct {\n    uint32_t message_id;\n    uint8_t data[8];\n    uint8_t data_length;\n    uint16_t crc;\n    uint8_t alive_counter;\n} SafetyMessage_t;\n\nbool ValidateSafetyMessage(SafetyMessage_t *msg) {\n    \u002F\u002F Calculate expected CRC (exclude CRC field itself)\n    uint16_t calculated_crc = CalculateCRC16(msg->data, msg->data_length);\n\n    \u002F\u002F Verify CRC\n    if (calculated_crc != msg->crc) {\n        SetDTC(DTC_CRC_MISMATCH);\n        return false;\n    }\n\n    \u002F\u002F Verify alive counter (detects message loss\u002Frepetition)\n    static uint8_t last_counter[256] = {0};  \u002F\u002F Per message ID\n    uint8_t expected_counter = (last_counter[msg->message_id] + 1) & 0x0F;\n\n    if (msg->alive_counter != expected_counter) {\n        SetDTC(DTC_ALIVE_COUNTER_ERROR);\n        return false;\n    }\n\n    last_counter[msg->message_id] = msg->alive_counter;\n    return true;\n}\n```\n\n### 2. AUTOSAR E2E Protection\n\n```c\n\u002F\u002F AUTOSAR E2E Profile 1 (for 8-byte CAN messages)\ntypedef struct {\n    uint8_t Counter;    \u002F\u002F 4-bit alive counter\n    uint8_t DataID;     \u002F\u002F Data identifier\n    uint16_t CRC;       \u002F\u002F 16-bit CRC\n} E2E_P01_Header_t;\n\ntypedef enum {\n    E2E_P01STATUS_OK,\n    E2E_P01STATUS_NONEWDATA,\n    E2E_P01STATUS_WRONGCRC,\n    E2E_P01STATUS_REPEATED,\n    E2E_P01STATUS_WRONGSEQUENCE\n} E2E_P01Status_t;\n\nE2E_P01Status_t E2E_P01Check(\n    const uint8_t *data,\n    uint8_t length,\n    uint8_t *last_counter\n) {\n    E2E_P01_Header_t *header = (E2E_P01_Header_t *)data;\n\n    \u002F\u002F 1. Verify CRC\n    uint16_t calculated_crc = CalculateCRC16(data + 2, length - 2);\n    if (calculated_crc != header->CRC) {\n        return E2E_P01STATUS_WRONGCRC;\n    }\n\n    \u002F\u002F 2. Check counter sequence\n    uint8_t expected_counter = (*last_counter + 1) & 0x0F;\n    if (header->Counter == *last_counter) {\n        return E2E_P01STATUS_REPEATED;\n    } else if (header->Counter != expected_counter) {\n        return E2E_P01STATUS_WRONGSEQUENCE;\n    }\n\n    \u002F\u002F 3. Update counter\n    *last_counter = header->Counter;\n\n    return E2E_P01STATUS_OK;\n}\n```\n\n## Memory Protection\n\n### 1. RAM Test Patterns\n\n```c\n\u002F\u002F March test for RAM integrity\ntypedef enum {\n    MARCH_TEST_PASS,\n    MARCH_TEST_FAIL_WRITE,\n    MARCH_TEST_FAIL_READ\n} MarchTestResult_t;\n\nMarchTestResult_t MarchTest(volatile uint32_t *ram_start, uint32_t size_words) {\n    uint32_t i;\n\n    \u002F\u002F Phase 1: Write 0 (ascending)\n    for (i = 0; i \u003C size_words; i++) {\n        ram_start[i] = 0x00000000;\n    }\n\n    \u002F\u002F Phase 2: Read 0, Write 1 (ascending)\n    for (i = 0; i \u003C size_words; i++) {\n        if (ram_start[i] != 0x00000000) {\n            return MARCH_TEST_FAIL_READ;\n        }\n        ram_start[i] = 0xFFFFFFFF;\n    }\n\n    \u002F\u002F Phase 3: Read 1, Write 0 (descending)\n    for (i = size_words; i > 0; i--) {\n        if (ram_start[i-1] != 0xFFFFFFFF) {\n            return MARCH_TEST_FAIL_READ;\n        }\n        ram_start[i-1] = 0x00000000;\n    }\n\n    \u002F\u002F Phase 4: Read 0 (descending)\n    for (i = size_words; i > 0; i--) {\n        if (ram_start[i-1] != 0x00000000) {\n            return MARCH_TEST_FAIL_READ;\n        }\n    }\n\n    return MARCH_TEST_PASS;\n}\n\n\u002F\u002F Background RAM test (runs incrementally)\ntypedef struct {\n    uint32_t *ram_start;\n    uint32_t ram_size_words;\n    uint32_t current_block;\n    uint32_t blocks_per_cycle;\n} BackgroundRAMTest_t;\n\nvoid InitBackgroundRAMTest(\n    BackgroundRAMTest_t *test,\n    uint32_t *ram_start,\n    uint32_t size_words,\n    uint32_t blocks_per_cycle\n) {\n    test->ram_start = ram_start;\n    test->ram_size_words = size_words;\n    test->current_block = 0;\n    test->blocks_per_cycle = blocks_per_cycle;\n}\n\nvoid RunBackgroundRAMTestCycle(BackgroundRAMTest_t *test) {\n    uint32_t words_per_block = test->ram_size_words \u002F test->blocks_per_cycle;\n    uint32_t start_offset = test->current_block * words_per_block;\n\n    MarchTestResult_t result = MarchTest(\n        &test->ram_start[start_offset],\n        words_per_block\n    );\n\n    if (result != MARCH_TEST_PASS) {\n        SetDTC(DTC_RAM_TEST_FAILURE);\n        EnterSafeState();\n    }\n\n    \u002F\u002F Move to next block\n    test->current_block = (test->current_block + 1) % test->blocks_per_cycle;\n}\n```\n\n### 2. Stack Overflow Detection\n\n```c\n\u002F\u002F Stack canary pattern\n#define STACK_CANARY_PATTERN 0xDEADBEEF\n\ntypedef struct {\n    uint32_t *stack_start;\n    uint32_t *stack_end;\n    uint32_t canary_value;\n} StackMonitor_t;\n\nvoid InitStackMonitor(\n    StackMonitor_t *monitor,\n    uint32_t *stack_start,\n    uint32_t *stack_end\n) {\n    monitor->stack_start = stack_start;\n    monitor->stack_end = stack_end;\n    monitor->canary_value = STACK_CANARY_PATTERN;\n\n    \u002F\u002F Place canary at stack boundary\n    *stack_end = STACK_CANARY_PATTERN;\n}\n\nbool CheckStackOverflow(StackMonitor_t *monitor) {\n    if (*monitor->stack_end != STACK_CANARY_PATTERN) {\n        SetDTC(DTC_STACK_OVERFLOW);\n        return true;\n    }\n    return false;\n}\n\n\u002F\u002F Call in task or periodic interrupt\nvoid StackMonitorTask(void) {\n    StackMonitor_t *monitor = GetStackMonitor();\n\n    if (CheckStackOverflow(monitor)) {\n        EnterSafeState();\n    }\n}\n```\n\n## Plausibility Checks\n\n### 1. Sensor Range Checks\n\n```c\n\u002F\u002F Multi-level range checking with hysteresis\ntypedef struct {\n    float min_physical;     \u002F\u002F Physical sensor limit\n    float max_physical;\n    float min_operational;  \u002F\u002F Normal operating range\n    float max_operational;\n    float hysteresis;       \u002F\u002F Debounce tolerance\n    uint32_t fault_counter;\n    uint32_t fault_threshold;\n} RangeLimits_t;\n\ntypedef enum {\n    RANGE_VALID,\n    RANGE_WARNING,\n    RANGE_FAULT\n} RangeStatus_t;\n\nRangeStatus_t CheckSensorRange(float value, RangeLimits_t *limits) {\n    \u002F\u002F Check physical limits (hard fault)\n    if (value \u003C limits->min_physical || value > limits->max_physical) {\n        limits->fault_counter++;\n\n        if (limits->fault_counter >= limits->fault_threshold) {\n            SetDTC(DTC_SENSOR_RANGE_PHYSICAL);\n            return RANGE_FAULT;\n        }\n    }\n\n    \u002F\u002F Check operational limits with hysteresis\n    if (value \u003C (limits->min_operational - limits->hysteresis) ||\n        value > (limits->max_operational + limits->hysteresis)) {\n\n        limits->fault_counter++;\n\n        if (limits->fault_counter >= limits->fault_threshold) {\n            SetDTC(DTC_SENSOR_RANGE_OPERATIONAL);\n            return RANGE_WARNING;\n        }\n    } else {\n        \u002F\u002F Value in range - reset counter\n        if (limits->fault_counter > 0) {\n            limits->fault_counter--;\n        }\n    }\n\n    return RANGE_VALID;\n}\n\n\u002F\u002F Example: Battery temperature sensor\nRangeLimits_t battery_temp_limits = {\n    .min_physical = -40.0f,      \u002F\u002F Physical sensor limit\n    .max_physical = 125.0f,\n    .min_operational = -20.0f,   \u002F\u002F Normal operating range\n    .max_operational = 60.0f,\n    .hysteresis = 2.0f,          \u002F\u002F 2°C hysteresis\n    .fault_counter = 0,\n    .fault_threshold = 3         \u002F\u002F 3 consecutive faults\n};\n```\n\n### 2. Signal Gradient Checks\n\n```c\n\u002F\u002F Detect unrealistic rate of change\ntypedef struct {\n    float last_value;\n    uint32_t last_timestamp_ms;\n    float max_gradient;  \u002F\u002F Maximum rate of change per second\n    uint32_t fault_counter;\n} GradientMonitor_t;\n\nbool CheckSignalGradient(\n    float current_value,\n    uint32_t current_timestamp_ms,\n    GradientMonitor_t *monitor\n) {\n    uint32_t delta_time_ms = current_timestamp_ms - monitor->last_timestamp_ms;\n\n    if (delta_time_ms > 0) {\n        float delta_value = current_value - monitor->last_value;\n        float gradient = (delta_value * 1000.0f) \u002F (float)delta_time_ms;  \u002F\u002F per second\n\n        if (fabsf(gradient) > monitor->max_gradient) {\n            monitor->fault_counter++;\n\n            if (monitor->fault_counter >= 3) {\n                SetDTC(DTC_SIGNAL_GRADIENT_FAULT);\n                return false;\n            }\n        } else {\n            monitor->fault_counter = 0;\n        }\n    }\n\n    \u002F\u002F Update history\n    monitor->last_value = current_value;\n    monitor->last_timestamp_ms = current_timestamp_ms;\n\n    return true;\n}\n\n\u002F\u002F Example: Vehicle speed gradient check\nGradientMonitor_t speed_gradient = {\n    .last_value = 0.0f,\n    .last_timestamp_ms = 0,\n    .max_gradient = 10.0f,  \u002F\u002F 10 m\u002Fs² max acceleration\u002Fdeceleration\n    .fault_counter = 0\n};\n```\n\n### 3. Cross-Signal Plausibility\n\n```c\n\u002F\u002F Verify consistency between related signals\ntypedef struct {\n    float wheel_speed_fl;\n    float wheel_speed_fr;\n    float wheel_speed_rl;\n    float wheel_speed_rr;\n    float vehicle_speed;\n    float accelerometer_speed;\n} SpeedPlausibility_t;\n\nbool CheckSpeedPlausibility(SpeedPlausibility_t *speeds) {\n    const float MAX_WHEEL_DELTA = 20.0f;  \u002F\u002F km\u002Fh max difference between wheels\n    const float MAX_ACCEL_DELTA = 10.0f;  \u002F\u002F km\u002Fh max difference with accelerometer\n\n    \u002F\u002F Check consistency between front wheels\n    float fl_fr_delta = fabsf(speeds->wheel_speed_fl - speeds->wheel_speed_fr);\n    if (fl_fr_delta > MAX_WHEEL_DELTA) {\n        SetDTC(DTC_WHEEL_SPEED_IMPLAUSIBLE);\n        return false;\n    }\n\n    \u002F\u002F Check consistency between rear wheels\n    float rl_rr_delta = fabsf(speeds->wheel_speed_rl - speeds->wheel_speed_rr);\n    if (rl_rr_delta > MAX_WHEEL_DELTA) {\n        SetDTC(DTC_WHEEL_SPEED_IMPLAUSIBLE);\n        return false;\n    }\n\n    \u002F\u002F Check vehicle speed vs accelerometer integration\n    float accel_delta = fabsf(speeds->vehicle_speed - speeds->accelerometer_speed);\n    if (accel_delta > MAX_ACCEL_DELTA) {\n        SetDTC(DTC_SPEED_ACCEL_MISMATCH);\n        return false;\n    }\n\n    return true;\n}\n```\n\n## Safe State Management\n\n### 1. Safe State Transition\n\n```c\n\u002F\u002F Safe state state machine\ntypedef enum {\n    STATE_NORMAL_OPERATION,\n    STATE_DEGRADED_MODE,\n    STATE_SAFE_STATE,\n    STATE_EMERGENCY_SHUTDOWN\n} SystemState_t;\n\ntypedef struct {\n    SystemState_t current_state;\n    uint32_t fault_mask;\n    uint32_t warning_mask;\n    uint32_t transition_timestamp;\n    bool safe_state_locked;\n} SafeStateManager_t;\n\nvoid TransitionToSafeState(\n    SafeStateManager_t *manager,\n    uint32_t fault_code\n) {\n    \u002F\u002F Record fault\n    manager->fault_mask |= fault_code;\n    manager->transition_timestamp = GetSystemTimeMs();\n\n    switch (manager->current_state) {\n        case STATE_NORMAL_OPERATION:\n            \u002F\u002F Evaluate severity\n            if (IsCriticalFault(fault_code)) {\n                manager->current_state = STATE_SAFE_STATE;\n                EnterSafeStateActions();\n            } else {\n                manager->current_state = STATE_DEGRADED_MODE;\n                EnterDegradedModeActions();\n            }\n            break;\n\n        case STATE_DEGRADED_MODE:\n            \u002F\u002F Any additional fault → safe state\n            manager->current_state = STATE_SAFE_STATE;\n            EnterSafeStateActions();\n            break;\n\n        case STATE_SAFE_STATE:\n            \u002F\u002F Check if emergency shutdown required\n            if (IsEmergencyCondition(fault_code)) {\n                manager->current_state = STATE_EMERGENCY_SHUTDOWN;\n                EmergencyShutdownActions();\n            }\n            break;\n\n        case STATE_EMERGENCY_SHUTDOWN:\n            \u002F\u002F Terminal state - stay here\n            break;\n    }\n\n    \u002F\u002F Log state transition\n    LogStateTransition(manager->current_state, fault_code);\n\n    \u002F\u002F Activate warning lamp\n    UpdateWarningLamp(manager->current_state);\n\n    \u002F\u002F Store DTC\n    SetDTC(fault_code);\n}\n\nvoid EnterSafeStateActions(void) {\n    \u002F\u002F Disable safety-critical outputs\n    DisableActuators();\n\n    \u002F\u002F Switch to fail-safe values\n    SetFailSafeOutputs();\n\n    \u002F\u002F Maintain basic functions (e.g., manual braking)\n    EnableManualControl();\n\n    \u002F\u002F Activate warning indicators\n    ActivateWarningLamp(WARNING_LAMP_SYSTEM_FAULT);\n\n    \u002F\u002F Log event in NVM\n    StoreEventInNonVolatileMemory();\n\n    \u002F\u002F Notify other ECUs via CAN\n    SendSafeStateNotification();\n}\n```\n\n### 2. Graceful Degradation\n\n```c\n\u002F\u002F Multi-level degradation strategy\ntypedef enum {\n    PERFORMANCE_FULL,        \u002F\u002F 100% capability\n    PERFORMANCE_REDUCED_1,   \u002F\u002F 80% capability\n    PERFORMANCE_REDUCED_2,   \u002F\u002F 50% capability\n    PERFORMANCE_MINIMAL,     \u002F\u002F 20% capability (safety only)\n    PERFORMANCE_DISABLED     \u002F\u002F 0% (safe state)\n} PerformanceLevel_t;\n\ntypedef struct {\n    PerformanceLevel_t current_level;\n    uint32_t redundancy_available;\n    uint32_t faults_detected;\n} DegradationManager_t;\n\nvoid UpdatePerformanceLevel(DegradationManager_t *manager) {\n    \u002F\u002F Determine performance level based on fault state\n    if (manager->faults_detected == 0) {\n        manager->current_level = PERFORMANCE_FULL;\n    } else if (manager->redundancy_available >= 2) {\n        manager->current_level = PERFORMANCE_REDUCED_1;\n    } else if (manager->redundancy_available == 1) {\n        manager->current_level = PERFORMANCE_REDUCED_2;\n    } else if (manager->redundancy_available == 0 && manager->faults_detected == 1) {\n        manager->current_level = PERFORMANCE_MINIMAL;\n    } else {\n        manager->current_level = PERFORMANCE_DISABLED;\n    }\n\n    \u002F\u002F Apply performance limits\n    ApplyPerformanceLimits(manager->current_level);\n\n    \u002F\u002F Notify driver\n    UpdateDriverDisplay(manager->current_level);\n}\n\nvoid ApplyPerformanceLimits(PerformanceLevel_t level) {\n    switch (level) {\n        case PERFORMANCE_FULL:\n            SetMaxTorque(100.0f);  \u002F\u002F 100% torque\n            SetMaxSpeed(200.0f);   \u002F\u002F 200 km\u002Fh\n            break;\n\n        case PERFORMANCE_REDUCED_1:\n            SetMaxTorque(80.0f);   \u002F\u002F 80% torque\n            SetMaxSpeed(160.0f);   \u002F\u002F 160 km\u002Fh\n            break;\n\n        case PERFORMANCE_REDUCED_2:\n            SetMaxTorque(50.0f);   \u002F\u002F 50% torque\n            SetMaxSpeed(100.0f);   \u002F\u002F 100 km\u002Fh\n            break;\n\n        case PERFORMANCE_MINIMAL:\n            SetMaxTorque(20.0f);   \u002F\u002F 20% torque (limp home)\n            SetMaxSpeed(50.0f);    \u002F\u002F 50 km\u002Fh\n            break;\n\n        case PERFORMANCE_DISABLED:\n            SetMaxTorque(0.0f);\n            SetMaxSpeed(0.0f);\n            EnterSafeState();\n            break;\n    }\n}\n```\n\n## Diagnostic Coverage Metrics\n\n### ASIL-D Target Coverage\n\n```c\n\u002F\u002F Diagnostic coverage calculation\ntypedef struct {\n    uint32_t total_failure_modes;\n    uint32_t detected_single_point_faults;\n    uint32_t detected_latent_faults;\n    uint32_t detected_residual_faults;\n} DiagnosticCoverage_t;\n\nfloat CalculateSPFM(DiagnosticCoverage_t *coverage) {\n    \u002F\u002F Single-Point Fault Metric\n    \u002F\u002F ASIL-D target: > 99%\n    return ((float)coverage->detected_single_point_faults \u002F\n            (float)coverage->total_failure_modes) * 100.0f;\n}\n\nfloat CalculateLFM(DiagnosticCoverage_t *coverage) {\n    \u002F\u002F Latent Fault Metric\n    \u002F\u002F ASIL-D target: > 90%\n    return ((float)coverage->detected_latent_faults \u002F\n            (float)coverage->total_failure_modes) * 100.0f;\n}\n```\n\n## Production Checklist\n\n- [ ] Redundancy pattern selected and justified\n- [ ] Diagnostic coverage calculated (SPFM > 99%, LFM > 90% for ASIL-D)\n- [ ] Watchdog configuration verified\n- [ ] CRC\u002Fchecksum implementation validated\n- [ ] Memory protection tested\n- [ ] Plausibility checks defined for all sensors\n- [ ] Safe state defined and tested\n- [ ] FTTI verified through fault injection\n- [ ] Warning lamp activation tested\n- [ ] DTC storage verified\n- [ ] Independent safety assessment completed\n\n## References\n\n- ISO 26262-5:2018 - Hardware Development\n- ISO 26262-6:2018 - Software Development\n- ISO 26262-9:2018 - ASIL-Oriented Analyses\n- IEC 61508 - Functional Safety (general industry)\n- AUTOSAR E2E Protocol Specification\n\n## Related Skills\n\n- ISO 26262 Overview\n- FMEA\u002FFTA Analysis\n- Hardware Safety Requirements\n- Software Safety Requirements\n- Safety Verification and Validation\n\n---\n\n## Safety Verification Validation\n\n# Safety Verification and Validation - ISO 26262\n\nComprehensive guidance on verification and validation per ISO 26262-4, including verification methods, validation test strategies, HIL testing, fault injection, back-to-back testing, traceability matrices, and functional safety assessment.\n\n## Verification vs Validation\n\n### Key Differences\n\n**Verification:** *\"Are we building the product right?\"*\n- Check implementation against requirements\n- Performed at each development level\n- Methods: review, analysis, test\n- Answers: Does code match specification?\n\n**Validation:** *\"Are we building the right product?\"*\n- Check product meets safety goals\n- Performed on integrated system\n- Methods: testing in target environment\n- Answers: Does system prevent hazards?\n\n```\nRequirements → [Verification] → Implementation\n      ↓\nSafety Goals → [Validation] → Final Product\n```\n\n## Verification Methods by ASIL\n\n### ISO 26262-8 Table 4 - Verification Methods\n\n| Method | ASIL A | ASIL B | ASIL C | ASIL D |\n|--------|--------|--------|--------|--------|\n| Walkthrough | + | + | ++ | ++ |\n| Inspection | + | ++ | ++ | +++ |\n| Semi-formal verification | O | + | ++ | ++ |\n| Formal verification | O | O | + | ++ |\n| Control flow analysis | + | ++ | ++ | +++ |\n| Data flow analysis | + | ++ | ++ | +++ |\n| Simulation\u002Fprototyping | ++ | ++ | +++ | +++ |\n| Requirements-based test | ++ | +++ | +++ | +++ |\n| Interface test | ++ | +++ | +++ | +++ |\n| Fault injection test | O | + | ++ | +++ |\n| Resource usage analysis | + | ++ | +++ | +++ |\n| Back-to-back comparison | O | + | ++ | +++ |\n\nLegend: +++ Highly recommended, ++ Recommended, + Optional, O Not recommended\n\n## Requirements Review\n\n### Review Checklist Template\n\n```yaml\nreview_id: \"REV-SWR-ESC-001\"\ndocument: \"Software Safety Requirements v2.5\"\nreview_type: \"Inspection\"\nasil: \"ASIL-D\"\ndate: \"2024-03-19\"\nparticipants:\n  - role: \"Moderator\"\n    name: \"J. Smith\"\n  - role: \"Safety Engineer\"\n    name: \"M. Johnson\"\n  - role: \"Software Architect\"\n    name: \"K. Williams\"\n  - role: \"Test Engineer\"\n    name: \"R. Davis\"\n\nrequirements_quality:\n  - criterion: \"Unambiguous\"\n    check: \"Each requirement has single interpretation\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Testable\"\n    check: \"Verification method defined for each requirement\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Complete\"\n    check: \"All safety goals covered by requirements\"\n    status: \"FAIL\"\n    findings:\n      - finding_id: \"F001\"\n        description: \"SG-ESC-003 (response time) not covered by SWR\"\n        severity: \"Critical\"\n        action: \"Add SWR-ESC-045 for timing requirement\"\n        responsible: \"Software Architect\"\n        due_date: \"2024-03-25\"\n\n  - criterion: \"Consistent\"\n    check: \"No conflicting requirements\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Traceable\"\n    check: \"Links to TSR and safety goals present\"\n    status: \"PASS\"\n    findings: []\n\n  - criterion: \"Feasible\"\n    check: \"Technically achievable with available resources\"\n    status: \"PASS\"\n    findings: []\n\nverification_criteria:\n  - requirement: \"SWR-ESC-001\"\n    method: \"Requirements-based test\"\n    coverage: \"MC\u002FDC\"\n    status: \"Defined\"\n\n  - requirement: \"SWR-ESC-002\"\n    method: \"Fault injection test\"\n    coverage: \"All fault modes\"\n    status: \"Defined\"\n\nsummary:\n  total_requirements: 44\n  passed: 43\n  failed: 1\n  open_findings: 1\n  approval_status: \"CONDITIONAL (pending F001 closure)\"\n\nnext_review: \"After F001 resolved (estimated 2024-03-26)\"\n```\n\n## Static Analysis\n\n### Control Flow Analysis\n\n```c\n\u002F\u002F Example function for control flow analysis\nuint8_t ESC_CalculateControl(float yaw_rate, float lateral_accel) {\n    uint8_t control_level = 0;\n\n    \u002F\u002F Control flow graph:\n    \u002F\u002F     Entry\n    \u002F\u002F       |\n    \u002F\u002F   Check yaw_rate\n    \u002F\u002F     \u002F   \\\n    \u002F\u002F   Yes    No\n    \u002F\u002F    |      |\n    \u002F\u002F Check    Check\n    \u002F\u002F lat_acc  lat_acc\n    \u002F\u002F    |      |\n    \u002F\u002F   Set    Set\n    \u002F\u002F   level  level\n    \u002F\u002F     \\   \u002F\n    \u002F\u002F     Exit\n\n    if (yaw_rate > YAW_THRESHOLD) {\n        if (lateral_accel > ACCEL_THRESHOLD) {\n            control_level = 3;  \u002F\u002F High intervention\n        } else {\n            control_level = 2;  \u002F\u002F Medium intervention\n        }\n    } else {\n        if (lateral_accel > ACCEL_THRESHOLD) {\n            control_level = 1;  \u002F\u002F Low intervention\n        } else {\n            control_level = 0;  \u002F\u002F No intervention\n        }\n    }\n\n    return control_level;  \u002F\u002F Single exit point (MISRA compliant)\n}\n\n\u002F\u002F Static analysis checks:\n\u002F\u002F ✓ No unreachable code\n\u002F\u002F ✓ Single entry, single exit\n\u002F\u002F ✓ All paths return a value\n\u002F\u002F ✓ Cyclomatic complexity: 3 (acceptable for ASIL-D)\n\u002F\u002F ✓ No recursion\n```\n\n### Data Flow Analysis\n\n```c\n\u002F\u002F Data flow analysis example\ntypedef struct {\n    float wheel_speed_fl;      \u002F\u002F Defined at line 5\n    float wheel_speed_fr;      \u002F\u002F Defined at line 6\n    bool valid_fl;             \u002F\u002F Defined at line 7\n    bool valid_fr;             \u002F\u002F Defined at line 8\n} SensorData_t;\n\nvoid ESC_ProcessSensors(SensorData_t *data) {\n    float average_speed;  \u002F\u002F Declared at line 12\n\n    \u002F\u002F Read sensors (define values)\n    data->wheel_speed_fl = ReadSensor(SENSOR_FL);  \u002F\u002F Line 15: Define wheel_speed_fl\n    data->wheel_speed_fr = ReadSensor(SENSOR_FR);  \u002F\u002F Line 16: Define wheel_speed_fr\n\n    \u002F\u002F Validate sensors (define valid flags)\n    data->valid_fl = ValidateSensor(data->wheel_speed_fl);  \u002F\u002F Line 19: Use wheel_speed_fl\n    data->valid_fr = ValidateSensor(data->wheel_speed_fr);  \u002F\u002F Line 20: Use wheel_speed_fr\n\n    \u002F\u002F Calculate average (use values)\n    if (data->valid_fl && data->valid_fr) {  \u002F\u002F Line 23: Use valid_fl, valid_fr\n        average_speed = (data->wheel_speed_fl + data->wheel_speed_fr) \u002F 2.0f;\n        \u002F\u002F Line 24: Use wheel_speed_fl, wheel_speed_fr, Define average_speed\n    }\n\n    \u002F\u002F Use average (line 28: Use average_speed)\n    if (data->valid_fl && data->valid_fr) {  \u002F\u002F Condition ensures average_speed is defined\n        UseAverageSpeed(average_speed);\n    }\n}\n\n\u002F\u002F Data flow analysis results:\n\u002F\u002F ✓ No use before definition (all variables initialized before use)\n\u002F\u002F ✓ No unused variables\n\u002F\u002F ✓ No redundant assignments\n\u002F\u002F ✓ Proper initialization of average_speed before use\n```\n\n## Requirements-Based Testing\n\n### Test Case Template\n\n```yaml\ntest_case_id: \"TC-SWR-ESC-001-001\"\nrequirement: \"SWR-ESC-001.1\"\nrequirement_text: \"Software SHALL reject wheel speed \u003C 0 km\u002Fh\"\ntest_type: \"Unit Test\"\nasil: \"ASIL-D\"\ntest_level: \"Software Unit Testing\"\n\npreconditions:\n  - ESC module initialized\n  - Wheel speed sensor interface configured\n  - No prior faults\n\ntest_inputs:\n  - name: \"wheel_speed_fl\"\n    value: -10.0\n    unit: \"km\u002Fh\"\n  - name: \"sensor_status\"\n    value: \"VALID\"\n\nexpected_outputs:\n  - name: \"validation_result\"\n    value: false\n    description: \"Validation should fail for negative speed\"\n  - name: \"fault_flag\"\n    value: true\n    description: \"Fault flag should be set\"\n  - name: \"dtc_code\"\n    value: \"DTC_WHEEL_SPEED_INVALID\"\n\ntest_procedure:\n  - step: 1\n    action: \"Call ESC_ValidateWheelSpeed(-10.0)\"\n    expected: \"Function returns false\"\n  - step: 2\n    action: \"Check fault flag\"\n    expected: \"Fault flag is set\"\n  - step: 3\n    action: \"Read DTC buffer\"\n    expected: \"DTC_WHEEL_SPEED_INVALID present\"\n\npass_criteria:\n  - All expected outputs match actual outputs\n  - No unexpected side effects\n  - Function executes within timing budget (\u003C 50 μs)\n\nexecution:\n  date: \"2024-03-19\"\n  tester: \"R. Davis\"\n  environment: \"Unit test framework (Unity)\"\n  result: \"PASS\"\n  actual_outputs:\n    validation_result: false\n    fault_flag: true\n    dtc_code: \"DTC_WHEEL_SPEED_INVALID\"\n  execution_time_us: 12\n  notes: \"Test passed on first attempt\"\n\ncoverage:\n  line_coverage: 100%\n  branch_coverage: 100%\n  mcdc_coverage: 100%\n```\n\n## Fault Injection Testing\n\n### Hardware Fault Injection\n\n```c\n\u002F\u002F Fault injection framework\ntypedef enum {\n    FAULT_NONE,\n    FAULT_SENSOR_STUCK_HIGH,\n    FAULT_SENSOR_STUCK_LOW,\n    FAULT_SENSOR_NOISE,\n    FAULT_SENSOR_DROPOUT,\n    FAULT_BIT_FLIP,\n    FAULT_TIMING_VIOLATION\n} FaultType_t;\n\ntypedef struct {\n    FaultType_t fault_type;\n    uint32_t injection_time_ms;\n    uint32_t duration_ms;\n    void *target_address;\n    uint32_t fault_mask;\n} FaultInjectionConfig_t;\n\n\u002F\u002F Inject sensor stuck-high fault\nvoid InjectFault_SensorStuckHigh(void) {\n    FaultInjectionConfig_t config = {\n        .fault_type = FAULT_SENSOR_STUCK_HIGH,\n        .injection_time_ms = 1000,  \u002F\u002F Inject after 1 second\n        .duration_ms = 500,          \u002F\u002F Fault persists for 500ms\n        .target_address = &wheel_speed_fl_raw,\n        .fault_mask = 0xFFFFFFFF     \u002F\u002F Maximum value\n    };\n\n    \u002F\u002F Configure fault injection hardware (e.g., FPGA, fault injection tool)\n    ConfigureFaultInjection(&config);\n}\n\n\u002F\u002F Test: Verify safe state transition on persistent sensor fault\nvoid Test_SafeState_PersistentSensorFault(void) {\n    \u002F\u002F 1. Initialize system\n    ESC_Init();\n    assert(ESC_GetMode() == ESC_MODE_NORMAL);\n\n    \u002F\u002F 2. Inject stuck-high fault on wheel speed sensor\n    InjectFault_SensorStuckHigh();\n\n    \u002F\u002F 3. Run for fault duration\n    for (uint32_t t = 0; t \u003C 600; t += 10) {  \u002F\u002F 600ms\n        ESC_MainFunction();  \u002F\u002F 10ms periodic task\n        Delay_ms(10);\n    }\n\n    \u002F\u002F 4. Verify safe state entered\n    assert(ESC_GetMode() == ESC_MODE_SAFE_STATE);\n\n    \u002F\u002F 5. Verify warning lamp activated\n    assert(GetWarningLampStatus() == WARNING_LAMP_ON);\n\n    \u002F\u002F 6. Verify DTC stored\n    assert(IsDTCStored(DTC_WHEEL_SPEED_FAULT));\n\n    \u002F\u002F 7. Verify transition time within FTTI\n    uint32_t transition_time = GetSafeStateTransitionTime_ms();\n    assert(transition_time \u003C= 150);  \u002F\u002F FTTI requirement\n\n    printf(\"✓ Safe state test PASS (transition time: %u ms)\\n\", transition_time);\n}\n```\n\n### Software Fault Injection (Mutation Testing)\n\n```python\n# Mutation testing for safety mechanisms\nimport subprocess\nimport re\n\nclass MutationTester:\n    def __init__(self, source_file, test_executable):\n        self.source_file = source_file\n        self.test_executable = test_executable\n        self.mutations = []\n\n    def generate_mutations(self):\n        \"\"\"Generate mutations of source code\"\"\"\n        with open(self.source_file, 'r') as f:\n            original_code = f.read()\n\n        # Mutation 1: Change comparison operators\n        mutations = [\n            (r'>', '>='),    # > to >=\n            (r'\u003C', '\u003C='),    # \u003C to \u003C=\n            (r'==', '!='),   # == to !=\n            (r'&&', '||'),   # && to ||\n        ]\n\n        for i, (pattern, replacement) in enumerate(mutations):\n            mutated_code = re.sub(pattern, replacement, original_code, count=1)\n            self.mutations.append({\n                'id': f'MUT-{i+1}',\n                'description': f'Change {pattern} to {replacement}',\n                'code': mutated_code\n            })\n\n    def run_mutation_test(self, mutation):\n        \"\"\"Run tests against mutated code\"\"\"\n        # Write mutated code to file\n        with open(self.source_file, 'w') as f:\n            f.write(mutation['code'])\n\n        # Recompile\n        compile_result = subprocess.run(['make', 'clean', 'all'],\n                                       capture_output=True)\n\n        # Run tests\n        test_result = subprocess.run([self.test_executable],\n                                     capture_output=True)\n\n        # Mutation killed if tests fail\n        killed = (test_result.returncode != 0)\n\n        return killed\n\n    def analyze_coverage(self):\n        \"\"\"Analyze mutation test coverage\"\"\"\n        total = len(self.mutations)\n        killed = sum(1 for m in self.mutations if self.run_mutation_test(m))\n\n        mutation_score = (killed \u002F total) * 100\n        print(f\"Mutation Score: {mutation_score:.1f}%\")\n        print(f\"Mutations Killed: {killed}\u002F{total}\")\n\n        # ASIL-D target: > 95% mutation score\n        if mutation_score > 95:\n            print(\"✓ Mutation testing PASS\")\n        else:\n            print(\"✗ Mutation testing FAIL (target: > 95%)\")\n\n        return mutation_score\n\n# Example usage\ntester = MutationTester('esc_safety.c', '.\u002Ftest_esc')\ntester.generate_mutations()\ntester.analyze_coverage()\n```\n\n## HIL (Hardware-in-Loop) Testing\n\n### HIL Test Setup\n\n```\n┌─────────────────────────────────────────────────────────┐\n│                   HIL Test System                       │\n│                                                         │\n│  ┌──────────────┐         ┌──────────────┐            │\n│  │   Real-Time  │         │  Vehicle     │            │\n│  │   Simulator  │◄───────►│  Dynamics    │            │\n│  │   (dSPACE)   │         │  Model       │            │\n│  └──────┬───────┘         └──────────────┘            │\n│         │                                              │\n│         │ CAN\u002FLIN\u002FEthernet                             │\n│         │                                              │\n│  ┌──────▼───────┐         ┌──────────────┐            │\n│  │   ESC ECU    │◄───────►│  Fault       │            │\n│  │   (Real HW)  │         │  Injection   │            │\n│  └──────┬───────┘         └──────────────┘            │\n│         │                                              │\n│         │ Actuator Outputs                             │\n│         │                                              │\n│  ┌──────▼───────┐         ┌──────────────┐            │\n│  │   Brake      │         │  Test        │            │\n│  │   Simulator  │◄───────►│  Automation  │            │\n│  └──────────────┘         └──────────────┘            │\n└─────────────────────────────────────────────────────────┘\n```\n\n### HIL Test Script (Python + dSPACE)\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"\nHIL Test: ESC Safety Goal Verification\nTest: SG-ESC-001 - Prevent unintended ESC activation\n\"\"\"\n\nimport dspace\nimport time\nimport numpy as np\n\nclass HILTest_ESC:\n    def __init__(self):\n        self.ds = dspace.HILSystem('10.0.0.100')  # dSPACE IP\n        self.test_results = []\n\n    def setup(self):\n        \"\"\"Initialize HIL system\"\"\"\n        # Load vehicle dynamics model\n        self.ds.load_model('vehicle_dynamics_sedan_2024.sdf')\n\n        # Configure CAN interface\n        self.ds.configure_can(channel=1, baudrate=500000)\n\n        # Reset ECU\n        self.ds.reset_ecu()\n        time.sleep(1)\n\n        # Set initial conditions\n        self.ds.set_variable('VehicleSpeed', 100.0)  # km\u002Fh\n        self.ds.set_variable('RoadFriction', 0.8)    # Dry road\n        self.ds.set_variable('SteeringAngle', 0.0)   # Straight\n\n    def test_no_intervention_straight_driving(self):\n        \"\"\"Verify ESC does not activate during normal straight driving\"\"\"\n        print(\"Test: No intervention during straight driving...\")\n\n        # Run simulation for 30 seconds\n        self.ds.start_simulation()\n\n        for t in np.arange(0, 30, 0.01):  # 10ms steps\n            # Maintain steady state\n            self.ds.set_variable('SteeringAngle', 0.0)\n            self.ds.set_variable('VehicleSpeed', 100.0)\n\n            # Read ESC status\n            esc_active = self.ds.get_can_signal('ESC_Status', 'ESC_Active')\n\n            # Verify ESC not active\n            if esc_active:\n                print(f\"✗ FAIL: Unintended ESC activation at t={t:.2f}s\")\n                self.test_results.append({\n                    'test': 'No_Intervention_Straight',\n                    'result': 'FAIL',\n                    'time': t\n                })\n                self.ds.stop_simulation()\n                return False\n\n            time.sleep(0.01)\n\n        self.ds.stop_simulation()\n        print(\"✓ PASS: No unintended activation\")\n        self.test_results.append({\n            'test': 'No_Intervention_Straight',\n            'result': 'PASS'\n        })\n        return True\n\n    def test_intervention_oversteer(self):\n        \"\"\"Verify ESC activates during oversteer condition\"\"\"\n        print(\"Test: ESC activation during oversteer...\")\n\n        self.ds.start_simulation()\n\n        # Create oversteer condition\n        self.ds.set_variable('VehicleSpeed', 100.0)\n        self.ds.set_variable('RoadFriction', 0.3)  # Wet road\n\n        # Sudden steering input\n        for t in np.arange(0, 2, 0.01):\n            self.ds.set_variable('SteeringAngle', 45.0)  # Sharp turn\n\n            # Monitor vehicle dynamics\n            yaw_rate = self.ds.get_variable('YawRate')\n            lateral_accel = self.ds.get_variable('LateralAccel')\n            esc_active = self.ds.get_can_signal('ESC_Status', 'ESC_Active')\n\n            # Check if ESC activates\n            if yaw_rate > 15.0 and not esc_active:\n                # Vehicle is oversteering but ESC not active\n                if t > 0.15:  # Allow for FTTI (150ms)\n                    print(f\"✗ FAIL: ESC did not activate (t={t:.2f}s, yaw={yaw_rate:.1f}°\u002Fs)\")\n                    self.test_results.append({\n                        'test': 'Intervention_Oversteer',\n                        'result': 'FAIL',\n                        'reason': 'No activation during oversteer'\n                    })\n                    self.ds.stop_simulation()\n                    return False\n\n            if esc_active:\n                print(f\"✓ PASS: ESC activated at t={t:.2f}s\")\n                self.test_results.append({\n                    'test': 'Intervention_Oversteer',\n                    'result': 'PASS',\n                    'activation_time': t\n                })\n                self.ds.stop_simulation()\n                return True\n\n            time.sleep(0.01)\n\n        print(\"✗ FAIL: ESC never activated\")\n        self.test_results.append({\n            'test': 'Intervention_Oversteer',\n            'result': 'FAIL',\n            'reason': 'No activation'\n        })\n        self.ds.stop_simulation()\n        return False\n\n    def test_safe_state_sensor_fault(self):\n        \"\"\"Verify safe state transition on sensor fault\"\"\"\n        print(\"Test: Safe state on sensor fault...\")\n\n        self.ds.start_simulation()\n\n        # Inject sensor fault\n        self.ds.inject_fault('WheelSpeed_FL', fault_type='stuck_high')\n\n        start_time = time.time()\n        safe_state_entered = False\n\n        for t in np.arange(0, 1, 0.01):\n            # Read ECU status\n            operating_mode = self.ds.get_can_signal('ESC_Status', 'OperatingMode')\n\n            if operating_mode == 3:  # Safe state\n                transition_time = (time.time() - start_time) * 1000  # ms\n                print(f\"✓ PASS: Safe state entered in {transition_time:.1f}ms\")\n\n                # Verify FTTI requirement\n                if transition_time \u003C= 150:\n                    print(f\"✓ PASS: FTTI requirement met ({transition_time:.1f}ms \u003C= 150ms)\")\n                    self.test_results.append({\n                        'test': 'Safe_State_Sensor_Fault',\n                        'result': 'PASS',\n                        'ftti_ms': transition_time\n                    })\n                else:\n                    print(f\"✗ FAIL: FTTI exceeded ({transition_time:.1f}ms > 150ms)\")\n                    self.test_results.append({\n                        'test': 'Safe_State_Sensor_Fault',\n                        'result': 'FAIL',\n                        'reason': 'FTTI exceeded'\n                    })\n\n                safe_state_entered = True\n                break\n\n            time.sleep(0.01)\n\n        self.ds.stop_simulation()\n        self.ds.clear_faults()\n\n        if not safe_state_entered:\n            print(\"✗ FAIL: Safe state not entered\")\n            self.test_results.append({\n                'test': 'Safe_State_Sensor_Fault',\n                'result': 'FAIL',\n                'reason': 'No safe state transition'\n            })\n            return False\n\n        return True\n\n    def generate_report(self):\n        \"\"\"Generate test report\"\"\"\n        print(\"\\n\" + \"=\"*60)\n        print(\"HIL Test Report - ESC Safety Verification\")\n        print(\"=\"*60)\n\n        total = len(self.test_results)\n        passed = sum(1 for r in self.test_results if r['result'] == 'PASS')\n\n        print(f\"\\nTotal Tests: {total}\")\n        print(f\"Passed: {passed}\")\n        print(f\"Failed: {total - passed}\")\n        print(f\"Pass Rate: {(passed\u002Ftotal)*100:.1f}%\\n\")\n\n        for result in self.test_results:\n            status = \"✓\" if result['result'] == 'PASS' else \"✗\"\n            print(f\"{status} {result['test']}: {result['result']}\")\n\n        return passed == total\n\n    def run_all_tests(self):\n        \"\"\"Execute all HIL tests\"\"\"\n        self.setup()\n\n        tests = [\n            self.test_no_intervention_straight_driving,\n            self.test_intervention_oversteer,\n            self.test_safe_state_sensor_fault\n        ]\n\n        for test in tests:\n            test()\n            time.sleep(2)  # Delay between tests\n\n        return self.generate_report()\n\n\nif __name__ == \"__main__\":\n    hil_test = HILTest_ESC()\n    all_passed = hil_test.run_all_tests()\n\n    if all_passed:\n        print(\"\\n✓ All HIL tests PASSED\")\n        exit(0)\n    else:\n        print(\"\\n✗ Some HIL tests FAILED\")\n        exit(1)\n```\n\n## Back-to-Back Testing\n\n### Model-Code Comparison\n\n```matlab\n% MATLAB\u002FSimulink reference model\n% ESC_ReferenceModel.m\n\nfunction [control_level] = ESC_ReferenceModel(yaw_rate, lateral_accel)\n    % Reference implementation in MATLAB\n    YAW_THRESHOLD = 15.0;      % deg\u002Fs\n    ACCEL_THRESHOLD = 0.4;     % g\n\n    if yaw_rate > YAW_THRESHOLD\n        if lateral_accel > ACCEL_THRESHOLD\n            control_level = 3;\n        else\n            control_level = 2;\n        end\n    else\n        if lateral_accel > ACCEL_THRESHOLD\n            control_level = 1;\n        else\n            control_level = 0;\n        end\n    end\nend\n\n% Back-to-back test vectors\ntest_vectors = [\n    % yaw_rate, lateral_accel, expected_output\n    0.0, 0.0, 0;     % No intervention\n    20.0, 0.2, 2;    % High yaw, low accel\n    10.0, 0.5, 1;    % Low yaw, high accel\n    20.0, 0.5, 3;    % High yaw, high accel\n    15.0, 0.4, 2;    % Boundary values\n];\n\n% Run reference model\nfprintf('Back-to-Back Test Results:\\n');\nfprintf('%-10s %-15s %-10s %-10s %-10s\\n', 'Test', 'Inputs', 'Model', 'Code', 'Status');\n\nfor i = 1:size(test_vectors, 1)\n    yaw = test_vectors(i, 1);\n    accel = test_vectors(i, 2);\n    expected = test_vectors(i, 3);\n\n    % Run MATLAB model\n    model_output = ESC_ReferenceModel(yaw, accel);\n\n    % Run C code (via MEX or external call)\n    code_output = ESC_CalculateControl_C(yaw, accel);\n\n    % Compare outputs\n    if model_output == code_output && model_output == expected\n        status = 'PASS';\n    else\n        status = 'FAIL';\n    end\n\n    fprintf('TC-%d     (%.1f, %.1f)    %d          %d         %s\\n', ...\n            i, yaw, accel, model_output, code_output, status);\nend\n```\n\n## Traceability Matrix\n\n### Requirements Traceability\n\n```sql\n-- Traceability database schema\nCREATE TABLE SafetyGoals (\n    sg_id VARCHAR(50) PRIMARY KEY,\n    description TEXT,\n    asil VARCHAR(10),\n    ftti_ms INT\n);\n\nCREATE TABLE FunctionalSafetyRequirements (\n    fsr_id VARCHAR(50) PRIMARY KEY,\n    sg_id VARCHAR(50) REFERENCES SafetyGoals(sg_id),\n    description TEXT\n);\n\nCREATE TABLE TechnicalSafetyRequirements (\n    tsr_id VARCHAR(50) PRIMARY KEY,\n    fsr_id VARCHAR(50) REFERENCES FunctionalSafetyRequirements(fsr_id),\n    description TEXT\n);\n\nCREATE TABLE SoftwareSafetyRequirements (\n    swr_id VARCHAR(50) PRIMARY KEY,\n    tsr_id VARCHAR(50) REFERENCES TechnicalSafetyRequirements(tsr_id),\n    description TEXT,\n    verification_method VARCHAR(100)\n);\n\nCREATE TABLE TestCases (\n    tc_id VARCHAR(50) PRIMARY KEY,\n    swr_id VARCHAR(50) REFERENCES SoftwareSafetyRequirements(swr_id),\n    test_type VARCHAR(50),\n    status VARCHAR(20),\n    result VARCHAR(20)\n);\n\n-- Query: Generate traceability matrix\nSELECT\n    sg.sg_id,\n    sg.description AS safety_goal,\n    fsr.fsr_id,\n    tsr.tsr_id,\n    swr.swr_id,\n    tc.tc_id,\n    tc.result\nFROM SafetyGoals sg\nLEFT JOIN FunctionalSafetyRequirements fsr ON sg.sg_id = fsr.sg_id\nLEFT JOIN TechnicalSafetyRequirements tsr ON fsr.fsr_id = tsr.fsr_id\nLEFT JOIN SoftwareSafetyRequirements swr ON tsr.tsr_id = swr.tsr_id\nLEFT JOIN TestCases tc ON swr.swr_id = tc.swr_id\nWHERE sg.sg_id = 'SG-ESC-001'\nORDER BY sg.sg_id, fsr.fsr_id, tsr.tsr_id, swr.swr_id;\n```\n\n## Functional Safety Assessment\n\n### Assessment Checklist\n\n```yaml\nassessment_id: \"FSA-ESC-ECU-001\"\nitem: \"ESC Electronic Control Unit\"\nasil: \"ASIL-D\"\nassessment_type: \"Independent Safety Assessment\"\nassessor: \"TÜV SÜD\"\ndate: \"2024-03-19\"\n\npart_2_management:\n  - criterion: \"Safety lifecycle defined\"\n    status: \"COMPLIANT\"\n    evidence: \"SAF-001: Safety Plan v1.5\"\n\n  - criterion: \"Safety manager appointed\"\n    status: \"COMPLIANT\"\n    evidence: \"Org chart, training records\"\n\n  - criterion: \"Safety culture established\"\n    status: \"COMPLIANT\"\n    evidence: \"Safety culture assessment report\"\n\npart_3_concept:\n  - criterion: \"Item definition complete\"\n    status: \"COMPLIANT\"\n    evidence: \"ITEM-ESC-001: Item Definition v2.0\"\n\n  - criterion: \"HARA performed\"\n    status: \"COMPLIANT\"\n    evidence: \"HARA-ESC-001: 15 hazardous events analyzed\"\n\n  - criterion: \"Safety goals defined\"\n    status: \"COMPLIANT\"\n    evidence: \"3 safety goals (ASIL-D, C, B)\"\n\npart_4_system:\n  - criterion: \"Technical safety concept\"\n    status: \"COMPLIANT\"\n    evidence: \"TSC-ESC-001: TSC v1.8\"\n\n  - criterion: \"System architecture\"\n    status: \"COMPLIANT\"\n    evidence: \"ARCH-ESC-001: Architecture spec\"\n\n  - criterion: \"Safety analysis (FMEA)\"\n    status: \"COMPLIANT\"\n    evidence: \"FMEA-ESC-HW-001, FMEA-ESC-SW-001\"\n\npart_5_hardware:\n  - criterion: \"Hardware safety requirements\"\n    status: \"COMPLIANT\"\n    evidence: \"HSR-ESC-001: 25 requirements\"\n\n  - criterion: \"SPFM\u002FLFM\u002FPMHF calculated\"\n    status: \"COMPLIANT\"\n    evidence: \"FMEDA-ESC-001: SPFM=99.2%, LFM=92.5%, PMHF=8.5 FIT\"\n\n  - criterion: \"Hardware metrics meet targets\"\n    status: \"COMPLIANT\"\n    evidence: \"All metrics within ASIL-D targets\"\n\npart_6_software:\n  - criterion: \"Software safety requirements\"\n    status: \"COMPLIANT\"\n    evidence: \"SWR-ESC-001: 44 requirements\"\n\n  - criterion: \"MISRA compliance\"\n    status: \"COMPLIANT\"\n    evidence: \"Static analysis: 0 violations\"\n\n  - criterion: \"Unit test MC\u002FDC coverage\"\n    status: \"COMPLIANT\"\n    evidence: \"Coverage report: 100% MC\u002FDC\"\n\n  - criterion: \"Software safety manual\"\n    status: \"COMPLIANT\"\n    evidence: \"SSM-ESC-001: SW Safety Manual v1.0\"\n\npart_8_supporting:\n  - criterion: \"Configuration management\"\n    status: \"COMPLIANT\"\n    evidence: \"Git repository, version control procedures\"\n\n  - criterion: \"Tool qualification\"\n    status: \"COMPLIANT\"\n    evidence: \"Compiler (GCC-ARM), Static analyzer (PC-Lint) qualified\"\n\n  - criterion: \"Documentation\"\n    status: \"COMPLIANT\"\n    evidence: \"All work products present and reviewed\"\n\nverification_validation:\n  - criterion: \"Verification plan executed\"\n    status: \"COMPLIANT\"\n    evidence: \"VER-PLAN-ESC-001: All activities complete\"\n\n  - criterion: \"Validation testing performed\"\n    status: \"COMPLIANT\"\n    evidence: \"VAL-REPORT-ESC-001: HIL testing 1000 hours\"\n\n  - criterion: \"Safety goals validated\"\n    status: \"COMPLIANT\"\n    evidence: \"All 3 safety goals verified in target environment\"\n\nfindings:\n  - finding_id: \"FSA-001\"\n    category: \"Observation\"\n    description: \"Traceability links between TSR and SWR could be improved\"\n    severity: \"Minor\"\n    recommendation: \"Add automated traceability tool\"\n    status: \"Open\"\n\n  - finding_id: \"FSA-002\"\n    category: \"Observation\"\n    description: \"Field monitoring process not fully defined\"\n    severity: \"Minor\"\n    recommendation: \"Document field data collection procedures\"\n    status: \"Open\"\n\nconclusion:\n  overall_assessment: \"POSITIVE\"\n  recommendation: \"Release for production\"\n  conditions:\n    - \"Address findings FSA-001 and FSA-002 before SOP\"\n    - \"Maintain configuration management during production\"\n  next_assessment: \"After 1 year of production (field monitoring review)\"\n```\n\n## Production Checklist\n\n### Verification & Validation Sign-Off\n\n- [ ] Requirements reviews completed (all levels)\n- [ ] Design reviews completed (all levels)\n- [ ] Static analysis performed (0 critical violations)\n- [ ] Unit testing completed (100% MC\u002FDC for ASIL-D)\n- [ ] Integration testing completed (all interfaces)\n- [ ] System testing completed (all requirements)\n- [ ] HIL testing completed (> 1000 hours for ASIL-D)\n- [ ] Fault injection testing completed\n- [ ] Back-to-back testing completed (model vs code)\n- [ ] Traceability matrix complete (SG → TC)\n- [ ] Safety analysis verified (FMEA\u002FFTA)\n- [ ] Hardware metrics verified (SPFM\u002FLFM\u002FPMHF)\n- [ ] Safety manual reviewed and approved\n- [ ] Independent safety assessment passed\n- [ ] Release for production authorized\n\n## References\n\n- ISO 26262-4:2018 - Product Development at System Level\n- ISO 26262-8:2018 - Supporting Processes (Verification)\n- ISO 26262-11:2018 - Semiconductors (Validation)\n- dSPACE HIL Testing Guide\n- AUTOSAR Methodology\n- Mutation Testing Handbook\n\n## Related Skills\n\n- ISO 26262 Overview\n- FMEA\u002FFTA Analysis\n- Software Safety Requirements\n- Safety Mechanisms and Patterns\n- Hardware Safety Requirements\n\n---\n\n## Software Safety Requirements\n\n# Software Safety Requirements - ISO 26262 Part 6\n\nComprehensive guidance on ASIL-D software development per ISO 26262-6, including safety requirements specification, architectural design, unit implementation, MISRA C\u002FC++ compliance, MC\u002FDC testing, and software safety manual creation.\n\n## Software Development V-Model\n\n```\n┌────────────────────────────────────────────────────────────┐\n│         Software Safety Requirements (Part 6-6)            │\n│  • Derived from Technical Safety Concept                   │\n│  • ASIL classification                                     │\n│  • Verification criteria                                   │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Architectural Design (Part 6-7)           │\n│  • Hierarchical structure                                  │\n│  • Component interfaces                                    │\n│  • Resource constraints                                    │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Unit Design (Part 6-8)                    │\n│  • Detailed design per unit                                │\n│  • Algorithms and data structures                          │\n│  • Static analysis                                         │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Unit Implementation (Part 6-9)            │\n│  • Coding per MISRA guidelines                             │\n│  • Code reviews                                            │\n│  • Static analysis                                         │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Unit Testing (Part 6-10)                  │\n│  • MC\u002FDC coverage (ASIL-D)                                 │\n│  • Requirements-based tests                                │\n│  • Back-to-back testing                                    │\n└───────────────┬────────────────────────────────────────────┘\n                │\n                ▼\n┌────────────────────────────────────────────────────────────┐\n│         Software Integration Testing (Part 6-11)           │\n│  • Interface testing                                       │\n│  • Resource usage verification                             │\n│  • Fault injection                                         │\n└────────────────────────────────────────────────────────────┘\n```\n\n## Software Safety Requirements\n\n### Requirement Structure\n\n**Good Safety Requirement (SMART):**\n- **Specific**: Unambiguous, single interpretation\n- **Measurable**: Testable\u002Fverifiable\n- **Achievable**: Technically feasible\n- **Relevant**: Traceable to safety goal\n- **Time-bound**: Response time specified\n\n**Example Requirements:**\n\n```yaml\nswr_id: \"SWR-ESC-001\"\ntitle: \"Wheel Speed Sensor Range Check\"\nderived_from: \"TSR-ESC-001\"  # Technical Safety Requirement\nasil: \"ASIL-D\"\nsafety_goal: \"SG-ESC-001 (Prevent unintended ESC activation)\"\n\ndescription: |\n  The software shall validate that each wheel speed sensor value is within\n  the physically possible range before using it in vehicle dynamics calculations.\n\nprecondition: \"Wheel speed sensor data received via CAN\"\n\nrequirements:\n  - id: \"SWR-ESC-001.1\"\n    text: \"The software SHALL reject wheel speed values \u003C 0 km\u002Fh\"\n    rationale: \"Negative speed is physically impossible\"\n    verification: \"Unit test with negative input\"\n\n  - id: \"SWR-ESC-001.2\"\n    text: \"The software SHALL reject wheel speed values > 350 km\u002Fh\"\n    rationale: \"Exceeds maximum vehicle speed by 50% margin\"\n    verification: \"Unit test with excessive input\"\n\n  - id: \"SWR-ESC-001.3\"\n    text: \"The software SHALL set a fault flag if invalid speed detected\"\n    rationale: \"Enable diagnostic monitoring\"\n    verification: \"Verify flag state after invalid input\"\n\n  - id: \"SWR-ESC-001.4\"\n    text: \"The software SHALL use last valid speed value if current invalid\"\n    rationale: \"Maintain functionality while rejecting invalid data\"\n    verification: \"Integration test with fault injection\"\n\n  - id: \"SWR-ESC-001.5\"\n    text: \"The software SHALL transition to safe state if > 3 consecutive invalid readings\"\n    rationale: \"Persistent fault indicates sensor failure\"\n    verification: \"System test with sustained fault\"\n\ntiming:\n  execution_time_max_us: 50\n  deadline_ms: 10\n  period_ms: 10\n\nsafety_mechanism: \"SM-ESC-004 (Range Check)\"\ninterfaces:\n  input: \"CAN message ESC_WheelSpeeds (ID 0x200)\"\n  output: \"Internal variable wheel_speed_fl_valid\"\n\nverification_methods:\n  - Requirements-based test\n  - Boundary value analysis\n  - Fault injection test\n  - MC\u002FDC coverage\n\nacceptance_criteria:\n  - All requirements verified with tests\n  - MC\u002FDC coverage >= 100%\n  - Static analysis: 0 violations\n  - Code review: approved\n```\n\n### Requirements Traceability\n\n```\nSafety Goal (SG)\n    │\n    ├─> Functional Safety Requirement (FSR)\n    │       │\n    │       ├─> Technical Safety Requirement (TSR)\n    │       │       │\n    │       │       ├─> Software Safety Requirement (SWR)\n    │       │       │       │\n    │       │       │       ├─> Software Unit (SW-U)\n    │       │       │       │       │\n    │       │       │       │       └─> Unit Test Case (UTC)\n    │       │       │       │\n    │       │       │       └─> Integration Test Case (ITC)\n    │       │       │\n    │       │       └─> System Test Case (STC)\n    │       │\n    │       └─> Validation Test Case (VTC)\n```\n\n## Software Architecture\n\n### ASIL-D Architecture Patterns\n\n**1. Freedom from Interference**\n\n```c\n\u002F\u002F Memory partitioning for ASIL-D\ntypedef struct {\n    \u002F\u002F ASIL-D partition (protected)\n    uint8_t safety_data[1024] __attribute__((section(\".safety_ram\")));\n\n    \u002F\u002F QM partition (separate)\n    uint8_t qm_data[4096] __attribute__((section(\".qm_ram\")));\n} MemoryPartitions_t;\n\n\u002F\u002F MPU configuration (ARM Cortex-M)\nvoid ConfigureMemoryProtection(void) {\n    \u002F\u002F Region 0: Safety-critical code (read-only, execute)\n    MPU->RBAR = SAFETY_CODE_BASE | MPU_REGION_VALID | 0;\n    MPU->RASR = MPU_RASR_ENABLE | MPU_RASR_XN_DISABLE |\n                MPU_RASR_AP_RO | MPU_SIZE_64KB;\n\n    \u002F\u002F Region 1: Safety-critical data (read-write, no execute)\n    MPU->RBAR = SAFETY_DATA_BASE | MPU_REGION_VALID | 1;\n    MPU->RASR = MPU_RASR_ENABLE | MPU_RASR_XN_ENABLE |\n                MPU_RASR_AP_RW | MPU_SIZE_16KB;\n\n    \u002F\u002F Region 2: QM code (separate partition)\n    MPU->RBAR = QM_CODE_BASE | MPU_REGION_VALID | 2;\n    MPU->RASR = MPU_RASR_ENABLE | MPU_RASR_XN_DISABLE |\n                MPU_RASR_AP_RO | MPU_SIZE_128KB;\n\n    \u002F\u002F Enable MPU\n    MPU->CTRL = MPU_CTRL_ENABLE | MPU_CTRL_PRIVDEFENA;\n}\n```\n\n**2. Timing and Scheduling**\n\n```c\n\u002F\u002F ASIL-D task configuration (AUTOSAR OS)\nTASK(SafetyCriticalTask) {\n    const uint32_t WCET_US = 500;  \u002F\u002F Worst-Case Execution Time\n    const uint32_t DEADLINE_MS = 10;\n\n    uint32_t start_time = GetTimestamp_us();\n\n    \u002F\u002F Execute safety-critical function\n    ESC_SafetyFunction();\n\n    uint32_t execution_time = GetTimestamp_us() - start_time;\n\n    \u002F\u002F Verify timing constraints\n    if (execution_time > WCET_US) {\n        SetDTC(DTC_TIMING_VIOLATION);\n        EnterSafeState();\n    }\n\n    TerminateTask();\n}\n\n\u002F\u002F Task scheduling configuration\nconst TaskConfigType SafetyCriticalTaskConfig = {\n    .priority = 255,  \u002F\u002F Highest priority\n    .activation = PERIODIC,\n    .period_ms = 10,\n    .deadline_ms = 10,\n    .stack_size = 2048,\n    .partition = SAFETY_PARTITION\n};\n```\n\n**3. Software Component Structure**\n\n```c\n\u002F\u002F Software component interface (AUTOSAR SWC)\ntypedef struct {\n    \u002F\u002F Inputs (ports)\n    float wheel_speed_fl;\n    float wheel_speed_fr;\n    float wheel_speed_rl;\n    float wheel_speed_rr;\n    float yaw_rate;\n    float lateral_accel;\n\n    \u002F\u002F Outputs (ports)\n    float brake_pressure_fl;\n    float brake_pressure_fr;\n    float brake_pressure_rl;\n    float brake_pressure_rr;\n    bool esc_active;\n\n    \u002F\u002F Mode management\n    ESC_ModeType operating_mode;\n\n    \u002F\u002F Fault status\n    uint32_t fault_flags;\n} ESC_Component_t;\n\n\u002F\u002F Runnable function\nvoid ESC_MainFunction(void) {\n    ESC_Component_t *component = GetESCComponent();\n\n    \u002F\u002F 1. Input validation\n    if (!ValidateInputs(component)) {\n        component->operating_mode = ESC_MODE_SAFE_STATE;\n        SetSafeOutputs(component);\n        return;\n    }\n\n    \u002F\u002F 2. Mode management\n    switch (component->operating_mode) {\n        case ESC_MODE_NORMAL:\n            ESC_NormalOperation(component);\n            break;\n\n        case ESC_MODE_DEGRADED:\n            ESC_DegradedOperation(component);\n            break;\n\n        case ESC_MODE_SAFE_STATE:\n            ESC_SafeState(component);\n            break;\n\n        default:\n            \u002F\u002F Invalid mode - enter safe state\n            component->operating_mode = ESC_MODE_SAFE_STATE;\n            SetDTC(DTC_INVALID_MODE);\n            break;\n    }\n\n    \u002F\u002F 3. Output validation\n    ValidateOutputs(component);\n}\n```\n\n## MISRA C\u002FC++ Compliance\n\n### MISRA C:2012 Critical Rules for ASIL-D\n\n**Mandatory Rules (Must follow):**\n\n```c\n\u002F\u002F Rule 1.3: No undefined behavior\n\u002F\u002F BAD: Integer overflow undefined\nint32_t bad_add(int32_t a, int32_t b) {\n    return a + b;  \u002F\u002F ✗ May overflow\n}\n\n\u002F\u002F GOOD: Check for overflow\nint32_t safe_add(int32_t a, int32_t b, bool *overflow) {\n    if ((b > 0) && (a > (INT32_MAX - b))) {\n        *overflow = true;\n        return INT32_MAX;\n    }\n    if ((b \u003C 0) && (a \u003C (INT32_MIN - b))) {\n        *overflow = true;\n        return INT32_MIN;\n    }\n    *overflow = false;\n    return a + b;\n}\n\n\u002F\u002F Rule 2.2: Dead code shall be removed\n\u002F\u002F BAD: Unreachable code\nvoid bad_function(bool condition) {\n    if (condition) {\n        return;\n    }\n    DoSomething();  \u002F\u002F ✗ Dead code if condition always true\n    return;\n}\n\n\u002F\u002F GOOD: No dead code\nvoid good_function(bool condition) {\n    if (!condition) {\n        DoSomething();\n    }\n}\n\n\u002F\u002F Rule 8.13: Pointer should be const if not modified\n\u002F\u002F BAD: Missing const\nvoid bad_process(uint8_t *data) {  \u002F\u002F ✗ data not modified but not const\n    uint8_t value = data[0];\n    UseValue(value);\n}\n\n\u002F\u002F GOOD: Const pointer\nvoid good_process(const uint8_t *data) {\n    uint8_t value = data[0];\n    UseValue(value);\n}\n\n\u002F\u002F Rule 9.1: Use before initialization\n\u002F\u002F BAD: Uninitialized variable\nvoid bad_init(void) {\n    uint32_t value;\n    if (SomeCondition()) {\n        value = 42;\n    }\n    UseValue(value);  \u002F\u002F ✗ May be uninitialized\n}\n\n\u002F\u002F GOOD: Always initialized\nvoid good_init(void) {\n    uint32_t value = 0;  \u002F\u002F Default initialization\n    if (SomeCondition()) {\n        value = 42;\n    }\n    UseValue(value);\n}\n\n\u002F\u002F Rule 21.3: malloc\u002Ffree shall not be used\n\u002F\u002F BAD: Dynamic memory\nvoid bad_alloc(void) {\n    uint8_t *buffer = (uint8_t *)malloc(100);  \u002F\u002F ✗ Not allowed\n    free(buffer);\n}\n\n\u002F\u002F GOOD: Static allocation\n#define BUFFER_SIZE 100\nvoid good_alloc(void) {\n    uint8_t buffer[BUFFER_SIZE];  \u002F\u002F Static allocation\n    ProcessBuffer(buffer, BUFFER_SIZE);\n}\n```\n\n### MISRA C++ Specific Rules\n\n```cpp\n\u002F\u002F Rule A5-1-2: Use nullptr instead of NULL\n\u002F\u002F BAD: NULL macro\nvoid bad_pointer(void) {\n    int *ptr = NULL;  \u002F\u002F ✗ Old C style\n}\n\n\u002F\u002F GOOD: nullptr\nvoid good_pointer(void) {\n    int *ptr = nullptr;  \u002F\u002F ✓ C++11 style\n}\n\n\u002F\u002F Rule A10-0-2: Virtual destructor for base class\n\u002F\u002F BAD: Missing virtual destructor\nclass BadBase {  \u002F\u002F ✗ No virtual destructor\npublic:\n    void DoSomething();\n};\n\n\u002F\u002F GOOD: Virtual destructor\nclass GoodBase {\npublic:\n    virtual ~GoodBase() = default;  \u002F\u002F ✓ Virtual destructor\n    virtual void DoSomething();\n};\n\n\u002F\u002F Rule A15-5-1: Exception specifications\n\u002F\u002F BAD: Throwing exceptions in safety code\nvoid bad_exception(void) {\n    throw std::runtime_error(\"Error\");  \u002F\u002F ✗ Exceptions not allowed ASIL-D\n}\n\n\u002F\u002F GOOD: Error codes\nenum class ErrorCode {\n    SUCCESS,\n    INVALID_INPUT,\n    TIMEOUT\n};\n\nErrorCode good_error_handling(void) {\n    if (InvalidInput()) {\n        return ErrorCode::INVALID_INPUT;\n    }\n    return ErrorCode::SUCCESS;\n}\n```\n\n### Static Analysis Configuration\n\n**.misra_config.txt (for PC-Lint\u002FFlexelint):**\n```\n\u002F\u002F MISRA C:2012 rules for ASIL-D\n+misra(2012)\n\n\u002F\u002F Mandatory rules\n-strong(AXJ)  \u002F\u002F All rules from Advisory to Required to Mandatory\n\n\u002F\u002F Specific rule configuration\n-esym(960, 1.3)   \u002F\u002F Enable: No undefined behavior\n-esym(960, 2.2)   \u002F\u002F Enable: No dead code\n-esym(960, 8.13)  \u002F\u002F Enable: Pointer to const\n-esym(960, 9.1)   \u002F\u002F Enable: No uninitialized variables\n-esym(960, 21.3)  \u002F\u002F Enable: No dynamic memory\n\n\u002F\u002F Project-specific deviations (requires justification)\n-elib(960)        \u002F\u002F Suppress for library code\n```\n\n## Unit Testing - MC\u002FDC Coverage\n\n### Modified Condition\u002FDecision Coverage (MC\u002FDC)\n\n**Definition:** Every condition in a decision independently affects the outcome.\n\n**Example:**\n\n```c\n\u002F\u002F Function to test\nbool ESC_ShouldActivate(float yaw_rate, float lateral_accel, bool driver_input) {\n    \u002F\u002F Decision with 3 conditions (A, B, C)\n    if ((yaw_rate > THRESHOLD_YAW) &&        \u002F\u002F Condition A\n        (lateral_accel > THRESHOLD_ACCEL) && \u002F\u002F Condition B\n        (!driver_input))                     \u002F\u002F Condition C\n    {\n        return true;\n    }\n    return false;\n}\n\n\u002F\u002F MC\u002FDC Test Cases\nvoid test_mcdc_coverage(void) {\n    \u002F\u002F Truth table with MC\u002FDC coverage\n    \u002F\u002F TC | A | B | C | Result | Covers\n    \u002F\u002F ---+---+---+---+--------+--------\n    \u002F\u002F  1 | F | F | F |   F    | -\n    \u002F\u002F  2 | T | F | F |   F    | A (vs TC4)\n    \u002F\u002F  3 | F | T | F |   F    | B (vs TC4)\n    \u002F\u002F  4 | T | T | F |   T    | baseline\n    \u002F\u002F  5 | T | T | T |   F    | C (vs TC4)\n\n    \u002F\u002F Test Case 1: All false\n    assert(ESC_ShouldActivate(0.0, 0.0, false) == false);\n\n    \u002F\u002F Test Case 2: Only A true (tests A independence)\n    assert(ESC_ShouldActivate(10.0, 0.0, false) == false);\n\n    \u002F\u002F Test Case 3: Only B true (tests B independence)\n    assert(ESC_ShouldActivate(0.0, 10.0, false) == false);\n\n    \u002F\u002F Test Case 4: A and B true, C false (baseline true)\n    assert(ESC_ShouldActivate(10.0, 10.0, false) == true);\n\n    \u002F\u002F Test Case 5: All true but C negated (tests C independence)\n    assert(ESC_ShouldActivate(10.0, 10.0, true) == false);\n\n    \u002F\u002F MC\u002FDC coverage: 100% ✓\n}\n```\n\n### Unit Test Framework (Unity)\n\n```c\n\u002F\u002F test_esc_range_check.c\n#include \"unity.h\"\n#include \"esc_sensor.h\"\n\nvoid setUp(void) {\n    \u002F\u002F Called before each test\n    ESC_Init();\n}\n\nvoid tearDown(void) {\n    \u002F\u002F Called after each test\n    ESC_Deinit();\n}\n\n\u002F\u002F Test: Valid speed accepted\nvoid test_valid_speed_accepted(void) {\n    float speed = 100.0f;  \u002F\u002F Valid: 0-350 km\u002Fh\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(result);\n}\n\n\u002F\u002F Test: Negative speed rejected\nvoid test_negative_speed_rejected(void) {\n    float speed = -10.0f;  \u002F\u002F Invalid: \u003C 0\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_FALSE(result);\n}\n\n\u002F\u002F Test: Excessive speed rejected\nvoid test_excessive_speed_rejected(void) {\n    float speed = 400.0f;  \u002F\u002F Invalid: > 350\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_FALSE(result);\n}\n\n\u002F\u002F Test: Boundary value (low)\nvoid test_boundary_low(void) {\n    float speed = 0.0f;  \u002F\u002F Boundary: exactly 0\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(result);\n}\n\n\u002F\u002F Test: Boundary value (high)\nvoid test_boundary_high(void) {\n    float speed = 350.0f;  \u002F\u002F Boundary: exactly max\n    bool result = ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(result);\n}\n\n\u002F\u002F Test: Fault flag set on invalid input\nvoid test_fault_flag_on_invalid(void) {\n    float speed = -10.0f;\n    ESC_ValidateWheelSpeed(speed);\n    TEST_ASSERT_TRUE(ESC_IsFaultFlagSet(FAULT_WHEEL_SPEED_INVALID));\n}\n\n\u002F\u002F Test: Safe state after persistent faults\nvoid test_safe_state_persistent_fault(void) {\n    \u002F\u002F Inject 4 consecutive invalid readings\n    for (int i = 0; i \u003C 4; i++) {\n        ESC_ValidateWheelSpeed(-10.0f);\n    }\n    TEST_ASSERT_EQUAL(ESC_MODE_SAFE_STATE, ESC_GetMode());\n}\n\nint main(void) {\n    UNITY_BEGIN();\n    RUN_TEST(test_valid_speed_accepted);\n    RUN_TEST(test_negative_speed_rejected);\n    RUN_TEST(test_excessive_speed_rejected);\n    RUN_TEST(test_boundary_low);\n    RUN_TEST(test_boundary_high);\n    RUN_TEST(test_fault_flag_on_invalid);\n    RUN_TEST(test_safe_state_persistent_fault);\n    return UNITY_END();\n}\n```\n\n### Coverage Report\n\n```bash\n# Run tests with coverage (gcov\u002Flcov)\ngcc -fprofile-arcs -ftest-coverage -o test_esc test_esc.c esc_sensor.c\n.\u002Ftest_esc\nlcov --capture --directory . --output-file coverage.info\ngenhtml coverage.info --output-directory coverage_html\n\n# Coverage report:\n# File: esc_sensor.c\n# Lines: 98.5% (65\u002F66)\n# Functions: 100% (8\u002F8)\n# Branches: 100% (24\u002F24)  ← MC\u002FDC coverage\n# MC\u002FDC: 100% ✓ (ASIL-D requirement met)\n```\n\n## Software Safety Manual\n\n### Template\n\n```markdown\n# Software Safety Manual\n# ESC Electronic Control Unit\n# Version 1.0\n# ASIL-D\n\n## 1. Introduction\n\n### 1.1 Scope\nThis Software Safety Manual describes the safety-related aspects of the\nESC (Electronic Stability Control) ECU software version 2.5.0, developed\nin accordance with ISO 26262-6:2018 for ASIL-D integrity level.\n\n### 1.2 Intended Use\nThe software is designed for use in passenger vehicles (M1 category) with:\n- Maximum gross weight: 3500 kg\n- Maximum speed: 200 km\u002Fh\n- Operating temperature: -40°C to +85°C\n\n## 2. Safety Concept\n\n### 2.1 Safety Goals\n- SG-ESC-001: Prevent unintended ESC activation (ASIL-D)\n- SG-ESC-002: ESC shall activate when stability compromised (ASIL-C)\n- SG-ESC-003: ESC response time \u003C 100ms (ASIL-B)\n\n### 2.2 Software Safety Requirements\nSee Section 5 for complete list (45 requirements, all verified).\n\n## 3. Assumptions and Dependencies\n\n### 3.1 Hardware Assumptions\n- Dual-core lockstep microcontroller (TMS570LC4357)\n- ECC-protected RAM (SECDED capable)\n- Watchdog timer with window monitoring\n- CAN controller with error detection\n\n### 3.2 Integration Assumptions\n- CAN bus operates at 500 kbps\n- Wheel speed sensors provide updates every 10ms\n- Supply voltage: 9V to 16V nominal\n\n### 3.3 Environmental Assumptions\n- Road surface friction coefficient: 0.1 to 1.0\n- Vehicle speed: 0 to 200 km\u002Fh\n- Tire pressure: 1.8 to 3.0 bar\n\n## 4. Safety Mechanisms\n\n### 4.1 Implemented Safety Mechanisms\n| ID | Description | Coverage |\n|----|-------------|----------|\n| SM-ESC-001 | Dual-core lockstep | 99.9% |\n| SM-ESC-002 | ECC on RAM | 99.99% |\n| SM-ESC-003 | Window watchdog | 95.0% |\n| SM-ESC-004 | Range checks | 90.0% |\n| SM-ESC-005 | CRC on CAN | 99.998% |\n\n### 4.2 Diagnostic Coverage\n- SPFM: 99.2% (target: > 99%) ✓\n- LFM: 92.5% (target: > 90%) ✓\n- PMHF: 8.5 FIT (target: \u003C 10 FIT) ✓\n\n## 5. Known Limitations\n\n### 5.1 Functional Limitations\n- ESC disabled when vehicle speed \u003C 10 km\u002Fh\n- ESC functionality reduced with 1 failed wheel speed sensor\n- ESC deactivated in reverse gear\n\n### 5.2 Performance Limitations\n- Maximum yaw rate: ±100°\u002Fs\n- Maximum lateral acceleration: ±1.5g\n- Response time: 50-100ms (depends on sensor update rate)\n\n## 6. Safe States\n\n### 6.1 Safe State Definition\n- All brake modulation disabled\n- Manual brake control available\n- Warning lamp activated\n- DTC stored in non-volatile memory\n\n### 6.2 Transition Conditions\n- Lockstep mismatch detected\n- Persistent sensor failure (> 3 consecutive)\n- Watchdog timeout\n- Critical software error detected\n\n## 7. Integration Guidelines\n\n### 7.1 Configuration Parameters\n```c\n#define ESC_YAW_THRESHOLD_DEG_S     (15.0f)\n#define ESC_LATERAL_ACCEL_THRESHOLD_G (0.4f)\n#define ESC_FTTI_MS                 (150)\n#define ESC_SENSOR_TIMEOUT_MS       (100)\n```\n\n### 7.2 Calibration Requirements\n- Parameters must be calibrated for specific vehicle platform\n- Validation testing required after calibration changes\n- Safety-critical parameters protected by CRC\n\n## 8. Verification Evidence\n\n### 8.1 Testing Summary\n- Unit tests: 487 test cases, 100% MC\u002FDC coverage\n- Integration tests: 125 test cases, all passed\n- System tests: 45 test cases, all passed\n- HIL testing: 1000 hours, 0 safety-critical failures\n\n### 8.2 Static Analysis\n- MISRA C:2012 compliance: 100% (0 deviations)\n- Cyclomatic complexity: Max 8 (target: \u003C 10)\n- Code review: All modules approved\n\n## 9. Maintenance and Support\n\n### 9.1 Software Updates\n- Updates require full regression testing\n- Safety assessment required for any safety-critical change\n- Version control: Git with signed commits\n\n### 9.2 Field Monitoring\n- DTC monitoring via diagnostic interface\n- Software version readable via OBD-II\n- Field failure data collection mandatory\n\n## 10. References\n- ISO 26262-6:2018 - Software Development\n- MISRA C:2012 - Guidelines for C\n- ESC_SWR_v2.5.pdf - Software Safety Requirements\n- ESC_TestReport_v2.5.pdf - Verification Report\n```\n\n## Production Checklist\n\n### ASIL-D Software Development\n\n- [ ] Software safety requirements defined and reviewed\n- [ ] Architecture designed with freedom from interference\n- [ ] MISRA C\u002FC++ compliance verified (100%)\n- [ ] Static analysis performed (0 critical violations)\n- [ ] Unit tests achieve MC\u002FDC coverage (100%)\n- [ ] Integration tests cover all interfaces\n- [ ] Timing analysis performed (WCET verified)\n- [ ] Memory usage analyzed (stack\u002Fheap within limits)\n- [ ] Code reviews completed (all units)\n- [ ] Back-to-back testing (model vs code) performed\n- [ ] Software safety manual completed\n- [ ] Tool qualification performed (compiler, static analyzer)\n- [ ] Configuration management in place\n- [ ] Independent software assessment passed\n\n## References\n\n- ISO 26262-6:2018 - Product Development at Software Level\n- ISO 26262-8:2018 - Supporting Processes\n- MISRA C:2012 - Guidelines for the Use of C\n- MISRA C++:2008 - Guidelines for C++\n- AUTOSAR Coding Guidelines\n- DO-178C - Software Considerations in Airborne Systems (reference)\n\n## Related Skills\n\n- ISO 26262 Overview\n- Safety Mechanisms and Patterns\n- FMEA\u002FFTA Analysis\n- Safety Verification and Validation\n- MISRA C Coding Guidelines\n",{"name":5,"tags":23,"description":25},[24,5],"automotive","Automotive Safety expertise. Covers 6 topics: Fmea Fta Analysis, Hazard Analysis Risk Assessment, Iso 26262 Overview, Safety Mechanisms Patterns, Safety Verification Validation.\n","main","764e05645935fe0d4c219ab3786883289700a063","skills\u002Fautomotive-safety",3,"https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025","2026-05-19 20:41:59",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-safety",{"tool":39,"command":40},"bunx","bunx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-safety",{"tool":42,"command":43},"pnpm","pnpm dlx skills add pangzhenying2025\u002Fhermes-automotive-skills --skill automotive-safety","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fautomotive-safety\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":18},"01M7360ZT6X73B7WX8G9T42MRX","china-sotif","China standard: Sotif. # 中国 SOTIF 标准集 — GB\u002FT 43267 + CSAE 316.1\u002F316.2 + CSAE 336","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-sotif\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7360VT7N20KBKD59QG6BEVQ","china-scenario-safety","China standard: Scenario Safety. # 场景安全评估框架 — ISO 34501\u002F34502 + ISO 34503\u002F34504\u002F34505","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-scenario-safety\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":18},"01M7360SM9DD8BAECKC7C03ST1","china-odd","China standard: Odd. # 自动驾驶系统设计运行条件（ODD）标准","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-odd\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M7360QDGZAFVAJ2M2BQY5AAS","china-multi-pillar","China standard: Multi Pillar. # \"多支柱\"标准综合应用指南","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-multi-pillar\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7360N6FMFHK17MH5MB96R9Z","china-l3-fusa-sotif","China standard: L3 Fusa Sotif. # L3 有条件自动驾驶系统 功能安全和预期功能安全技术要求","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-l3-fusa-sotif\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7360J517TM1JC1YS6M2YX38","china-l2-adas-safety","China standard: L2 Adas Safety. # L2 组合驾驶辅助系统安全要求（强制性国标草案）","https:\u002F\u002Fgithub.com\u002Fpangzhenying2025\u002Fhermes-automotive-skills\u002Fblob\u002Fmain\u002Fskills\u002Fchina-l2-adas-safety\u002FSKILL.md",[],[]]